40 lines
885 B
Go
40 lines
885 B
Go
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()
|
|
}
|
|
}
|