first commit
This commit is contained in:
@@ -0,0 +1,75 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"server/pkg/jwtutil"
|
||||
|
||||
"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 := jwtutil.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)
|
||||
|
||||
// 从token中获取用户类型(如果token中没有,则默认为"user")
|
||||
userType := claims.UserType
|
||||
if userType == "" {
|
||||
userType = "user"
|
||||
}
|
||||
ctx.Input.SetData("userType", userType)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user