fin-check-api/middleware/auth.go

43 lines
929 B
Go
Raw Normal View History

2024-08-03 07:43:08 +02:00
package middleware
import (
2024-10-31 09:07:36 +01:00
"strings"
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) {
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
c.JSON(401, types.ErrorResponse{Message: "Authorization header is required"})
c.Abort()
return
}
token := authHeader
2024-10-31 09:07:36 +01:00
if strings.Index(token, "Bearer ") == 0 {
token = strings.Split(token, " ")[1]
}
2024-08-03 07:43:08 +02:00
if !tokens.AmIAllowed(token) {
c.JSON(401, types.ErrorResponse{Message: "Token is invalid"})
c.Abort()
return
}
if userID, err := tokens.GetID(token); err != nil {
c.JSON(401, types.ErrorResponse{Message: "Token is invalid ERR4001"})
c.Abort()
return
} else {
c.Set("UserID", userID)
}
2024-08-03 07:43:08 +02:00
c.Next()
}
}