This commit is contained in:
2025-11-11 15:57:33 +03:30
parent d4db672672
commit 95191f9b30
4 changed files with 21 additions and 77 deletions
+9 -9
View File
@@ -28,7 +28,7 @@ export class AuthController {
@ApiResponse({ status: 200, description: 'OTP verified successfully' }) @ApiResponse({ status: 200, description: 'OTP verified successfully' })
@ApiResponse({ status: 400, description: 'Invalid OTP or expired' }) @ApiResponse({ status: 400, description: 'Invalid OTP or expired' })
otpVerify(@Body() dto: VerifyOtpDto) { otpVerify(@Body() dto: VerifyOtpDto) {
return this.authService.verifyOtp(dto.phone, dto.otp); // assuming dto has `otp` property return this.authService.verifyOtp(dto.phone, dto.slug, dto.otp); // assuming dto has `otp` property
} }
@Post('admin/otp/request') @Post('admin/otp/request')
@@ -40,14 +40,14 @@ export class AuthController {
return this.authService.requestOtpAdmin(dto); return this.authService.requestOtpAdmin(dto);
} }
@Post('admin/otp/verify') // @Post('admin/otp/verify')
@ApiOperation({ summary: 'Verify OTP code' }) // @ApiOperation({ summary: 'Verify OTP code' })
@ApiBody({ type: VerifyOtpDto, description: 'Mobile number and OTP code' }) // @ApiBody({ type: VerifyOtpDto, description: 'Mobile number and OTP code' })
@ApiResponse({ status: 200, description: 'OTP verified successfully' }) // @ApiResponse({ status: 200, description: 'OTP verified successfully' })
@ApiResponse({ status: 400, description: 'Invalid OTP or expired' }) // @ApiResponse({ status: 400, description: 'Invalid OTP or expired' })
adminOtpVerify(@Body() dto: VerifyOtpDto) { // adminOtpVerify(@Body() dto: VerifyOtpDto) {
return this.authService.verifyOtpAdmin(dto.phone, dto.otp); // assuming dto has `otp` property // return this.authService.verifyOtpAdmin(dto.phone, dto.otp); // assuming dto has `otp` property
} // }
@RefreshTokenRateLimit() @RefreshTokenRateLimit()
@ApiOperation({ summary: 'refresh the user access token / refresh token' }) @ApiOperation({ summary: 'refresh the user access token / refresh token' })
+5
View File
@@ -7,6 +7,9 @@ import { JwtModule } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config'; import { ConfigService } from '@nestjs/config';
import { AdminModule } from '../admin/admin.module'; import { AdminModule } from '../admin/admin.module';
import { TokensService } from './services/tokens.service'; import { TokensService } from './services/tokens.service';
import { RestaurantsModule } from '../restaurants/restaurants.module';
import { MikroOrmModule } from '@mikro-orm/nestjs';
import { User } from '../users/entities/user.entity';
@Module({ @Module({
imports: [ imports: [
@@ -23,6 +26,8 @@ import { TokensService } from './services/tokens.service';
inject: [ConfigService], inject: [ConfigService],
}), }),
AdminModule, AdminModule,
RestaurantsModule,
MikroOrmModule.forFeature([User]),
], ],
controllers: [AuthController], controllers: [AuthController],
providers: [AuthService, TokensService], providers: [AuthService, TokensService],
@@ -1,50 +0,0 @@
// guards/jwt-auth.guard.ts
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
import { Request } from 'express';
import { JwtService } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config';
import { AuthEntityType, AuthRequest, JwtPayload } from './auth.guard';
@Injectable()
export class AdminAuthGuard implements CanActivate {
constructor(
private readonly jwtService: JwtService,
private readonly configService: ConfigService,
) {}
async canActivate(context: ExecutionContext) {
const request = context.switchToHttp().getRequest<AuthRequest>();
try {
const secret = this.configService.get<string>('JWT_SECRET');
const token = this.extractTokenFromHeader(request);
if (!token) {
throw new UnauthorizedException();
}
try {
const payload = await this.jwtService.verifyAsync<JwtPayload>(token, {
secret,
});
if (payload.type !== AuthEntityType.ADMIN) {
throw new UnauthorizedException('Access denied. Admin rights required.');
}
// 💡 We're assigning the payload to the request object here
// so that we can access it in our route handlers
request['user'] = payload;
} catch {
throw new UnauthorizedException();
}
return true;
} catch (err) {
console.log('error in AuthGuard', err);
throw new UnauthorizedException('Invalid or expired token');
}
}
private extractTokenFromHeader(request: Request): string | undefined {
const [type, token] = request.headers.authorization?.split(' ') ?? [];
return type === 'Bearer' ? token : undefined;
}
}
+6 -17
View File
@@ -1,22 +1,12 @@
// guards/jwt-auth.guard.ts
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common'; import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
import { Request } from 'express'; import { Request } from 'express';
import { JwtService } from '@nestjs/jwt'; import { JwtService } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config'; import { ConfigService } from '@nestjs/config';
import { ITokenPayload } from '../interfaces/IToken-payload';
export enum AuthEntityType {
USER = 'user',
ADMIN = 'admin',
}
export interface AuthRequest extends Request { export interface AuthRequest extends Request {
user: { userId: string;
sub: string; // userId
slug: string; slug: string;
};
}
export interface JwtPayload {
sub: string; // The userId
type: AuthEntityType;
} }
@Injectable() @Injectable()
@@ -37,13 +27,12 @@ export class AuthGuard implements CanActivate {
} }
try { try {
const payload = await this.jwtService.verifyAsync<JwtPayload>(token, { const payload = await this.jwtService.verifyAsync<ITokenPayload>(token, {
secret, secret,
}); });
if (payload.type !== AuthEntityType.USER) {
throw new UnauthorizedException('Access denied. User rights required.'); request['userId'] = payload.id;
} request['slug'] = payload.restId;
request['user'] = payload;
} catch { } catch {
throw new UnauthorizedException(); throw new UnauthorizedException();
} }