78 lines
2.0 KiB
Go
78 lines
2.0 KiB
Go
package middleware
|
||
|
||
import (
|
||
"strings"
|
||
|
||
"server/models"
|
||
"server/services"
|
||
|
||
"github.com/beego/beego/v2/server/web"
|
||
"github.com/beego/beego/v2/server/web/context"
|
||
)
|
||
|
||
// JWTAuthMiddleware JWT认证中间件
|
||
func JWTAuthMiddleware() web.FilterFunc {
|
||
return func(ctx *context.Context) {
|
||
// 跳过登录相关的路由
|
||
if strings.HasPrefix(ctx.Request.RequestURI, "/api/login") ||
|
||
strings.HasPrefix(ctx.Request.RequestURI, "/api/reset-password") {
|
||
return
|
||
}
|
||
|
||
// 从请求头中获取Authorization
|
||
authHeader := ctx.Request.Header.Get("Authorization")
|
||
if authHeader == "" {
|
||
ctx.Output.SetStatus(401)
|
||
ctx.Output.JSON(map[string]interface{}{
|
||
"success": false,
|
||
"message": "未提供认证信息",
|
||
}, false, false)
|
||
return
|
||
}
|
||
|
||
// 按空格分割
|
||
authParts := strings.SplitN(authHeader, " ", 2)
|
||
if !(len(authParts) == 2 && authParts[0] == "Bearer") {
|
||
ctx.Output.SetStatus(401)
|
||
ctx.Output.JSON(map[string]interface{}{
|
||
"success": false,
|
||
"message": "认证信息格式错误",
|
||
}, false, false)
|
||
return
|
||
}
|
||
|
||
// 解析token
|
||
claims, err := models.ParseToken(authParts[1])
|
||
if err != nil {
|
||
// 处理各种错误情况
|
||
ctx.Output.SetStatus(401)
|
||
switch err.Error() {
|
||
case "token is expired":
|
||
ctx.Output.JSON(map[string]interface{}{
|
||
"success": false,
|
||
"message": "token已过期",
|
||
}, false, false)
|
||
default:
|
||
ctx.Output.JSON(map[string]interface{}{
|
||
"success": false,
|
||
"message": "无效的token",
|
||
}, false, false)
|
||
}
|
||
return
|
||
}
|
||
|
||
// 将用户信息存储在上下文
|
||
ctx.Input.SetData("userId", claims.UserID)
|
||
ctx.Input.SetData("username", claims.Username)
|
||
ctx.Input.SetData("tenantId", claims.TenantId)
|
||
|
||
// 判断用户类型:检查userId是否在员工表中
|
||
// 如果userId在yz_tenant_employees表中存在,则为员工登录;否则为用户登录
|
||
userType := "user"
|
||
if services.IsEmployee(claims.UserID) {
|
||
userType = "employee"
|
||
}
|
||
ctx.Input.SetData("userType", userType)
|
||
}
|
||
}
|