79 lines
1.6 KiB
Go
79 lines
1.6 KiB
Go
package middleware
|
|
|
|
import (
|
|
"allapp/utils/jwtx"
|
|
"allapp/utils/pathx"
|
|
"allapp/utils/response"
|
|
"context"
|
|
"strings"
|
|
|
|
"github.com/cloudwego/hertz/pkg/app"
|
|
)
|
|
|
|
// 私有 key,防止冲突
|
|
type ctxKeyUser struct{}
|
|
|
|
// ContextUser 保存用户信息,包括 UserID、DeviceUUID 和当前 SpaceID
|
|
type ContextUser struct {
|
|
UserID int64
|
|
DeviceUUID string
|
|
}
|
|
|
|
// Auth 中间件,支持 header 中传 spaceid 并校验权限
|
|
func Auth() app.HandlerFunc {
|
|
whitelistPaths := []string{
|
|
"/auth/login",
|
|
"/auth/register",
|
|
"/auth/refresh/token",
|
|
"/ws",
|
|
}
|
|
|
|
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 := strings.TrimSpace(string(c.GetHeader("Token")))
|
|
|
|
verifyToken, flag := jwtx.VerifyToken(token)
|
|
if !flag {
|
|
response.Fail(c).Code(response.HttpCode.Unauthorized).Send()
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
userID := verifyToken.UserID
|
|
|
|
// 设置 context
|
|
user := &ContextUser{
|
|
UserID: userID,
|
|
}
|
|
ctx = setContextUser(ctx, user)
|
|
|
|
c.Next(ctx)
|
|
}
|
|
}
|
|
|
|
// GetContextUser 从 context 获取用户信息
|
|
func GetContextUser(ctx context.Context) *ContextUser {
|
|
user, ok := ctx.Value(ctxKeyUser{}).(*ContextUser)
|
|
if !ok || user == nil {
|
|
return &ContextUser{}
|
|
}
|
|
return user
|
|
}
|
|
|
|
// GetUserID 从 context 获取 user_id
|
|
func GetUserID(ctx context.Context) int64 {
|
|
return GetContextUser(ctx).UserID
|
|
}
|
|
|
|
// 内部中间件设置 ContextUser
|
|
func setContextUser(ctx context.Context, user *ContextUser) context.Context {
|
|
return context.WithValue(ctx, ctxKeyUser{}, user)
|
|
}
|