update auth

This commit is contained in:
2025-12-09 16:28:50 +03:30
parent f2094f87c5
commit 07f3006aef
4 changed files with 24 additions and 5 deletions
+8 -3
View File
@@ -8,6 +8,7 @@ import dayjs from 'dayjs';
import { AuthMessage } from '../../../common/enums/message.enum';
import { RefreshToken, RefreshTokenType } from '../entities/refresh-token.entity';
import { IAdminTokenPayload, ITokenPayload } from '../interfaces/IToken-payload';
import { Restaurant } from 'src/modules/restaurants/entities/restaurant.entity';
@Injectable()
export class TokensService {
@@ -18,13 +19,13 @@ export class TokensService {
private readonly em: EntityManager,
) {}
async generateAccessAndRefreshToken(ownerId: string, restaurantId: string, isAdmin: boolean) {
async generateAccessAndRefreshToken(ownerId: string, restaurantId: string, isAdmin: boolean, slug: string) {
const refreshExpire = this.configService.getOrThrow<number>('REFRESH_TOKEN_EXPIRE');
const accessExpire = this.configService.getOrThrow<number>('JWT_EXPIRATION_TIME');
const payload: ITokenPayload | IAdminTokenPayload = isAdmin
? { adminId: ownerId, restId: restaurantId }
: { userId: ownerId, restId: restaurantId };
: { userId: ownerId, restId: restaurantId, slug };
const accessToken = await this.generateAccessToken(payload, accessExpire);
const refreshToken = this.generateRefreshToken();
@@ -78,12 +79,16 @@ export class TokensService {
const ownerId = token.ownerId;
const restId = token.restId;
const restaurant = await this.em.findOne(Restaurant, { id: restId });
if (!restaurant) {
throw new UnauthorizedException(AuthMessage.INVALID_REFRESH_TOKEN);
}
// Remove the old token
this.em.remove(token);
const isAdmin = token.type === RefreshTokenType.ADMIN;
try {
// Generate new tokens
const tokens = await this.generateAccessAndRefreshToken(ownerId, restId, isAdmin);
const tokens = await this.generateAccessAndRefreshToken(ownerId, restId, isAdmin, restaurant.slug);
// Commit the transaction
await this.em.flush();