You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
52 lines
1.2 KiB
52 lines
1.2 KiB
package middleware
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
|
|
"github.com/casbin/casbin/v2"
|
|
)
|
|
|
|
type AuthzMiddleware struct {
|
|
Enforcer *casbin.Enforcer
|
|
}
|
|
|
|
func NewAuthzMiddleware(enforcer *casbin.Enforcer) *AuthzMiddleware {
|
|
return &AuthzMiddleware{Enforcer: enforcer}
|
|
}
|
|
|
|
func (m *AuthzMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
// 从 context 获取 role(由 Auth middleware 注入)
|
|
role, _ := r.Context().Value("role").(string)
|
|
if role == "" {
|
|
role = "guest"
|
|
}
|
|
|
|
// Casbin enforce: role, path, method
|
|
allowed, err := m.Enforcer.Enforce(role, r.URL.Path, r.Method)
|
|
if err != nil {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
json.NewEncoder(w).Encode(map[string]interface{}{
|
|
"code": 500,
|
|
"message": "权限检查失败",
|
|
"success": false,
|
|
})
|
|
return
|
|
}
|
|
|
|
if !allowed {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(http.StatusForbidden)
|
|
json.NewEncoder(w).Encode(map[string]interface{}{
|
|
"code": 403,
|
|
"message": "没有权限执行此操作",
|
|
"success": false,
|
|
})
|
|
return
|
|
}
|
|
|
|
next(w, r)
|
|
}
|
|
}
|
|
|