82 lines
2.5 KiB
Go
82 lines
2.5 KiB
Go
package middlewares
|
|
|
|
import (
|
|
"net/http"
|
|
"strings"
|
|
|
|
"github.com/Caknoooo/go-gin-clean-starter/modules/user/dto"
|
|
"github.com/Caknoooo/go-gin-clean-starter/modules/user/service"
|
|
"github.com/Caknoooo/go-gin-clean-starter/pkg/utils"
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
func RoleSuperAdmin(userService service.UserService) gin.HandlerFunc {
|
|
return func(ctx *gin.Context) {
|
|
userID, exists := ctx.Get("user_id")
|
|
if !exists {
|
|
response := utils.BuildResponseFailed(dto.MESSAGE_FAILED_PROSES_REQUEST, "User ID not found in context", nil)
|
|
ctx.AbortWithStatusJSON(http.StatusUnauthorized, response)
|
|
return
|
|
}
|
|
|
|
// Get user details including role
|
|
user, err := userService.GetUserById(ctx.Request.Context(), userID.(string))
|
|
if err != nil {
|
|
response := utils.BuildResponseFailed(dto.MESSAGE_FAILED_PROSES_REQUEST, "Failed to get user data", nil)
|
|
ctx.AbortWithStatusJSON(http.StatusForbidden, response)
|
|
return
|
|
}
|
|
|
|
hasSuperAdmin := false
|
|
for _, role := range user.Roles {
|
|
normalized := strings.ToLower(strings.ReplaceAll(role.Name, " ", ""))
|
|
if normalized == "superadmin" {
|
|
hasSuperAdmin = true
|
|
break
|
|
}
|
|
}
|
|
if !hasSuperAdmin {
|
|
response := utils.BuildResponseFailed(dto.MESSAGE_FAILED_PROSES_REQUEST, "Access denied. Superadmin role required", nil)
|
|
ctx.AbortWithStatusJSON(http.StatusForbidden, response)
|
|
return
|
|
}
|
|
|
|
ctx.Next()
|
|
}
|
|
}
|
|
|
|
// Alternative: Generic role checker
|
|
func RequireRole(requiredRole string, userService service.UserService) gin.HandlerFunc {
|
|
return func(ctx *gin.Context) {
|
|
userID, exists := ctx.Get("user_id")
|
|
if !exists {
|
|
response := utils.BuildResponseFailed(dto.MESSAGE_FAILED_PROSES_REQUEST, "User ID not found in context", nil)
|
|
ctx.AbortWithStatusJSON(http.StatusUnauthorized, response)
|
|
return
|
|
}
|
|
|
|
user, err := userService.GetUserById(ctx.Request.Context(), userID.(string))
|
|
if err != nil {
|
|
response := utils.BuildResponseFailed(dto.MESSAGE_FAILED_PROSES_REQUEST, "Failed to get user data", nil)
|
|
ctx.AbortWithStatusJSON(http.StatusForbidden, response)
|
|
return
|
|
}
|
|
|
|
hasRequiredRole := false
|
|
for _, role := range user.Roles {
|
|
normalized := strings.ToLower(strings.ReplaceAll(role.Name, " ", ""))
|
|
if normalized == requiredRole {
|
|
hasRequiredRole = true
|
|
break
|
|
}
|
|
}
|
|
if !hasRequiredRole {
|
|
response := utils.BuildResponseFailed(dto.MESSAGE_FAILED_PROSES_REQUEST, "Access denied. Required role: "+requiredRole, nil)
|
|
ctx.AbortWithStatusJSON(http.StatusForbidden, response)
|
|
return
|
|
}
|
|
|
|
ctx.Next()
|
|
}
|
|
}
|