u
This commit is contained in:
1 parent
8408cf779f
commit
25a9e41025
58 files changed
+2079
-6308
No files matched your search
@@ -0,0 +1,67 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"cn/oneao/base-go/utils/jwtx"
|
||||
"cn/oneao/base-go/utils/pathx"
|
||||
"cn/oneao/base-go/utils/response"
|
||||
"context"
|
||||
"github.com/cloudwego/hertz/pkg/app"
|
||||
)
|
||||
|
||||
// 私有 key,防止冲突
|
||||
type ctxKeyUserID struct{}
|
||||
|
||||
// Auth 中间件,直接在中间件里过滤白名单路径
|
||||
func Auth() app.HandlerFunc {
|
||||
// 白名单路径,直接写死
|
||||
whitelistPaths := []string{
|
||||
"/auth/login",
|
||||
"/auth/register",
|
||||
"/auth/refreshToken",
|
||||
}
|
||||
|
||||
return func(ctx context.Context, c *app.RequestContext) {
|
||||
path := string(c.Request.URI().Path())
|
||||
|
||||
// 使用工具函数判断是否在白名单
|
||||
if pathx.MatchPath(path, whitelistPaths) {
|
||||
c.Next(ctx)
|
||||
return
|
||||
}
|
||||
|
||||
// 获取 token
|
||||
token := string(c.GetHeader("token"))
|
||||
if token == "" {
|
||||
response.Fail(c).Code(response.HttpCode.Unauthorized).Send()
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
verifyToken := jwtx.VerifyToken(token)
|
||||
|
||||
if verifyToken.IsValid {
|
||||
// 设置 userID 到 context
|
||||
ctx = setUserID(ctx, verifyToken.Claims.UserID)
|
||||
c.Next(ctx)
|
||||
return
|
||||
}
|
||||
|
||||
// token 无效
|
||||
response.Fail(c).Code(response.HttpCode.RefreshToken).Send()
|
||||
c.Abort()
|
||||
}
|
||||
}
|
||||
|
||||
// GetUserID 从 context 中获取 user_id
|
||||
func GetUserID(ctx context.Context) int64 {
|
||||
userID, ok := ctx.Value(ctxKeyUserID{}).(int64)
|
||||
if !ok {
|
||||
return 0 // 或者返回 error,根据业务需求
|
||||
}
|
||||
return userID
|
||||
}
|
||||
|
||||
// 内部中间件设置 user_id
|
||||
func setUserID(ctx context.Context, userID int64) context.Context {
|
||||
return context.WithValue(ctx, ctxKeyUserID{}, userID)
|
||||
}
|
||||
Reference in new issue
Block a user