From a7fb54eeb726d5107357f6277361437c2e858d1d Mon Sep 17 00:00:00 2001 From: qowevisa Date: Wed, 6 Nov 2024 19:47:40 +0200 Subject: [PATCH] Change auth middleware to be session based on cookies --- middleware/auth.go | 31 ++++++++++++++----------------- 1 file changed, 14 insertions(+), 17 deletions(-) diff --git a/middleware/auth.go b/middleware/auth.go index 43cc2c2..416f68d 100644 --- a/middleware/auth.go +++ b/middleware/auth.go @@ -1,8 +1,11 @@ package middleware import ( - "strings" + "errors" + "log" + "net/http" + "git.qowevisa.me/Qowevisa/fin-check-api/consts" "git.qowevisa.me/Qowevisa/fin-check-api/tokens" "git.qowevisa.me/Qowevisa/fin-check-api/types" "github.com/gin-gonic/gin" @@ -11,31 +14,25 @@ import ( // Passes UserID with `c.Set("UserID")` as it gets id from token func AuthMiddleware() gin.HandlerFunc { return func(c *gin.Context) { - authHeader := c.GetHeader("Authorization") - if authHeader == "" { - c.JSON(401, types.ErrorResponse{Message: "Authorization header is required"}) + token, err := c.Cookie(consts.COOKIE_SESSION) + if errors.Is(err, http.ErrNoCookie) { + c.JSON(401, types.ErrorResponse{Message: "Authorization cookie is required"}) c.Abort() return } - - token := authHeader - if strings.Index(token, "Bearer ") == 0 { - token = strings.Split(token, " ")[1] - } - - if !tokens.AmIAllowed(token) { - c.JSON(401, types.ErrorResponse{Message: "Token is invalid"}) + if !tokens.ValidateSessionToken(token) { + c.JSON(401, types.ErrorResponse{Message: "Invalid authorization cookie"}) c.Abort() return } - - if userID, err := tokens.GetID(token); err != nil { - c.JSON(401, types.ErrorResponse{Message: "Token is invalid ERR4001"}) + session, err := tokens.GetSession(token) + if err != nil { + log.Printf("ERROR: tokens.GetSession: %v\n", err) + c.JSON(500, types.ErrorResponse{Message: "Server error"}) c.Abort() return - } else { - c.Set("UserID", userID) } + c.Set("UserID", session.UserID) c.Next() }