update auth
This commit is contained in:
@@ -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();
|
||||
|
||||
Reference in New Issue
Block a user