feat: add admin auth

This commit is contained in:
2026-06-01 18:08:38 +03:30
parent 967b96184a
commit 39e6c96113
12 changed files with 121 additions and 12 deletions
@@ -0,0 +1,21 @@
import { Body, Controller, HttpCode, Post } from '@nestjs/common';
import { AdminAuthService } from './providers/admin-auth.service';
import { AdminLoginDTO } from './dtos/admin-login.dto';
import { Public } from '@/modules/auth/decorators/public.decorator';
@Controller('admin/auth')
export class AdminAuthController {
constructor(
/**
* Inject Admin Auth Service
*/
private readonly adminAuthService: AdminAuthService,
) {}
@Public()
@Post('login')
@HttpCode(200)
public async login(@Body() adminLoginDto: AdminLoginDTO) {
return await this.adminAuthService.login(adminLoginDto);
}
}
@@ -0,0 +1,23 @@
import { PhoneDTO } from '@/modules/auth/dtos/login.dto';
import { IsNotEmpty, IsString } from 'class-validator';
import { i18nValidationMessage as t } from 'nestjs-i18n';
export class AdminLoginDTO extends PhoneDTO {
// @ApiProperty({
// type: 'string',
// description: 'Password for User Account',
// example: 'Password1@',
// required: true,
// })
@IsNotEmpty({
message: t('validation.requiredField', {
field: '$t(auth.fields.password)',
}),
})
@IsString({
message: t('validation.wrongFieldFormat', {
field: '$t(auth.fields.password)',
}),
})
password: string;
}
@@ -0,0 +1,7 @@
POST http://localhost:3000/admin/auth/login
Content-Type: application/json
{
"phone": "0933302636",
"password": "Password1@"
}
@@ -0,0 +1,52 @@
import { HashingProvider } from '@/common/modules/hashing/providers/hashing.provider';
import { GenerateTokenProvider } from '@/modules/auth/providers/generate-token.provider';
import { UsersService } from '@/modules/users/providers/users.service';
import {
ForbiddenException,
Injectable,
UnauthorizedException,
} from '@nestjs/common';
import { AdminLoginDTO } from '../dtos/admin-login.dto';
import { Role } from '@/common/enums/roles.enum';
import { randomUUID } from 'crypto';
@Injectable()
export class AdminAuthService {
constructor(
/**
* Inject Users Service
*/
private readonly usersService: UsersService,
/**
* Inject Generate Tokens Provider
*/
private readonly generateTokenProvider: GenerateTokenProvider,
/**
* Inject Hashing Provider
*/
private readonly hashingProvider: HashingProvider,
) {}
public async login(adminLoginDto: AdminLoginDTO) {
const { phone, password } = adminLoginDto;
const user = await this.usersService.findOneByPhone(phone);
const isPasswordCorrect = await this.hashingProvider.compare(
password,
user?.password || '',
);
if (!user || !isPasswordCorrect) {
throw new UnauthorizedException('auth.errors.wrongPhoneOrPass');
}
if ([Role.ADMIN, Role.SUPERUSER].includes(user.role)) {
const jti = randomUUID();
return await this.generateTokenProvider.generateTokens(user, jti);
}
throw new ForbiddenException('auth.errors.accessDenied');
}
}