2024-08-03 07:43:08 +02:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
import (
|
2024-11-06 18:47:40 +01:00
|
|
|
"errors"
|
|
|
|
"log"
|
|
|
|
"net/http"
|
2024-10-31 09:07:36 +01:00
|
|
|
|
2024-11-06 18:47:40 +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"
|
|
|
|
)
|
|
|
|
|
2024-08-03 07:50:06 +02:00
|
|
|
// 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) {
|
2024-11-06 18:47:40 +01:00
|
|
|
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
|
|
|
|
}
|
2024-11-06 18:47:40 +01:00
|
|
|
if !tokens.ValidateSessionToken(token) {
|
|
|
|
c.JSON(401, types.ErrorResponse{Message: "Invalid authorization cookie"})
|
2024-08-03 07:43:08 +02:00
|
|
|
c.Abort()
|
|
|
|
return
|
|
|
|
}
|
2024-11-06 18:47:40 +01:00
|
|
|
session, err := tokens.GetSession(token)
|
|
|
|
if err != nil {
|
|
|
|
log.Printf("ERROR: tokens.GetSession: %v\n", err)
|
|
|
|
c.JSON(500, types.ErrorResponse{Message: "Server error"})
|
2024-08-03 07:50:06 +02:00
|
|
|
c.Abort()
|
|
|
|
return
|
|
|
|
}
|
2024-11-06 18:47:40 +01:00
|
|
|
c.Set("UserID", session.UserID)
|
2024-08-03 07:50:06 +02:00
|
|
|
|
2024-08-03 07:43:08 +02:00
|
|
|
c.Next()
|
|
|
|
}
|
|
|
|
}
|