This commit is contained in:
Tomas Dvorak
2025-11-11 10:29:30 +01:00
parent d5b4faea61
commit 8762bde4bf
139 changed files with 7240 additions and 2870 deletions
+49
View File
@@ -75,6 +75,55 @@ func JWTAuth(db *gorm.DB) gin.HandlerFunc {
}
}
// JWTOptional attempts to authenticate the request if a token or auth cookie is present.
func JWTOptional(db *gorm.DB) gin.HandlerFunc {
return func(c *gin.Context) {
if config.AppConfig != nil && config.AppConfig.AppEnv != "production" {
if strings.ToLower(c.GetHeader("X-Dev-Admin")) == "true" {
c.Set("userRole", "admin")
c.Set("user", &models.User{Role: "admin"})
c.Next()
return
}
}
var tokenString string
if authHeader := c.GetHeader("Authorization"); authHeader != "" {
parts := strings.Split(authHeader, " ")
if len(parts) == 2 && parts[0] == "Bearer" {
tokenString = parts[1]
}
}
if tokenString == "" {
if cookie, err := c.Request.Cookie("auth_token"); err == nil {
tokenString = cookie.Value
}
}
if tokenString == "" {
c.Next()
return
}
claims, err := utils.ParseJWT(tokenString)
if err != nil {
c.Next()
return
}
var user models.User
if err := db.First(&user, claims.UserID).Error; err != nil {
c.Next()
return
}
c.Set("user", &user)
c.Set("claims", claims)
c.Set("userID", user.ID)
c.Set("userRole", user.Role)
c.Next()
}
}
// DevBypass checks for special dev header and grants admin role when not in production
func DevBypass() gin.HandlerFunc {
return func(c *gin.Context) {