Files
AuthCentral/api/middlewares/admin_middleware.go
Beyhan Oğur 8b1fbdee99 first commit
2026-04-26 21:37:58 +03:00

50 lines
1.0 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package middlewares
import (
"net/http"
"gauth-central/internal/database"
"gauth-central/internal/models"
"github.com/gin-gonic/gin"
)
// AdminMiddleware - Sadece admin rolündeki kullanıcıların erişimini sağlar
func AdminMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
// Get user_id from context (set by AuthMiddleware)
userID := c.GetString("user_id")
if userID == "" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
c.Abort()
return
}
// Fetch user with roles
var user models.User
err := database.DB.Preload("Roles").Where("id = ?", userID).First(&user).Error
if err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "User not found"})
c.Abort()
return
}
// Check if user has admin role
hasAdminRole := false
for _, role := range user.Roles {
if role.Name == "admin" {
hasAdminRole = true
break
}
}
if !hasAdminRole {
c.JSON(http.StatusForbidden, gin.H{"error": "Admin access required"})
c.Abort()
return
}
c.Next()
}
}