42 lines
1.1 KiB
Go
42 lines
1.1 KiB
Go
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)
|
||
})
|
||
}
|