Refactor AdminAuthController and AuthService to implement admin-specific token refresh functionality; update TokensService to handle refresh token logic with improved transaction management and error handling.
This commit is contained in:
@@ -36,10 +36,10 @@ export class TokensService {
|
||||
);
|
||||
}
|
||||
|
||||
async generateTokensAdmin(admin: Admin, rest: Restaurant, em?: EntityManager) {
|
||||
async generateTokensAdmin(adminId: string, rest: Restaurant, em?: EntityManager) {
|
||||
return this.generateAccessAndRefreshTokenAdmin(
|
||||
{
|
||||
adminId: admin.id,
|
||||
adminId,
|
||||
restId: rest.id,
|
||||
},
|
||||
em,
|
||||
@@ -219,6 +219,52 @@ export class TokensService {
|
||||
}
|
||||
}
|
||||
|
||||
async refreshTokenAdmin(oldRefreshToken: string) {
|
||||
const entityManager = this.em.fork();
|
||||
|
||||
try {
|
||||
await entityManager.begin();
|
||||
console.log('oldRefreshToken', oldRefreshToken);
|
||||
const token = await entityManager.findOne(
|
||||
RefreshToken,
|
||||
{ token: oldRefreshToken },
|
||||
{
|
||||
populate: ['restaurant'],
|
||||
},
|
||||
);
|
||||
|
||||
if (!token) throw new UnauthorizedException(AuthMessage.INVALID_REFRESH_TOKEN);
|
||||
|
||||
// const rest = await this.restRepository.findOne({ id: token.user.id });
|
||||
// if (!rest) throw new UnauthorizedException(AuthMessage.INVALID_REFRESH_TOKEN);
|
||||
|
||||
if (dayjs(token.expiresAt).isBefore(dayjs())) {
|
||||
entityManager.remove(token);
|
||||
await entityManager.flush();
|
||||
await entityManager.commit();
|
||||
throw new UnauthorizedException(AuthMessage.REFRESH_TOKEN_EXPIRED);
|
||||
}
|
||||
|
||||
// Remove the old token
|
||||
entityManager.remove(token);
|
||||
|
||||
// Generate new tokens within the same transaction
|
||||
const tokens = await this.generateTokensAdmin(token.ownerId, token.restaurant, entityManager);
|
||||
|
||||
// Commit the transaction
|
||||
await entityManager.flush();
|
||||
await entityManager.commit();
|
||||
|
||||
return tokens;
|
||||
} catch (error) {
|
||||
this.logger.error(error);
|
||||
if (entityManager.isInTransaction()) {
|
||||
await entityManager.rollback();
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async invalidateRefreshToken(userId: string) {
|
||||
const entityManager = this.em.fork();
|
||||
|
||||
|
||||
Reference in New Issue
Block a user