38 lines
866 B
Go
38 lines
866 B
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// Admin 管理员权限中间件,检查 context 中 user 的 role 是否为 admin
|
|
func Admin() gin.HandlerFunc {
|
|
return AdminMiddleware()
|
|
}
|
|
|
|
// AdminMiddleware 管理员权限中间件,检查 context 中 user 的 role 是否为 admin
|
|
func AdminMiddleware() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
user, exists := c.Get("user")
|
|
if !exists {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "未认证"})
|
|
return
|
|
}
|
|
|
|
userMap, ok := user.(map[string]interface{})
|
|
if !ok {
|
|
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "权限不足"})
|
|
return
|
|
}
|
|
|
|
role, ok := userMap["role"].(string)
|
|
if !ok || role != "admin" {
|
|
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "需要管理员权限"})
|
|
return
|
|
}
|
|
|
|
c.Next()
|
|
}
|
|
}
|