This commit is contained in:
2026-03-10 10:47:25 +03:30
parent d07f7d3777
commit 4104bab0c6
64 changed files with 189 additions and 38637 deletions
+3 -3
View File
@@ -6,11 +6,11 @@ import { UtilsModule } from '../utils/utils.module';
import { ConfigService } from '@nestjs/config';
import { AdminModule } from '../admin/admin.module';
import { TokensService } from './services/tokens.service';
import { RestaurantsModule } from '../restaurants/restaurants.module';
import { MikroOrmModule } from '@mikro-orm/nestjs';
import { MikroOrmModule } from '@mikro-orm/nestjs';
import { AdminAuthGuard } from './guards/adminAuth.guard';
import { RefreshToken } from './entities/refresh-token.entity';
import { NotificationsModule } from '../notifications/notifications.module';
import { BusinessModule } from '../business/business.module';
@Module({
imports: [
@@ -30,7 +30,7 @@ import { NotificationsModule } from '../notifications/notifications.module';
inject: [ConfigService],
}),
forwardRef(() => AdminModule),
forwardRef(() => RestaurantsModule),
forwardRef(() => BusinessModule),
MikroOrmModule.forFeature([RefreshToken]),
forwardRef(() => NotificationsModule),
+40 -40
View File
@@ -14,52 +14,52 @@ import { SuperAdminAuthGuard } from '../guards/superAdminAuth.guard';
export class AuthController {
constructor(private readonly authService: AuthService) { }
@Throttle({ default: { limit: 3, ttl: 180_000 } })
@Post('public/auth/otp/request')
@ApiOperation({ summary: 'Request OTP for login or signup' })
@ApiBody({ type: RequestOtpDto, description: 'Mobile number to receive OTP' })
otpRequest(@Body() dto: RequestOtpDto) {
return this.authService.requestOtp(dto, false);
}
// @Throttle({ default: { limit: 3, ttl: 180_000 } })
// @Post('public/auth/otp/request')
// @ApiOperation({ summary: 'Request OTP for login or signup' })
// @ApiBody({ type: RequestOtpDto, description: 'Mobile number to receive OTP' })
// otpRequest(@Body() dto: RequestOtpDto) {
// return this.authService.requestOtp(dto, false);
// }
@RefreshTokenRateLimit()
@ApiOperation({ summary: 'refresh the user access token / refresh token' })
@Post('public/auth/refresh')
refreshToken(@Body() refreshTokenDto: RefreshTokenDto) {
return this.authService.refreshToken(refreshTokenDto.refreshToken);
}
// @RefreshTokenRateLimit()
// @ApiOperation({ summary: 'refresh the user access token / refresh token' })
// @Post('public/auth/refresh')
// refreshToken(@Body() refreshTokenDto: RefreshTokenDto) {
// return this.authService.refreshToken(refreshTokenDto.refreshToken);
// }
@Throttle({ default: { limit: 3, ttl: 180_000 } })
@Post('admin/auth/otp/request')
@ApiOperation({ summary: 'Request OTP for login or signup' })
@ApiBody({ type: RequestOtpDto, description: 'Mobile number to receive OTP' })
otpRequestAdmin(@Body() dto: RequestOtpDto) {
return this.authService.requestOtp(dto, true);
}
// @Throttle({ default: { limit: 3, ttl: 180_000 } })
// @Post('admin/auth/otp/request')
// @ApiOperation({ summary: 'Request OTP for login or signup' })
// @ApiBody({ type: RequestOtpDto, description: 'Mobile number to receive OTP' })
// otpRequestAdmin(@Body() dto: RequestOtpDto) {
// return this.authService.requestOtp(dto, true);
// }
@Post('admin/auth/otp/verify')
@ApiOperation({ summary: 'Verify OTP code' })
@ApiBody({ type: VerifyOtpDto, description: 'Mobile number and OTP code' })
otpVerifyAdmin(@Body() dto: VerifyOtpDto) {
return this.authService.verifyOtpAdmin(dto.phone, dto.slug, dto.otp);
}
// @Post('admin/auth/otp/verify')
// @ApiOperation({ summary: 'Verify OTP code' })
// @ApiBody({ type: VerifyOtpDto, description: 'Mobile number and OTP code' })
// otpVerifyAdmin(@Body() dto: VerifyOtpDto) {
// return this.authService.verifyOtpAdmin(dto.phone, dto.slug, dto.otp);
// }
@RefreshTokenRateLimit()
@ApiOperation({ summary: 'refresh the admin access token / refresh token' })
@Post('admin/auth/refresh')
refreshTokenAdmin(@Body() refreshTokenDto: RefreshTokenDto) {
return this.authService.refreshToken(refreshTokenDto.refreshToken);
}
// @RefreshTokenRateLimit()
// @ApiOperation({ summary: 'refresh the admin access token / refresh token' })
// @Post('admin/auth/refresh')
// refreshTokenAdmin(@Body() refreshTokenDto: RefreshTokenDto) {
// return this.authService.refreshToken(refreshTokenDto.refreshToken);
// }
//super admin routes
// //super admin routes
@UseGuards(SuperAdminAuthGuard)
@Post('super-admin/auth/direct-login')
@ApiOperation({ summary: 'Direct login for DSC - returns login credentials' })
@ApiBody({ type: DirectLoginDto, description: 'Phone number and restaurant slug for direct login' })
directloginForDsc(@Body() dto: DirectLoginDto) {
return this.authService.loginAdminForDsc(dto.phone, dto.slug);
}
// @UseGuards(SuperAdminAuthGuard)
// @Post('super-admin/auth/direct-login')
// @ApiOperation({ summary: 'Direct login for DSC - returns login credentials' })
// @ApiBody({ type: DirectLoginDto, description: 'Phone number and restaurant slug for direct login' })
// directloginForDsc(@Body() dto: DirectLoginDto) {
// return this.authService.loginAdminForDsc(dto.phone, dto.slug);
// }
}
+62 -64
View File
@@ -2,12 +2,11 @@ import { Injectable, BadRequestException } from '@nestjs/common';
import { RequestOtpDto } from '../dto/request-otp.dto';
import { CacheService } from '../../utils/cache.service';
import { SmsService } from '../../notifications/services/sms.service';
import { randomInt } from 'crypto';
import { randomInt } from 'crypto';
import { TokensService } from './tokens.service';
import { RestRepository } from 'src/modules/restaurants/repositories/rest.repository';
import { AuthMessage, RestMessage } from 'src/common/enums/message.enum';
import { AuthMessage, RestMessage } from 'src/common/enums/message.enum';
import { AdminRepository } from 'src/modules/admin/repositories/admin.repository';
import { ConfigService } from '@nestjs/config';
import { ConfigService } from '@nestjs/config';
import { normalizePhone } from '../../utils/phone.util';
@Injectable()
@@ -17,9 +16,8 @@ export class AuthService {
constructor(
private readonly cacheService: CacheService,
private readonly smsService: SmsService,
private readonly tokensService: TokensService,
private readonly restRepository: RestRepository,
private readonly adminRepository: AdminRepository,
private readonly tokensService: TokensService,
private readonly adminRepository: AdminRepository,
private readonly configService: ConfigService,
) {
this.OTP_EXPIRATION_TIME = this.configService.get<number>('OTP_EXPIRATION_TIME') ?? 240;
@@ -33,85 +31,85 @@ export class AuthService {
return `otp-admin:${restaurantSlug}:${phone}`;
}
async requestOtp(dto: RequestOtpDto, isAdmin: boolean) {
const { phone, slug } = dto;
const normalizedPhone = normalizePhone(phone);
if (isAdmin) {
const admin = await this.adminRepository.findByPhoneAndRestaurantSlug(normalizedPhone, slug);
if (!admin) {
throw new BadRequestException(AuthMessage.ADMIN_NOT_FOUND);
}
}
const code = this.generateOtpCode();
const key = isAdmin ? this.adminOtpKey(slug, normalizedPhone) : this.userOtpKey(slug, normalizedPhone);
await this.cacheService.set(key, code, this.OTP_EXPIRATION_TIME);
// async requestOtp(dto: RequestOtpDto, isAdmin: boolean) {
// const { phone, slug } = dto;
// const normalizedPhone = normalizePhone(phone);
await this.smsService.sendotp(normalizedPhone, code);
// if (isAdmin) {
// const admin = await this.adminRepository.findByPhoneAndRestaurantSlug(normalizedPhone, slug);
// if (!admin) {
// throw new BadRequestException(AuthMessage.ADMIN_NOT_FOUND);
// }
// }
// const code = this.generateOtpCode();
// const key = isAdmin ? this.adminOtpKey(slug, normalizedPhone) : this.userOtpKey(slug, normalizedPhone);
// await this.cacheService.set(key, code, this.OTP_EXPIRATION_TIME);
return { code: null };
}
// await this.smsService.sendotp(normalizedPhone, code);
// return { code: null };
// }
async verifyOtpAdmin(phone: string, slug: string, code: string) {
const normalizedPhone = normalizePhone(phone);
const key = this.adminOtpKey(slug, normalizedPhone);
const cachedCode = await this.cacheService.get(key);
if (!cachedCode) throw new BadRequestException('OTP expired or not found');
if (cachedCode !== code) throw new BadRequestException('Invalid OTP');
await this.cacheService.del(key);
// async verifyOtpAdmin(phone: string, slug: string, code: string) {
// const normalizedPhone = normalizePhone(phone);
// const key = this.adminOtpKey(slug, normalizedPhone);
// const cachedCode = await this.cacheService.get(key);
const admin = await this.adminRepository.findByPhoneAndRestaurantSlug(normalizedPhone, slug);
// if (!cachedCode) throw new BadRequestException('OTP expired or not found');
if (!admin) {
throw new BadRequestException(AuthMessage.ADMIN_NOT_FOUND);
}
// if (cachedCode !== code) throw new BadRequestException('Invalid OTP');
// await this.cacheService.del(key);
const rest = await this.restRepository.findOne({ slug });
// // const admin = await this.adminRepository.findByPhoneAndRestaurantSlug(normalizedPhone, slug);
if (!rest) {
throw new BadRequestException(RestMessage.NOT_FOUND);
}
// // if (!admin) {
// // throw new BadRequestException(AuthMessage.ADMIN_NOT_FOUND);
// // }
const tokens = await this.tokensService.generateAccessAndRefreshToken(admin.id, rest.id, true, slug);
// const rest = await this.restRepository.findOne({ slug });
// if (!rest) {
// throw new BadRequestException(RestMessage.NOT_FOUND);
// }
return { tokens, admin };
}
// const tokens = await this.tokensService.generateAccessAndRefreshToken(admin.id, rest.id, true, slug);
// return { tokens, admin };
// }
/**
*
to use for login directly from DSC
*/
async loginAdminForDsc(phone: string, slug: string) {
const normalizedPhone = normalizePhone(phone);
const admin = await this.adminRepository.findByPhoneAndRestaurantSlug(normalizedPhone, slug);
// async loginAdminForDsc(phone: string, slug: string) {
// const normalizedPhone = normalizePhone(phone);
// const admin = await this.adminRepository.findByPhoneAndRestaurantSlug(normalizedPhone, slug);
if (!admin) {
throw new BadRequestException(AuthMessage.ADMIN_NOT_FOUND);
}
// if (!admin) {
// throw new BadRequestException(AuthMessage.ADMIN_NOT_FOUND);
// }
const rest = await this.restRepository.findOne({ slug });
// const rest = await this.restRepository.findOne({ slug });
if (!rest) {
throw new BadRequestException(RestMessage.NOT_FOUND);
}
// if (!rest) {
// throw new BadRequestException(RestMessage.NOT_FOUND);
// }
const tokens = await this.tokensService.generateAccessAndRefreshToken(admin.id, rest.id, true, slug);
// const tokens = await this.tokensService.generateAccessAndRefreshToken(admin.id, rest.id, true, slug);
return { tokens, admin };
}
private generateOtpCode(): string {
const code = randomInt(10000, 100000);
return code.toString();
}
// return { tokens, admin };
// }
refreshToken(oldRefreshToken: string) {
return this.tokensService.refreshToken(oldRefreshToken);
}
// private generateOtpCode(): string {
// const code = randomInt(10000, 100000);
// return code.toString();
// }
// refreshToken(oldRefreshToken: string) {
// return this.tokensService.refreshToken(oldRefreshToken);
// }
}
+6 -7
View File
@@ -9,8 +9,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 {
private readonly logger = new Logger(TokensService.name);
@@ -110,15 +109,15 @@ export class TokensService {
const isAdmin = token.type === RefreshTokenType.ADMIN;
// Verify restaurant still exists
const restaurant = await em.findOne(Restaurant, { id: restId });
if (!restaurant) {
throw new UnauthorizedException(AuthMessage.INVALID_REFRESH_TOKEN);
}
// const restaurant = await em.findOne(Restaurant, { id: restId });
// if (!restaurant) {
// throw new UnauthorizedException(AuthMessage.INVALID_REFRESH_TOKEN);
// }
try {
// Generate new tokens first (before removing old token)
// Pass the transaction EntityManager to ensure operations are within the transaction
const tokens = await this.generateAccessAndRefreshToken(ownerId, restaurant.id, isAdmin, restaurant.slug, em);
const tokens = await this.generateAccessAndRefreshToken(ownerId, "restaurant.id", isAdmin, "restaurant.slug", em);
// Remove old token only after new token is created
em.remove(token);