style: apply standard ESLint & Prettier formatting across backend
Deploy Canina / deploy (push) Successful in 4m58s
Deploy Canina / deploy (push) Successful in 4m58s
This commit is contained in:
1 parent
ae636c8b03
commit
62bd8811fa
66 files changed
+1398
-607
No files matched your search
@@ -7,16 +7,18 @@ describe('AuthController', () => {
|
||||
let service: AuthService;
|
||||
|
||||
const mockAuthService = {
|
||||
sendOtp: jest.fn().mockResolvedValue({ success: true, message: 'کد تایید ارسال شد' }),
|
||||
verifyOtp: jest.fn().mockResolvedValue({ success: true, data: { accessToken: 'token' } }),
|
||||
sendOtp: jest
|
||||
.fn()
|
||||
.mockResolvedValue({ success: true, message: 'کد تایید ارسال شد' }),
|
||||
verifyOtp: jest
|
||||
.fn()
|
||||
.mockResolvedValue({ success: true, data: { accessToken: 'token' } }),
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
controllers: [AuthController],
|
||||
providers: [
|
||||
{ provide: AuthService, useValue: mockAuthService },
|
||||
],
|
||||
providers: [{ provide: AuthService, useValue: mockAuthService }],
|
||||
}).compile();
|
||||
|
||||
controller = module.get<AuthController>(AuthController);
|
||||
|
||||
@@ -4,7 +4,13 @@ import { SendOtpDto } from './dto/send-otp.dto';
|
||||
import { VerifyOtpDto } from './dto/verify-otp.dto';
|
||||
import { RegisterDto } from './dto/register.dto';
|
||||
import { LoginDto } from './dto/login.dto';
|
||||
import { ApiTags, ApiOperation, ApiResponse, ApiOkResponse, ApiBadRequestResponse } from '@nestjs/swagger';
|
||||
import {
|
||||
ApiTags,
|
||||
ApiOperation,
|
||||
ApiResponse,
|
||||
ApiOkResponse,
|
||||
ApiBadRequestResponse,
|
||||
} from '@nestjs/swagger';
|
||||
|
||||
@ApiTags('Auth - احراز هویت')
|
||||
@Controller('auth')
|
||||
@@ -16,9 +22,9 @@ import { ApiTags, ApiOperation, ApiResponse, ApiOkResponse, ApiBadRequestRespons
|
||||
success: false,
|
||||
message: 'خطای ناشناخته در سرور رخ داده است',
|
||||
code: 'SERVER_ERROR',
|
||||
details: {}
|
||||
}
|
||||
}
|
||||
details: {},
|
||||
},
|
||||
},
|
||||
})
|
||||
export class AuthController {
|
||||
constructor(private readonly authService: AuthService) {}
|
||||
@@ -32,9 +38,9 @@ export class AuthController {
|
||||
example: {
|
||||
success: true,
|
||||
message: 'کد تایید ارسال شد',
|
||||
code: '12345'
|
||||
}
|
||||
}
|
||||
code: '12345',
|
||||
},
|
||||
},
|
||||
})
|
||||
@ApiBadRequestResponse({
|
||||
description: 'فرمت شماره تلفن همراه نامعتبر است',
|
||||
@@ -44,10 +50,10 @@ export class AuthController {
|
||||
message: 'شماره موبایل نامعتبر است',
|
||||
code: 'BAD_REQUEST',
|
||||
details: {
|
||||
message: ['شماره موبایل نامعتبر است']
|
||||
}
|
||||
}
|
||||
}
|
||||
message: ['شماره موبایل نامعتبر است'],
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
sendOtp(@Body() sendOtpDto: SendOtpDto) {
|
||||
return this.authService.sendOtp(sendOtpDto);
|
||||
@@ -72,12 +78,12 @@ export class AuthController {
|
||||
walletBalance: '0.00',
|
||||
charityDonationTotal: '0.00',
|
||||
createdAt: '2026-05-26T15:20:00.000Z',
|
||||
updatedAt: '2026-05-26T15:20:00.000Z'
|
||||
updatedAt: '2026-05-26T15:20:00.000Z',
|
||||
},
|
||||
accessToken: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...'
|
||||
}
|
||||
}
|
||||
}
|
||||
accessToken: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...',
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
@ApiBadRequestResponse({
|
||||
description: 'کد تایید اشتباه یا منقضی شده است',
|
||||
@@ -86,9 +92,9 @@ export class AuthController {
|
||||
success: false,
|
||||
message: 'کد تایید اشتباه است',
|
||||
code: 'OTP_INVALID',
|
||||
details: {}
|
||||
}
|
||||
}
|
||||
details: {},
|
||||
},
|
||||
},
|
||||
})
|
||||
verifyOtp(@Body() verifyOtpDto: VerifyOtpDto) {
|
||||
return this.authService.verifyOtp(verifyOtpDto);
|
||||
@@ -98,7 +104,9 @@ export class AuthController {
|
||||
@HttpCode(HttpStatus.CREATED)
|
||||
@ApiOperation({ summary: 'ثبتنام با ایمیل/موبایل و رمز عبور' })
|
||||
@ApiOkResponse({ description: 'کاربر با موفقیت ثبتنام شد' })
|
||||
@ApiBadRequestResponse({ description: 'اطلاعات ثبتنام نامعتبر است یا کاربر از قبل وجود دارد' })
|
||||
@ApiBadRequestResponse({
|
||||
description: 'اطلاعات ثبتنام نامعتبر است یا کاربر از قبل وجود دارد',
|
||||
})
|
||||
register(@Body() registerDto: RegisterDto) {
|
||||
return this.authService.register(registerDto);
|
||||
}
|
||||
|
||||
@@ -88,11 +88,19 @@ describe('AuthService', () => {
|
||||
const mockUser = { id: 'user-id', mobile: '09123456789' };
|
||||
mockPrisma.user.findUnique.mockResolvedValue(mockUser);
|
||||
|
||||
const result = await service.verifyOtp({ phoneNumber: '09123456789', code: '12345' });
|
||||
|
||||
const result = await service.verifyOtp({
|
||||
phoneNumber: '09123456789',
|
||||
code: '12345',
|
||||
});
|
||||
|
||||
expect(redis.del).toHaveBeenCalledWith('otp:09123456789');
|
||||
expect(prisma.user.findUnique).toHaveBeenCalledWith({ where: { mobile: '09123456789' } });
|
||||
expect(jwt.sign).toHaveBeenCalledWith({ sub: 'user-id', phoneNumber: '09123456789' });
|
||||
expect(prisma.user.findUnique).toHaveBeenCalledWith({
|
||||
where: { mobile: '09123456789' },
|
||||
});
|
||||
expect(jwt.sign).toHaveBeenCalledWith({
|
||||
sub: 'user-id',
|
||||
phoneNumber: '09123456789',
|
||||
});
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.data.accessToken).toBe('mock-jwt-token');
|
||||
expect(result.data.user).toEqual(mockUser);
|
||||
@@ -104,7 +112,10 @@ describe('AuthService', () => {
|
||||
const newUser = { id: 'new-user-id', mobile: '09123456789' };
|
||||
mockPrisma.user.create.mockResolvedValue(newUser);
|
||||
|
||||
const result = await service.verifyOtp({ phoneNumber: '09123456789', code: '12345' });
|
||||
const result = await service.verifyOtp({
|
||||
phoneNumber: '09123456789',
|
||||
code: '12345',
|
||||
});
|
||||
expect(prisma.user.create).toHaveBeenCalled();
|
||||
expect(result.data.user).toEqual(newUser);
|
||||
});
|
||||
|
||||
@@ -33,20 +33,28 @@ export class AuthService {
|
||||
const savedCode = await this.redisService.get(`otp:${phoneNumber}`);
|
||||
|
||||
if (!savedCode) {
|
||||
throw new BadRequestException({ message: 'کد تایید منقضی شده است', error: 'OTP_EXPIRED' });
|
||||
throw new BadRequestException({
|
||||
message: 'کد تایید منقضی شده است',
|
||||
error: 'OTP_EXPIRED',
|
||||
});
|
||||
}
|
||||
|
||||
if (savedCode !== code) {
|
||||
throw new BadRequestException({ message: 'کد تایید اشتباه است', error: 'OTP_INVALID' });
|
||||
throw new BadRequestException({
|
||||
message: 'کد تایید اشتباه است',
|
||||
error: 'OTP_INVALID',
|
||||
});
|
||||
}
|
||||
|
||||
await this.redisService.del(`otp:${phoneNumber}`);
|
||||
|
||||
let user = await this.prisma.user.findUnique({ where: { mobile: phoneNumber } });
|
||||
let user = await this.prisma.user.findUnique({
|
||||
where: { mobile: phoneNumber },
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
user = await this.prisma.user.create({
|
||||
data: {
|
||||
data: {
|
||||
mobile: phoneNumber,
|
||||
firstName: 'کاربر',
|
||||
lastName: 'جدید',
|
||||
@@ -70,15 +78,25 @@ export class AuthService {
|
||||
async register(registerDto: any) {
|
||||
const { firstName, lastName, email, mobile, password } = registerDto;
|
||||
|
||||
const existingUser = await this.prisma.user.findUnique({ where: { mobile } });
|
||||
const existingUser = await this.prisma.user.findUnique({
|
||||
where: { mobile },
|
||||
});
|
||||
if (existingUser) {
|
||||
throw new BadRequestException({ message: 'کاربری با این شماره موبایل قبلا ثبت نام کرده است', error: 'MOBILE_EXISTS' });
|
||||
throw new BadRequestException({
|
||||
message: 'کاربری با این شماره موبایل قبلا ثبت نام کرده است',
|
||||
error: 'MOBILE_EXISTS',
|
||||
});
|
||||
}
|
||||
|
||||
if (email) {
|
||||
const existingEmail = await this.prisma.user.findUnique({ where: { email } });
|
||||
const existingEmail = await this.prisma.user.findUnique({
|
||||
where: { email },
|
||||
});
|
||||
if (existingEmail) {
|
||||
throw new BadRequestException({ message: 'کاربری با این ایمیل قبلا ثبت نام کرده است', error: 'EMAIL_EXISTS' });
|
||||
throw new BadRequestException({
|
||||
message: 'کاربری با این ایمیل قبلا ثبت نام کرده است',
|
||||
error: 'EMAIL_EXISTS',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -111,16 +129,25 @@ export class AuthService {
|
||||
|
||||
const user = await this.prisma.user.findUnique({ where: { mobile } });
|
||||
if (!user) {
|
||||
throw new BadRequestException({ message: 'نام کاربری یا رمز عبور اشتباه است', error: 'INVALID_CREDENTIALS' });
|
||||
throw new BadRequestException({
|
||||
message: 'نام کاربری یا رمز عبور اشتباه است',
|
||||
error: 'INVALID_CREDENTIALS',
|
||||
});
|
||||
}
|
||||
|
||||
if (!user.password) {
|
||||
throw new BadRequestException({ message: 'شما با رمز عبور ثبت نام نکردهاید. لطفاً با موبایل وارد شوید', error: 'NO_PASSWORD' });
|
||||
throw new BadRequestException({
|
||||
message: 'شما با رمز عبور ثبت نام نکردهاید. لطفاً با موبایل وارد شوید',
|
||||
error: 'NO_PASSWORD',
|
||||
});
|
||||
}
|
||||
|
||||
const isMatch = await bcrypt.compare(password, user.password);
|
||||
if (!isMatch) {
|
||||
throw new BadRequestException({ message: 'نام کاربری یا رمز عبور اشتباه است', error: 'INVALID_CREDENTIALS' });
|
||||
throw new BadRequestException({
|
||||
message: 'نام کاربری یا رمز عبور اشتباه است',
|
||||
error: 'INVALID_CREDENTIALS',
|
||||
});
|
||||
}
|
||||
|
||||
const payload = { sub: user.id, phoneNumber: user.mobile };
|
||||
@@ -136,16 +163,30 @@ export class AuthService {
|
||||
}
|
||||
|
||||
async adminLogin(body: any) {
|
||||
if (body.email === 'admin@canino-iran.com' && body.password === 'admin123') {
|
||||
const payload = { sub: '12345678-1234-1234-1234-123456789012', email: body.email, role: 'Admin' };
|
||||
if (
|
||||
body.email === 'admin@canino-iran.com' &&
|
||||
body.password === 'admin123'
|
||||
) {
|
||||
const payload = {
|
||||
sub: '12345678-1234-1234-1234-123456789012',
|
||||
email: body.email,
|
||||
role: 'Admin',
|
||||
};
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
user: { id: '12345678-1234-1234-1234-123456789012', email: body.email, role: 'Admin' },
|
||||
user: {
|
||||
id: '12345678-1234-1234-1234-123456789012',
|
||||
email: body.email,
|
||||
role: 'Admin',
|
||||
},
|
||||
accessToken: this.jwtService.sign(payload),
|
||||
},
|
||||
};
|
||||
}
|
||||
throw new BadRequestException({ message: 'ایمیل یا رمز عبور اشتباه است', error: 'INVALID_CREDENTIALS' });
|
||||
throw new BadRequestException({
|
||||
message: 'ایمیل یا رمز عبور اشتباه است',
|
||||
error: 'INVALID_CREDENTIALS',
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,10 @@
|
||||
import { IsEmail, IsNotEmpty, IsOptional, IsString, MinLength } from 'class-validator';
|
||||
import {
|
||||
IsEmail,
|
||||
IsNotEmpty,
|
||||
IsOptional,
|
||||
IsString,
|
||||
MinLength,
|
||||
} from 'class-validator';
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
|
||||
export class RegisterDto {
|
||||
@@ -12,7 +18,10 @@ export class RegisterDto {
|
||||
@IsString()
|
||||
lastName: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'ایمیل (اختیاری)', example: 'ali@example.com' })
|
||||
@ApiPropertyOptional({
|
||||
description: 'ایمیل (اختیاری)',
|
||||
example: 'ali@example.com',
|
||||
})
|
||||
@IsOptional()
|
||||
@IsEmail({}, { message: 'ایمیل نامعتبر است' })
|
||||
email?: string;
|
||||
|
||||
@@ -5,7 +5,9 @@ import { AuthGuard } from '@nestjs/passport';
|
||||
export class JwtAuthGuard extends AuthGuard('jwt') {
|
||||
handleRequest(err: any, user: any, info: any) {
|
||||
if (err || !user) {
|
||||
throw err || new UnauthorizedException('لطفا ابتدا وارد حساب کاربری خود شوید');
|
||||
throw (
|
||||
err || new UnauthorizedException('لطفا ابتدا وارد حساب کاربری خود شوید')
|
||||
);
|
||||
}
|
||||
return user;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
import { Injectable, CanActivate, ExecutionContext, ForbiddenException } from '@nestjs/common';
|
||||
import {
|
||||
Injectable,
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
ForbiddenException,
|
||||
} from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import { ROLES_KEY } from './roles.decorator';
|
||||
|
||||
@@ -7,11 +12,11 @@ export class RolesGuard implements CanActivate {
|
||||
constructor(private reflector: Reflector) {}
|
||||
|
||||
canActivate(context: ExecutionContext): boolean {
|
||||
const requiredRoles = this.reflector.getAllAndOverride<string[]>(ROLES_KEY, [
|
||||
context.getHandler(),
|
||||
context.getClass(),
|
||||
]);
|
||||
|
||||
const requiredRoles = this.reflector.getAllAndOverride<string[]>(
|
||||
ROLES_KEY,
|
||||
[context.getHandler(), context.getClass()],
|
||||
);
|
||||
|
||||
if (!requiredRoles || requiredRoles.length === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user