Skip to content

Commit

Permalink
fix checking auth cookie, add logs
Browse files Browse the repository at this point in the history
  • Loading branch information
nightlord189 committed Jan 28, 2024
1 parent a607d5b commit 2c6a2f6
Show file tree
Hide file tree
Showing 8 changed files with 63 additions and 8 deletions.
4 changes: 2 additions & 2 deletions internal/docker/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ package docker
import (
"context"
"fmt"
"github.com/rs/zerolog/log"
"strings"

"github.com/docker/docker/api/types"
"github.com/rs/zerolog"
)

func (a *Adapter) Run(ctx context.Context) {
Expand All @@ -20,7 +20,7 @@ func (a *Adapter) GetAliveContainers(ctx context.Context) ([]string, error) {
All: true,
})
if err != nil {
zerolog.Ctx(ctx).Err(err).Msg("get containers error")
log.Ctx(ctx).Err(err).Msg("GetAliveContainers: get containers error")
return nil, fmt.Errorf("get containers error: %w", err)
}
result := make([]string, 0, len(containers))
Expand Down
2 changes: 1 addition & 1 deletion internal/docker/logs.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ func (a *Adapter) update(ctx context.Context) {
All: true,
})
if err != nil {
zerolog.Ctx(ctx).Err(err).Msg("get containers error")
zerolog.Ctx(ctx).Err(err).Msg("docker.update: get containers error")
return
}

Expand Down
9 changes: 8 additions & 1 deletion internal/handler/auth.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package handler

import (
"github.com/rs/zerolog/log"
"net/http"

"github.com/gin-contrib/sessions"
Expand All @@ -25,24 +26,30 @@ const (
// @Router /api/auth [Post]
// @BasePath /
func (h *Handler) Auth(c *gin.Context) {
ctx := c.Request.Context()

var req AuthRequest
if err := c.ShouldBindJSON(&req); err != nil {
log.Ctx(ctx).Error().Msgf("auth: parse json error: %v", err)
c.JSON(http.StatusBadRequest, GenericError("parse json error: "+err.Error()))
return
}

if req.Username != defaultUser || req.Password != h.Config.Auth.Password {
log.Ctx(ctx).Error().Msgf("auth: bad credentials: %s", req.Username)
c.JSON(http.StatusUnauthorized, GenericError("bad credentials"))
return
}

session := sessions.Default(c)
session.Set(userKey, defaultUser)
session.Set(userKey, req.Username)

if err := session.Save(); err != nil {
log.Ctx(ctx).Error().Msgf("auth: save session error: %v", err)
c.JSON(http.StatusInternalServerError, GenericError("save session error: "+err.Error()))
return
}

log.Ctx(ctx).Info().Msgf("auth: authenticated user %s", req.Username)
c.JSON(http.StatusOK, GenericError("authenticated"))
}
2 changes: 1 addition & 1 deletion internal/handler/container.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import (
func (h *Handler) GetContainers(c *gin.Context) {
containers, err := h.Usecase.GetContainers(c.Request.Context())
if err != nil {
log.Ctx(c.Request.Context()).Err(err).Msg("get containers error")
log.Ctx(c.Request.Context()).Err(err).Msg("getContainers api: get containers error")
c.JSON(http.StatusInternalServerError, GenericError(err.Error()))
}
c.JSON(http.StatusOK, GetContainersResponse{Containers: containers})
Expand Down
14 changes: 14 additions & 0 deletions internal/handler/mdw.go
Original file line number Diff line number Diff line change
@@ -1,19 +1,33 @@
package handler

import (
"github.com/rs/zerolog/log"
"net/http"

"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
)

func (h *Handler) CookieAuthMdw(c *gin.Context) {
ctx := c.Request.Context()

session := sessions.Default(c)
user := session.Get(userKey)

if user != defaultUser {
log.Ctx(ctx).Error().Msgf("user from cookie is %s, invalid cookie, aborting", user)

session.Delete(userKey)

if err := session.Save(); err != nil {
log.Ctx(ctx).Error().Msgf("CookieAuthMdw: save session error: %v", err)
}

c.JSON(http.StatusUnauthorized, GenericError("invalid cookie"))

c.Abort()
return
}

c.Next()
}
11 changes: 10 additions & 1 deletion static/web/js/logs.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ async function setCurrentContainer (newVal) {

window.onload = function() {
if (!isAuthorized()) {
console.log('user is not authorized');
console.log('logs: user is not authorized, redirecting to auth page');
window.location.href = '/';
}
};
Expand Down Expand Up @@ -98,6 +98,9 @@ async function updateContainers () {
if (resp.status <= 299) {
console.log('success get containers');
renderContainers(respJson.containers);
} else if (resp.status === 401) {
console.log('401, redirecting to auth page')
logout()
} else {
const errorMessage = respJson.message || 'Something went wrong';
console.log(errorMessage);
Expand Down Expand Up @@ -182,6 +185,9 @@ async function getLogs (dir, cursor) {
console.log(`got logs for container ${currentContainer} cursor ${cursor}`);

return respJson;
} else if (resp.status === 401) {
console.log('401, redirecting to auth page')
logout()
} else {
const errorMessage = respJson.message || 'Something went wrong';
console.log(errorMessage);
Expand All @@ -206,6 +212,9 @@ async function search (contains) {
if (resp.status <= 299) {
console.log('success search');
renderLogs(respJson.records, appendValues.NONE, 'Not found', contains);
} else if (resp.status === 401) {
console.log('401, redirecting to auth page')
logout()
} else {
const errorMessage = respJson.message || 'Something went wrong';
console.log(errorMessage);
Expand Down
27 changes: 26 additions & 1 deletion static/web/js/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,33 @@ function arraysOfObjectsAreEqual(arr1, arr2) {
return true;
}

function getCookie(cookieKey) {
// Split the cookies string into an array of individual cookies
const cookiesArray = document.cookie.split('; ');

// Iterate over each cookie to find the one with the specified key
for (const cookie of cookiesArray) {
const [key, value] = cookie.split('=');

// Trim any leading or trailing spaces
const trimmedKey = key.trim();

// Check if the current cookie's key matches the specified key
if (trimmedKey === cookieKey) {
// Return the corresponding value
return decodeURIComponent(value);
}
}

// Return null if the cookie with the specified key is not found
return null;
}

function isAuthorized () {
return document.cookie.startsWith('default=') && document.cookie !== 'default='
//console.log('raw cookie: ', document.cookie)
const defaultCookie = getCookie('default')
//console.log('defaultCookie: ', defaultCookie)
return defaultCookie !== null && defaultCookie.trim() !== ''
}

function logout () {
Expand Down
2 changes: 1 addition & 1 deletion static/web/js/triggers.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
window.onload = function() {
if (!isAuthorized()) {
console.log('user is not authorized');
console.log('triggers: user is not authorized, redirecting to auth page');
window.location.href = '/';
}
};
Expand Down

0 comments on commit 2c6a2f6

Please sign in to comment.