first commit
This commit is contained in:
97
middle/middle_auth.go
Normal file
97
middle/middle_auth.go
Normal file
@@ -0,0 +1,97 @@
|
||||
// Package middle auth_middleware.go
|
||||
package middle
|
||||
|
||||
import (
|
||||
"Quincy_admin/utils"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type AuthMiddleware struct {
|
||||
Service *MService
|
||||
}
|
||||
|
||||
func NewAuthMiddleware(Service *MService) *AuthMiddleware {
|
||||
return &AuthMiddleware{
|
||||
Service: Service,
|
||||
}
|
||||
}
|
||||
|
||||
// Auth 验证 X-Access-Token 的中间件
|
||||
func (m *AuthMiddleware) Auth() gin.HandlerFunc {
|
||||
return func(ctx *gin.Context) {
|
||||
|
||||
// 获取 X-Access-Token 头部
|
||||
token := ctx.GetHeader("Authorization")
|
||||
if token == "" {
|
||||
utils.Error(ctx, http.StatusUnauthorized, "缺少访问令牌")
|
||||
ctx.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
user, err := utils.ParseToken(token)
|
||||
if err != nil {
|
||||
utils.Error(ctx, http.StatusUnauthorized, "无效的访问令牌")
|
||||
ctx.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
// 验证用户是否存在
|
||||
newUser, err := m.Service.GetUserID(user.SessionCode)
|
||||
if err != nil {
|
||||
utils.Error(ctx, http.StatusUnauthorized, "用户不存在")
|
||||
ctx.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
if newUser.Status != 1 {
|
||||
utils.Error(ctx, http.StatusUnauthorized, "用户已被锁定")
|
||||
ctx.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
// 使用 ctx.Set() 存储用户 ID,角色ID,供后续中间件读取
|
||||
ctx.Set("user_id", newUser.ID)
|
||||
ctx.Set("role_id", newUser.RoleCode)
|
||||
ctx.Set("code", newUser.SessionCode)
|
||||
|
||||
// token 验证成功,继续处理请求
|
||||
ctx.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// Perm 验证权限
|
||||
func (m *AuthMiddleware) Perm(perm string) gin.HandlerFunc {
|
||||
return func(ctx *gin.Context) {
|
||||
|
||||
userIDInterface, exists := ctx.Get("user_id")
|
||||
if !exists {
|
||||
utils.Error(ctx, http.StatusUnauthorized, "权限校验错误:用户ID不存在")
|
||||
ctx.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
userID, ok := userIDInterface.(int)
|
||||
if !ok {
|
||||
utils.Error(ctx, http.StatusUnauthorized, "权限校验错误:用户ID类型错误")
|
||||
ctx.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
// 检查是否为超级管理员,如果是则跳过权限校验
|
||||
if m.Service.IsSuperAdmin(userID) {
|
||||
ctx.Next()
|
||||
return
|
||||
}
|
||||
|
||||
// 非超管账号检查权限
|
||||
if err := m.Service.HasPermission(userID, perm); err != nil {
|
||||
utils.Error(ctx, http.StatusForbidden, "没有权限")
|
||||
ctx.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Next()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user