feat: Add error handling for invalid token in JwtAuthGuard

This commit is contained in:
M1000fr 2024-12-11 18:51:48 +01:00
parent 80ce7d7f16
commit 28e42b2248
2 changed files with 32 additions and 3 deletions

View File

@ -47,9 +47,13 @@ export class JwtAuthGuard implements CanActivate {
algorithms: ["RS256"], algorithms: ["RS256"],
}); });
let user = await this.userService.findByProviderId( if (typeof verifiedToken == "string")
verifiedToken.sub.toString(), throw new UnauthorizedException("Invalid token");
);
let user = await this.userService.findOrCreateByProviderId({
providerId: verifiedToken.sub.toString(),
username: verifiedToken.preferred_username,
});
request.user = user; request.user = user;

View File

@ -45,6 +45,31 @@ export class UserService {
}); });
} }
async findOrCreateByProviderId({
providerId,
username,
}: {
providerId: string;
username: string;
}) {
let user = await this.prisma.user.findUnique({
where: {
providerId,
username,
},
});
if (!user)
user = await this.prisma.user.create({
data: {
providerId,
username,
},
});
return user;
}
async create(createUserDto: CreateUserDTO) { async create(createUserDto: CreateUserDTO) {
return await this.prisma.user.create({ return await this.prisma.user.create({
data: { data: {