qnc-server/common/ctxdata/ctxData.go
liangzai d09e7a08cf feat(user): 实现基础用户系统
- 实现用户手机验证码、密码登录功能,支持 JWT 认证
- 实现用户注册功能
- 实现jwt中获取用户信息
2024-11-03 19:06:09 +08:00

26 lines
550 B
Go

package ctxdata
import (
"context"
"encoding/json"
"fmt"
)
const CtxKeyJwtUserId = "userId"
// GetUidFromCtx 从 context 中获取用户 ID
func GetUidFromCtx(ctx context.Context) (int64, error) {
// 尝试从上下文中获取 jwtUserId
jsonUid, ok := ctx.Value(CtxKeyJwtUserId).(json.Number)
if !ok {
return 0, fmt.Errorf("无法获取用户 ID, CtxKeyJwtUserId = %v", CtxKeyJwtUserId)
}
// 转换为 int64
uid, err := jsonUid.Int64()
if err != nil {
return 0, fmt.Errorf("用户 ID 转换失败: %+v", err)
}
return uid, nil
}