64 lines
1.5 KiB
Go
64 lines
1.5 KiB
Go
package user
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// AuthMiddleware validates the bearer token and injects the user into the Gin context.
|
|
func AuthMiddleware() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
token := c.GetHeader("Authorization")
|
|
u := CheckToken(token)
|
|
if u == nil {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
c.Set("userID", u.UserID)
|
|
c.Set("username", u.Username)
|
|
c.Set("user", u)
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
// RequireRole is a middleware that enforces a minimum role level.
|
|
func RequireRole(required string) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
u, exists := c.Get("user")
|
|
if !exists {
|
|
respondWithError(c, http.StatusUnauthorized, "unauthorized")
|
|
c.Abort()
|
|
return
|
|
}
|
|
user, ok := u.(*User)
|
|
if !ok {
|
|
respondWithError(c, http.StatusInternalServerError, "invalid user context")
|
|
c.Abort()
|
|
return
|
|
}
|
|
switch required {
|
|
case RoleAdmin:
|
|
if !user.IsAdmin() {
|
|
respondWithError(c, http.StatusForbidden, "admin role required")
|
|
c.Abort()
|
|
return
|
|
}
|
|
case RoleMaintainer:
|
|
if !user.IsMaintainer() {
|
|
respondWithError(c, http.StatusForbidden, "maintainer role required")
|
|
c.Abort()
|
|
return
|
|
}
|
|
}
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
// RequireAdmin is a convenience wrapper for admin-only endpoints.
|
|
func RequireAdmin() gin.HandlerFunc { return RequireRole(RoleAdmin) }
|
|
|
|
// RequireMaintainer is a convenience wrapper for maintainer-or-higher endpoints.
|
|
func RequireMaintainer() gin.HandlerFunc { return RequireRole(RoleMaintainer) }
|