Change auth middleware to be session based on cookies

This commit is contained in:
qowevisa 2024-11-06 19:47:40 +02:00
parent 06e0a2d7ec
commit a7fb54eeb7

View File

@ -1,8 +1,11 @@
package middleware package middleware
import ( 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/tokens"
"git.qowevisa.me/Qowevisa/fin-check-api/types" "git.qowevisa.me/Qowevisa/fin-check-api/types"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
@ -11,31 +14,25 @@ import (
// Passes UserID with `c.Set("UserID")` as it gets id from token // Passes UserID with `c.Set("UserID")` as it gets id from token
func AuthMiddleware() gin.HandlerFunc { func AuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) { return func(c *gin.Context) {
authHeader := c.GetHeader("Authorization") token, err := c.Cookie(consts.COOKIE_SESSION)
if authHeader == "" { if errors.Is(err, http.ErrNoCookie) {
c.JSON(401, types.ErrorResponse{Message: "Authorization header is required"}) c.JSON(401, types.ErrorResponse{Message: "Authorization cookie is required"})
c.Abort() c.Abort()
return return
} }
if !tokens.ValidateSessionToken(token) {
token := authHeader c.JSON(401, types.ErrorResponse{Message: "Invalid authorization cookie"})
if strings.Index(token, "Bearer ") == 0 {
token = strings.Split(token, " ")[1]
}
if !tokens.AmIAllowed(token) {
c.JSON(401, types.ErrorResponse{Message: "Token is invalid"})
c.Abort() c.Abort()
return return
} }
session, err := tokens.GetSession(token)
if userID, err := tokens.GetID(token); err != nil { if err != nil {
c.JSON(401, types.ErrorResponse{Message: "Token is invalid ERR4001"}) log.Printf("ERROR: tokens.GetSession: %v\n", err)
c.JSON(500, types.ErrorResponse{Message: "Server error"})
c.Abort() c.Abort()
return return
} else {
c.Set("UserID", userID)
} }
c.Set("UserID", session.UserID)
c.Next() c.Next()
} }