Change logging to be json comaptible
This commit is contained in:
@@ -19,6 +19,9 @@ type Claims struct {
|
||||
|
||||
func AuthMiddleware() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
log := StructuredLog(c).With().
|
||||
Str("event", "auth_middleware").
|
||||
Logger()
|
||||
|
||||
var tokenString string
|
||||
|
||||
@@ -39,6 +42,7 @@ func AuthMiddleware() gin.HandlerFunc {
|
||||
}
|
||||
|
||||
if tokenString == "" {
|
||||
log.Warn().Str("reason", "no_token").Msg("Auth failed - no token provided")
|
||||
abortUnauthorized(c)
|
||||
return
|
||||
}
|
||||
@@ -51,13 +55,26 @@ func AuthMiddleware() gin.HandlerFunc {
|
||||
return jwtSecret, nil
|
||||
})
|
||||
|
||||
if err != nil || !token.Valid {
|
||||
if err != nil {
|
||||
log.Warn().
|
||||
Str("reason", "token_parse_error").
|
||||
Err(err).
|
||||
Msg("Auth failed - token parse error")
|
||||
abortUnauthorized(c)
|
||||
return
|
||||
}
|
||||
|
||||
if !token.Valid {
|
||||
log.Warn().Str("reason", "invalid_token").Msg("Auth failed - invalid token")
|
||||
abortUnauthorized(c)
|
||||
return
|
||||
}
|
||||
|
||||
c.Set("user_id", claims.UserID)
|
||||
c.Set("role", claims.Role)
|
||||
c.Set("username", claims.UserID)
|
||||
|
||||
log.Debug().Str("user_id", claims.UserID).Str("role", claims.Role).Msg("Auth successful")
|
||||
|
||||
c.Next()
|
||||
}
|
||||
@@ -76,26 +93,37 @@ func abortUnauthorized(c *gin.Context) {
|
||||
|
||||
func RequireRole(roles ...string) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
log := StructuredLog(c).With().
|
||||
Str("event", "role_check").
|
||||
Logger()
|
||||
|
||||
roleValue, exists := c.Get("role")
|
||||
if !exists {
|
||||
log.Warn().Str("reason", "no_role").Msg("Role check failed - no role in context")
|
||||
abortForbidden(c)
|
||||
return
|
||||
}
|
||||
|
||||
userRole, ok := roleValue.(string)
|
||||
if !ok {
|
||||
log.Warn().Str("reason", "invalid_role_type").Msg("Role check failed - invalid role type")
|
||||
abortForbidden(c)
|
||||
return
|
||||
}
|
||||
|
||||
for _, allowed := range roles {
|
||||
if userRole == allowed {
|
||||
log.Debug().Str("required_roles", strings.Join(roles, ",")).Str("user_role", userRole).Msg("Role check passed")
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
log.Warn().
|
||||
Str("required_roles", strings.Join(roles, ",")).
|
||||
Str("user_role", userRole).
|
||||
Msg("Role check failed - insufficient permissions")
|
||||
|
||||
abortForbidden(c)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user