fin-check-api/middleware/auth.go

40 lines
968 B
Go
Raw Permalink Normal View History

2024-08-03 07:43:08 +02:00
package middleware
import (
"errors"
"log"
"net/http"
2024-10-31 09:07:36 +01:00
"git.qowevisa.me/Qowevisa/fin-check-api/consts"
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
}
if !tokens.ValidateSessionToken(token) {
c.JSON(401, types.ErrorResponse{Message: "Invalid authorization cookie"})
2024-08-03 07:43:08 +02:00
c.Abort()
return
}
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
}
c.Set("UserID", session.UserID)
2024-08-03 07:43:08 +02:00
c.Next()
}
}