117 lines
2.8 KiB
Go
117 lines
2.8 KiB
Go
package middleware
|
||
|
||
import (
|
||
"github.com/gin-gonic/gin"
|
||
"net/http"
|
||
"psi/database"
|
||
"psi/models"
|
||
"psi/utils"
|
||
"strings"
|
||
)
|
||
|
||
// JWTAuth JWT认证中间件
|
||
func JWTAuth() gin.HandlerFunc {
|
||
// 处理JWT认证
|
||
return func(c *gin.Context) {
|
||
// 检查认证头
|
||
authHeader := c.GetHeader("Authorization")
|
||
// 检查认证头是否为空
|
||
if authHeader == "" {
|
||
// 返回错误
|
||
c.JSON(http.StatusUnauthorized, gin.H{"error": "未提供认证令牌"})
|
||
// 中断处理
|
||
c.Abort()
|
||
// 返回
|
||
return
|
||
}
|
||
|
||
// 提取令牌
|
||
parts := strings.SplitN(authHeader, " ", 2)
|
||
// 处理错误
|
||
if !(len(parts) == 2 && parts[0] == "Bearer") {
|
||
// 返回错误
|
||
c.JSON(http.StatusUnauthorized, gin.H{"error": "认证格式错误"})
|
||
// 中断处理
|
||
c.Abort()
|
||
// 返回
|
||
return
|
||
}
|
||
// 解析JWT
|
||
claims, err := utils.ParseJWT(parts[1])
|
||
// 处理错误
|
||
if err != nil {
|
||
// 返回错误
|
||
c.JSON(http.StatusUnauthorized, gin.H{"error": "无效的认证令牌"})
|
||
// 中断处理
|
||
c.Abort()
|
||
// 返回
|
||
return
|
||
}
|
||
// 判断是员工还是用户
|
||
if claims.ID > 0 {
|
||
// 检查员工状态
|
||
var employee models.Employee
|
||
// 查询员工
|
||
if err := database.DB.Where("id = ? AND status = ? AND deleted_at = ?", claims.ID, 1, 0).First(&employee).Error;
|
||
// 处理错误
|
||
err != nil {
|
||
// 返回错误
|
||
c.JSON(http.StatusUnauthorized, gin.H{"error": "账号不存在或已被禁用"})
|
||
// 中断处理
|
||
c.Abort()
|
||
// 返回
|
||
return
|
||
}
|
||
|
||
// 将员工信息存入上下文
|
||
c.Set("id", employee.ID) // 设置员工ID
|
||
c.Set("role", employee.Role) // 设置角色
|
||
c.Set("username", employee.Username) // 设置用户名
|
||
c.Set("employee", employee) // 添加员工信息
|
||
c.Set("about_id", claims.AboutID) // 租户ID
|
||
c.Set("fid", employee.Fid) // 父级ID
|
||
|
||
// 如果有租户ID,获取租户数据库连接并存入上下文
|
||
if claims.AboutID > 0 {
|
||
tenantDB, err := database.GetTenantDB(claims.AboutID)
|
||
if err != nil {
|
||
c.JSON(http.StatusInternalServerError, gin.H{"error": "租户数据库连接失败"})
|
||
c.Abort()
|
||
return
|
||
}
|
||
c.Set("tenant_db", tenantDB)
|
||
}
|
||
} else {
|
||
// 无效的身份
|
||
c.JSON(http.StatusUnauthorized, gin.H{"error": "无效的身份标识"})
|
||
// 中断处理
|
||
c.Abort()
|
||
// 返回
|
||
return
|
||
}
|
||
|
||
// 继续处理
|
||
c.Next()
|
||
}
|
||
}
|
||
|
||
// AdminRequired 管理员权限
|
||
func AdminRequired() gin.HandlerFunc {
|
||
// 处理管理员权限
|
||
return func(c *gin.Context) {
|
||
// 检查角色
|
||
role, exists := c.Get("role")
|
||
// 处理错误
|
||
if !exists || role.(int64) != 255 {
|
||
// 返回错误
|
||
c.JSON(http.StatusForbidden, gin.H{"error": "需要管理员权限"})
|
||
// 中断处理
|
||
c.Abort()
|
||
// 返回
|
||
return
|
||
}
|
||
// 继续处理
|
||
c.Next()
|
||
}
|
||
}
|