Skip to content

Commit 349e12c

Browse files
authored
Merge pull request #22 from minorcell/djh
Djh
2 parents 28ffcc5 + ffc85e3 commit 349e12c

4 files changed

Lines changed: 64 additions & 26 deletions

File tree

src/auth/auth.service.ts

Lines changed: 44 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { UsercenterService } from './../usercenter/usercenter.service';
2-
import { Injectable, UnauthorizedException } from '@nestjs/common';
2+
import { Injectable, UnauthorizedException, NotFoundException, BadRequestException } from '@nestjs/common';
33
import { JwtService } from '@nestjs/jwt';
44

55
@Injectable()
@@ -10,32 +10,51 @@ export class AuthService {
1010
) {}
1111

1212
async signIn(username: string, pass: string): Promise<any> {
13-
const user = await this.usersService.findOne(username);
13+
try {
14+
const user = await this.usersService.findOne(username);
1415

15-
// 直接使用用户密码进行验证
16-
if (user?.userPassword !== pass) {
17-
throw new UnauthorizedException();
18-
}
16+
// 直接使用用户密码进行验证
17+
if (user?.userPassword !== pass) {
18+
throw new UnauthorizedException('用户名或密码错误');
19+
}
1920

20-
const payload = { sub: user.userId, username: user.userName };
21-
const refreshPayload = { sub: user.userId };
22-
23-
return {
24-
userId: user.userId,
25-
access_token: await this.jwtService.signAsync(payload, {
26-
expiresIn: '7d',
27-
}),
28-
refresh_token: await this.jwtService.signAsync(refreshPayload, {
29-
expiresIn: '7d',
30-
}),
31-
};
21+
const payload = { sub: user.userId, username: user.userName };
22+
const refreshPayload = { sub: user.userId };
23+
24+
return {
25+
userId: user.userId,
26+
access_token: await this.jwtService.signAsync(payload, {
27+
expiresIn: '7d',
28+
}),
29+
refresh_token: await this.jwtService.signAsync(refreshPayload, {
30+
expiresIn: '7d',
31+
}),
32+
};
33+
} catch (error) {
34+
// 捕获findOne方法抛出的NotFoundException异常并将其转换为UnauthorizedException
35+
// 这样用户名不存在和密码错误都返回相同的401状态码
36+
if (error instanceof NotFoundException) {
37+
throw new UnauthorizedException('用户名或密码错误');
38+
}
39+
throw error;
40+
}
3241
}
3342

3443
async refreshToken(refresh_token: string) {
3544
try {
45+
// 如果refresh_token为空或无效格式,返回400错误
46+
if (!refresh_token || typeof refresh_token !== 'string') {
47+
throw new BadRequestException('无效的refresh_token格式');
48+
}
49+
50+
// 验证token
3651
const decoded = await this.jwtService.verifyAsync(refresh_token);
3752

53+
// 确保用户存在
3854
const user = await this.usersService.findOne(decoded.sub);
55+
if (!user) {
56+
throw new NotFoundException('用户不存在');
57+
}
3958

4059
const access_token = await this.jwtService.signAsync(
4160
{ id: decoded.sub, userName: user.userName },
@@ -47,8 +66,13 @@ export class AuthService {
4766
{ expiresIn: '7d' },
4867
);
4968
return { refresh_token: newRefresh_token, access_token };
50-
} catch {
51-
throw new UnauthorizedException('refresh_token已过期');
69+
} catch (error) {
70+
// 区分不同类型的错误
71+
if (error instanceof BadRequestException || error instanceof NotFoundException) {
72+
throw error; // 重新抛出原始错误
73+
}
74+
// JWT相关错误统一处理为401未授权
75+
throw new UnauthorizedException('refresh_token无效或已过期');
5276
}
5377
}
5478
}

src/usercenter/dto/create-usercenter.dto.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,4 +33,8 @@ export class CreateUsercenterDto {
3333
@Min(0, { message: '性别值必须大于等于0' })
3434
@Max(2, { message: '性别值必须小于等于2' })
3535
sex?: number; // 性别,0未知,1男,2女
36+
37+
@IsOptional()
38+
@IsString()
39+
avatar?: string; // 用户头像
3640
}

src/usercenter/entities/usercenter.entity.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,13 @@ export class UserEntity {
124124
})
125125
userPassword: string; // 用户密码
126126

127+
@Column({
128+
type: 'varchar',
129+
name: 'avatar',
130+
default: ''
131+
})
132+
avatar: string; // 头像
133+
127134
// 关联文章,一个用户可以有多篇文章
128135
@OneToMany(() => ArticleEntity, (article) => article.user)
129136
articles: ArticleEntity[];

src/usercenter/usercenter.service.ts

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ import {
22
BadRequestException,
33
Injectable,
44
InternalServerErrorException,
5+
NotFoundException,
6+
ConflictException
57
} from '@nestjs/common';
68
import { CreateUsercenterDto } from './dto/create-usercenter.dto';
79
import { UpdateUsercenterDto } from './dto/update-usercenter.dto';
@@ -29,15 +31,15 @@ export class UsercenterService {
2931
where: [{ userName: createUsercenterDto.userName }],
3032
});
3133
if (existingUser) {
32-
throw new BadRequestException('用户名已存在');
34+
throw new ConflictException('用户名已存在');
3335
}
3436

3537
// 检查邮箱是否已存在
3638
const existingEmail = await this.userRepository.findOne({
3739
where: [{ userEmail: createUsercenterDto.userEmail }],
3840
});
3941
if (existingEmail) {
40-
throw new BadRequestException('邮箱已被注册');
42+
throw new ConflictException('邮箱已被注册');
4143
}
4244

4345
await validateOrReject(createUsercenterDto);
@@ -74,8 +76,9 @@ export class UsercenterService {
7476
take: limit, // 每页记录数
7577
order: { createTime: 'DESC' }, // 按创建时间倒序排列
7678
});
79+
// 如果没有数据,返回空数组,不抛出异常
7780
if (total === 0) {
78-
throw new InternalServerErrorException(`数量为0`);
81+
return { total: 0, data: [], message: '没有数据', status: 200 };
7982
}
8083

8184
return { total, data, message: '查询成功', status: 200 };
@@ -146,7 +149,7 @@ export class UsercenterService {
146149
});
147150
}
148151
if (!user) {
149-
throw new InternalServerErrorException(`未找到匹配 ${identifier} 的记录`);
152+
throw new NotFoundException(`未找到匹配 ${identifier} 的记录`);
150153
}
151154

152155
return user;
@@ -155,7 +158,7 @@ export class UsercenterService {
155158
async update(id: number, updateUsercenterDto: UpdateUsercenterDto) {
156159
const user = await this.userRepository.findOneBy({ userId: id });
157160
if (!user) {
158-
throw new InternalServerErrorException(`用户 ID 为 ${id} 的记录不存在`);
161+
throw new NotFoundException(`用户 ID 为 ${id} 的记录不存在`);
159162
}
160163

161164
// 合并更新数据
@@ -172,7 +175,7 @@ export class UsercenterService {
172175
async remove(id: number) {
173176
const user = await this.userRepository.findOneBy({ userId: id });
174177
if (!user) {
175-
throw new InternalServerErrorException(`用户 ID 为 ${id} 的记录不存在`);
178+
throw new NotFoundException(`用户 ID 为 ${id} 的记录不存在`);
176179
}
177180
const data = await this.userRepository.delete(id);
178181

0 commit comments

Comments
 (0)