This commit is contained in:
2025-11-11 15:58:02 +03:30
parent 111540bb15
commit 046286b559
4 changed files with 21 additions and 51 deletions
+2 -29
View File
@@ -1,4 +1,4 @@
import { Injectable, BadRequestException, UnauthorizedException, NotFoundException } from '@nestjs/common';
import { Injectable, BadRequestException, NotFoundException } from '@nestjs/common';
import { RequestOtpDto } from '../dto/request-otp.dto';
import { CacheService } from '../../utils/cache.service';
import { SmsService } from '../../utils/sms.service';
@@ -6,10 +6,8 @@ import { UserService } from '../../users/user.service';
import { randomInt } from 'crypto';
import { JwtService } from '@nestjs/jwt';
import { AdminService } from '../../admin/admin.service';
import { AuthEntityType } from 'src/modules/auth/guards/auth.guard';
import { TokensService } from './tokens.service';
import { RestaurantsService } from 'src/modules/restaurants/restaurants.service';
import { RestRepository } from 'src/modules/restaurants/repositories/user.repository';
import { RestRepository } from 'src/modules/restaurants/repositories/rest.repository';
import { RestMessage } from 'src/common/enums/message.enum';
@Injectable()
@@ -18,7 +16,6 @@ export class AuthService {
private readonly cacheService: CacheService,
private readonly smsService: SmsService,
private readonly userService: UserService,
private readonly jwtService: JwtService,
private readonly adminService: AdminService,
private readonly tokensService: TokensService,
private readonly restRepository: RestRepository,
@@ -70,35 +67,11 @@ export class AuthService {
return { success: true, message: 'User registered successfully!', tokens };
}
async verifyOtpAdmin(phone: string, code: string) {
const cachedCode = await this.cacheService.get(`otp-admin:${phone}`);
if (!cachedCode) throw new BadRequestException('OTP expired or not found');
if (cachedCode !== code) throw new BadRequestException('Invalid OTP');
await this.cacheService.del(`otp:${phone}`);
const admin = await this.adminService.findByPhone(phone);
if (!admin) {
throw new UnauthorizedException();
}
const accessToken = await this.issueToken(admin.id.toString(), AuthEntityType.ADMIN);
return { success: true, message: 'successfully!', accessToken };
}
private generateOtpCode(): string {
const code = randomInt(10000, 100000);
return code.toString();
}
private issueToken(id: string, entityType: AuthEntityType) {
const payload = {
sub: id,
type: entityType,
};
return this.jwtService.signAsync(payload);
}
refreshToken(oldRefreshToken: string) {
return this.tokensService.refreshToken(oldRefreshToken);
}
+6 -1
View File
@@ -11,6 +11,7 @@ import { RefreshToken } from '../../users/entities/refresh-token.entity';
import { User } from '../../users/entities/user.entity';
import { ITokenPayload } from '../interfaces/IToken-payload';
import { Restaurant } from 'src/modules/restaurants/entities/restaurant.entity';
import { RestRepository } from 'src/modules/restaurants/repositories/rest.repository';
@Injectable()
export class TokensService {
@@ -19,6 +20,7 @@ export class TokensService {
private readonly configService: ConfigService,
private readonly jwtService: JwtService,
private readonly em: EntityManager,
private readonly restRepository: RestRepository,
) {}
async generateTokens(user: User, rest: Restaurant, em?: EntityManager) {
@@ -107,6 +109,9 @@ export class TokensService {
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();
@@ -118,7 +123,7 @@ export class TokensService {
entityManager.remove(token);
// Generate new tokens within the same transaction
const tokens = await this.generateTokens(token.user, entityManager);
const tokens = await this.generateTokens(token.user, rest, entityManager);
// Commit the transaction
await entityManager.flush();
@@ -1,6 +0,0 @@
import { EntityRepository } from '@mikro-orm/postgresql';
import type { Restaurant } from '../entities/restaurant.entity';
// import { PaginationUtils } from '../../utils/services/pagination.utils';
export class RestRepository extends EntityRepository<Restaurant> {}
+13 -15
View File
@@ -1,10 +1,8 @@
import { Controller, Get, Req, UseGuards, Query, ValidationPipe } from '@nestjs/common';
import { Controller, Get, Req, UseGuards } from '@nestjs/common';
import { ApiTags, ApiBearerAuth, ApiOperation } from '@nestjs/swagger';
import { AuthGuard, type AuthRequest } from 'src/modules/auth/guards/auth.guard';
import { UserService } from './user.service';
// import { UpdateUserDto } from './dto/update-user.dto';
import { FindUsersDto } from './dto/find-user.dto';
import { AdminAuthGuard } from 'src/modules/auth/guards/auth.admin.guard';
@ApiTags('User')
@Controller('user')
@@ -16,7 +14,7 @@ export class UserController {
@ApiOperation({ summary: 'Get the current authenticated user profile' })
@Get('/me')
async getUser(@Req() req: AuthRequest) {
const userId = req.user.sub;
const userId = req.userId;
const user = await this.userService.findById(userId);
return {
message: `GET request: Retrieving profile for authenticated user `,
@@ -40,15 +38,15 @@ export class UserController {
// };
// }
@UseGuards(AdminAuthGuard)
@ApiBearerAuth()
@ApiOperation({ summary: 'Users : Admin Route' })
@Get('/admin/users')
async findAll(
// Use ValidationPipe to validate and transform the DTO
@Query(new ValidationPipe({ transform: true, whitelist: true }))
query: FindUsersDto,
) {
return this.userService.findAll(query);
}
// @UseGuards(AdminAuthGuard)
// @ApiBearerAuth()
// @ApiOperation({ summary: 'Users : Admin Route' })
// @Get('/admin/users')
// async findAll(
// // Use ValidationPipe to validate and transform the DTO
// @Query(new ValidationPipe({ transform: true, whitelist: true }))
// query: FindUsersDto,
// ) {
// return this.userService.findAll(query);
// }
}