init
This commit is contained in:
39
backend/internal/auth/admin_middleware.go
Normal file
39
backend/internal/auth/admin_middleware.go
Normal file
@@ -0,0 +1,39 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"social-raiting.nekiiinkognito.ru/internal/models"
|
||||
)
|
||||
|
||||
func RequireAdmin(db *gorm.DB) gin.HandlerFunc {
|
||||
return func(ctx *gin.Context) {
|
||||
userID, exists := ctx.Get("userID")
|
||||
if !exists {
|
||||
ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "missing user context"})
|
||||
return
|
||||
}
|
||||
|
||||
var user models.User
|
||||
if err := db.First(&user, "id = ?", userID).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "user not found"})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "failed to load user"})
|
||||
return
|
||||
}
|
||||
|
||||
if !user.IsAdmin {
|
||||
ctx.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "admin access required"})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Next()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user