Feat admin rbac migration (#1)
Co-authored-by: Jeffrey Smith <jasafpro@gmail.com> Co-committed-by: Jeffrey Smith <jasafpro@gmail.com>
This commit was merged in pull request #1.
This commit is contained in:
@@ -7,6 +7,7 @@ import (
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"switchboard-core/auth"
|
||||
"switchboard-core/config"
|
||||
"switchboard-core/database"
|
||||
"switchboard-core/store"
|
||||
@@ -60,37 +61,34 @@ func AuthOrRedirect(cfg *config.Config, users store.UserStore, cache *UserStatus
|
||||
return
|
||||
}
|
||||
|
||||
// Resolve user role — redirect (not JSON) on any failure.
|
||||
var role string
|
||||
// Check user is active — redirect (not JSON) on failure.
|
||||
if entry, hit := cache.get(claims.UserID); hit {
|
||||
if !entry.isActive {
|
||||
redirectToLogin(c, loginPath)
|
||||
return
|
||||
}
|
||||
role = entry.role
|
||||
} else {
|
||||
user, err := users.GetByID(c.Request.Context(), claims.UserID)
|
||||
if err != nil || !user.IsActive {
|
||||
redirectToLogin(c, loginPath)
|
||||
return
|
||||
}
|
||||
cache.set(claims.UserID, user.IsActive, user.Role)
|
||||
role = user.Role
|
||||
cache.set(claims.UserID, user.IsActive)
|
||||
}
|
||||
|
||||
c.Set("user_id", claims.UserID)
|
||||
c.Set("email", claims.Email)
|
||||
c.Set("role", role)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// RequireAdminPage aborts with 403 if the user isn't an admin.
|
||||
// RequireAdminPage aborts with 403 if the user lacks surface.admin.access.
|
||||
// Use after AuthOrRedirect for admin-only page routes.
|
||||
func RequireAdminPage() gin.HandlerFunc {
|
||||
func RequireAdminPage(stores store.Stores) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
role, _ := c.Get("role")
|
||||
if role != "admin" {
|
||||
userID := c.GetString("user_id")
|
||||
perms, err := resolveAndCachePerms(c, stores, userID)
|
||||
if err != nil || !perms[auth.PermSurfaceAdminAccess] {
|
||||
c.String(http.StatusForbidden, "Admin access required")
|
||||
c.Abort()
|
||||
return
|
||||
|
||||
Reference in New Issue
Block a user