Files
GovAI/server/internal/middleware/rbac.go
T
2026-06-15 23:48:37 +08:00

42 lines
1.1 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 middleware
import (
"net/http"
"github.com/enterprise-ai-platform/server/internal/response"
)
var roleLevel = map[string]int{
"user": 0,
"creator": 1,
"admin": 2,
"super_admin": 3,
}
// RequireRole returns middleware that checks if user has the minimum required role.
func RequireRole(minRole string) func(http.Handler) http.Handler {
minLevel := roleLevel[minRole]
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
role := GetRole(r.Context())
if roleLevel[role] < minLevel {
response.Forbidden(w, "权限不足")
return
}
next.ServeHTTP(w, r)
})
}
}
// RequireSuperAdmin restricts access to platform-level (super_admin) operations only.
// Unlike RequireRole("admin")super admin 不受机构(org_id)限制,可执行跨机构操作。
func RequireSuperAdmin(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if GetRole(r.Context()) != "super_admin" {
response.Forbidden(w, "仅平台管理员可访问")
return
}
next.ServeHTTP(w, r)
})
}