fin-check-api/middleware/auth.go

36 lines
907 B
Go
Raw Normal View History

2024-08-03 07:43:08 +02:00
package middleware
import (
"errors"
"net/http"
2024-10-31 09:07:36 +01:00
"git.qowevisa.me/Qowevisa/fin-check-api/consts"
"git.qowevisa.me/Qowevisa/fin-check-api/db"
2024-11-04 16:55:14 +01:00
"git.qowevisa.me/Qowevisa/fin-check-api/tokens"
"git.qowevisa.me/Qowevisa/fin-check-api/types"
2024-08-03 07:43:08 +02:00
"github.com/gin-gonic/gin"
)
// Passes UserID with `c.Set("UserID")` as it gets id from token
2024-08-03 07:43:08 +02:00
func AuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
token, err := c.Cookie(consts.COOKIE_SESSION)
if errors.Is(err, http.ErrNoCookie) {
c.JSON(401, types.ErrorResponse{Message: "Authorization cookie is required"})
2024-08-03 07:43:08 +02:00
c.Abort()
return
}
var session *db.Session
if validated, tmpSession := tokens.ValidateAndGetSessionToken(token); !validated {
c.JSON(401, types.ErrorResponse{Message: "Invalid authorization cookie"})
2024-08-03 07:43:08 +02:00
c.Abort()
return
} else {
session = tmpSession
}
c.Set("UserID", session.UserID)
2024-08-03 07:43:08 +02:00
c.Next()
}
}