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:
2025-11-18 14:29:00 +03:30
parent 3fc7cccb80
commit a53c0a5b13
3 changed files with 54 additions and 4 deletions
+48 -2
View File
@@ -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();