Skip to content

Commit

Permalink
feat: fix refresh token constraint
Browse files Browse the repository at this point in the history
  • Loading branch information
Psami-wondah committed Feb 6, 2025
1 parent 50e41ac commit c8d2265
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 8 deletions.
1 change: 0 additions & 1 deletion src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,6 @@ export class AuthController {
};
}

@UseGuards(AuthGuard)
@Post("/resend-email-otp")
async resendEmailOtp(
@Body() data: ResendOtpEmailDto,
Expand Down
17 changes: 11 additions & 6 deletions src/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,11 +86,7 @@ export class AuthService {
Number(this.configService.get<string>("REFRESH_TOKEN_EXPIRE_DAYS")),
);

await this.refreshTokenModel.findOneAndUpdate(
{ userId: user._id },
{ token, expiresAt },
{ upsert: true, new: true },
);
await this.refreshTokenModel.create({ userId: user._id, token, expiresAt });

return { token, expiry: expiresAt };
}
Expand Down Expand Up @@ -130,6 +126,16 @@ export class AuthService {
if (!user) {
throw new UnauthorizedException("Invalid or expired refresh token");
}
try {
await this.jwtService.verifyAsync(refreshToken, {
secret: this.configService.get<string>("REFRESH_SECRET_KEY"),
});
} catch {
throw new UnauthorizedException("Invalid or expired refresh token");
}

// remove the old token
await this.refreshTokenModel.deleteOne({ token: refreshToken });

return await this.generateTokensForUser(user);
}
Expand Down Expand Up @@ -227,7 +233,6 @@ export class AuthService {
};
}

// TODO: Protect with Auth
async resendEmailVerificationOtp(data: ResendOtpEmailDto): Promise<{
message: string;
}> {
Expand Down
2 changes: 1 addition & 1 deletion src/auth/schemas/refresh-token.schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ export type RefreshTokenDocument = HydratedDocument<RefreshToken>;

@Schema({ timestamps: true })
export class RefreshToken {
@Prop({ required: true, unique: true, ref: "User" })
@Prop({ required: true, ref: "User" })
userId: Types.ObjectId;

@Prop({ required: true })
Expand Down

0 comments on commit c8d2265

Please sign in to comment.