Revalidate admin roles from the database and serialize report generation registration with owner-scoped deletion. Refs #9 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
53 lines
1.3 KiB
Go
53 lines
1.3 KiB
Go
package auth
|
|
|
|
import (
|
|
"github.com/tradarr/backend/internal/models"
|
|
"net/http"
|
|
"strings"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
func Middleware(secret string) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
header := c.GetHeader("Authorization")
|
|
if !strings.HasPrefix(header, "Bearer ") {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "missing token"})
|
|
return
|
|
}
|
|
claims, err := ValidateToken(strings.TrimPrefix(header, "Bearer "), secret)
|
|
if err != nil {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid token"})
|
|
return
|
|
}
|
|
c.Set("userID", claims.UserID)
|
|
c.Set("email", claims.Email)
|
|
c.Set("role", claims.Role)
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
type UserLookup interface {
|
|
GetUserByID(string) (*models.User, error)
|
|
}
|
|
|
|
func AdminOnly(repo UserLookup) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
user, err := repo.GetUserByID(c.GetString("userID"))
|
|
if err != nil {
|
|
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "account lookup failed"})
|
|
return
|
|
}
|
|
if user == nil {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
|
|
return
|
|
}
|
|
if user.Role != models.RoleAdmin {
|
|
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "admin only"})
|
|
return
|
|
}
|
|
c.Set("role", string(user.Role))
|
|
c.Next()
|
|
}
|
|
}
|