- Added gin-gonic v1.10.0 dependency - Refactored router.go: clean route groups with middleware chains - Refactored all handlers to use gin.Context instead of http.ResponseWriter/*http.Request - Simplified response helpers (JSON, Error, Success, Created, NoContent) - Clean auth middleware using Gin's c.Set() for context - Cleaner route definitions with path parameters (e.g., /domains/:name/users/:id) - Admin routes moved to /api/admin group with RequireAdmin middleware
62 lines
1.4 KiB
Go
62 lines
1.4 KiB
Go
package handlers
|
|
|
|
import (
|
|
"net/http"
|
|
"strings"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/imc-vibe/backend/internal/auth"
|
|
)
|
|
|
|
const AuthContextKey = "auth"
|
|
|
|
func AuthMiddleware(jwtManager *auth.JWTManager) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
authHeader := c.GetHeader("Authorization")
|
|
if authHeader == "" {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, Response{Error: "authorization header required"})
|
|
return
|
|
}
|
|
|
|
parts := strings.SplitN(authHeader, " ", 2)
|
|
if len(parts) != 2 || strings.ToLower(parts[0]) != "bearer" {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, Response{Error: "invalid authorization header format"})
|
|
return
|
|
}
|
|
|
|
claims, err := jwtManager.ValidateToken(parts[1])
|
|
if err != nil {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, Response{Error: "invalid token"})
|
|
return
|
|
}
|
|
|
|
authCtx := &auth.Context{
|
|
UserID: claims.UserID,
|
|
Username: claims.Username,
|
|
Role: auth.Role(claims.Role),
|
|
}
|
|
|
|
c.Set(AuthContextKey, authCtx)
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
func GetAuthContext(c *gin.Context) *auth.Context {
|
|
if ctx, exists := c.Get(AuthContextKey); exists {
|
|
if authCtx, ok := ctx.(*auth.Context); ok {
|
|
return authCtx
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func RequireAdmin() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
authCtx := GetAuthContext(c)
|
|
if authCtx == nil || !authCtx.IsAdmin() {
|
|
c.AbortWithStatusJSON(http.StatusForbidden, Response{Error: "admin access required"})
|
|
return
|
|
}
|
|
c.Next()
|
|
}
|
|
}
|