feat(challenges): 支持公开访问挑战列表与详情接口
- 在 GET /challenges、GET /challenges/:id、GET /challenges/:id/rankings 添加 @Public() 装饰器,允许未登录用户访问 - 将 userId 改为可选参数,未登录时仍可返回基础数据 - 列表接口过滤掉 UPCOMING 状态挑战,仅展示进行中/已结束 - 返回 DTO 新增 unit 字段,用于前端展示进度单位 - 鉴权守卫优化:公开接口若携带 token 仍尝试解析并注入 user,方便后续业务逻辑
This commit is contained in:
@@ -17,21 +17,35 @@ export class JwtAuthGuard implements CanActivate {
|
||||
context.getClass(),
|
||||
]);
|
||||
|
||||
if (isPublic) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const request = context.switchToHttp().getRequest();
|
||||
const authHeader = request.headers.authorization;
|
||||
|
||||
this.logger.log(`authHeader: ${authHeader}`);
|
||||
this.logger.log(`authHeader: ${authHeader}, isPublic: ${isPublic}`);
|
||||
|
||||
const token = this.appleAuthService.extractTokenFromHeader(authHeader);
|
||||
|
||||
if (isPublic) {
|
||||
// 公开接口如果有 token,也可以尝试获取用户信息
|
||||
if (token) {
|
||||
try {
|
||||
const payload = this.appleAuthService.verifyAccessToken(token);
|
||||
this.logger.log(`鉴权成功: ${JSON.stringify(payload)}, token: ${token}`);
|
||||
// 将用户信息添加到请求对象中
|
||||
request.user = payload;
|
||||
} catch (error) {
|
||||
this.logger.error(`鉴权失败: ${error.message}, token: ${token}`);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
|
||||
if (!authHeader) {
|
||||
throw new UnauthorizedException('缺少授权头');
|
||||
}
|
||||
|
||||
try {
|
||||
const token = this.appleAuthService.extractTokenFromHeader(authHeader);
|
||||
const payload = this.appleAuthService.verifyAccessToken(token);
|
||||
|
||||
this.logger.log(`鉴权成功: ${JSON.stringify(payload)}, token: ${token}`);
|
||||
|
||||
Reference in New Issue
Block a user