feat: complete testing, security, dynamic content, and devops overhaul
This commit is contained in:
1 parent
467532713c
commit
40ff169dc2
52 files changed
+3918
-104
No files matched your search
@@ -0,0 +1,47 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { AuthController } from './auth.controller';
|
||||
import { AuthService } from './auth.service';
|
||||
|
||||
describe('AuthController', () => {
|
||||
let controller: AuthController;
|
||||
let service: AuthService;
|
||||
|
||||
const mockAuthService = {
|
||||
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 },
|
||||
],
|
||||
}).compile();
|
||||
|
||||
controller = module.get<AuthController>(AuthController);
|
||||
service = module.get<AuthService>(AuthService);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(controller).toBeDefined();
|
||||
});
|
||||
|
||||
it('should call sendOtp on service', async () => {
|
||||
const dto = { phoneNumber: '09123456789' };
|
||||
const result = await controller.sendOtp(dto);
|
||||
expect(service.sendOtp).toHaveBeenCalledWith(dto);
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it('should call verifyOtp on service', async () => {
|
||||
const dto = { phoneNumber: '09123456789', code: '12345' };
|
||||
const result = await controller.verifyOtp(dto);
|
||||
expect(service.verifyOtp).toHaveBeenCalledWith(dto);
|
||||
expect(result.data.accessToken).toBe('token');
|
||||
});
|
||||
});
|
||||
@@ -2,25 +2,92 @@ import { Controller, Post, Body, HttpCode, HttpStatus } from '@nestjs/common';
|
||||
import { AuthService } from './auth.service';
|
||||
import { SendOtpDto } from './dto/send-otp.dto';
|
||||
import { VerifyOtpDto } from './dto/verify-otp.dto';
|
||||
import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';
|
||||
import { ApiTags, ApiOperation, ApiResponse, ApiOkResponse, ApiBadRequestResponse } from '@nestjs/swagger';
|
||||
|
||||
@ApiTags('Auth')
|
||||
@ApiTags('Auth - احراز هویت')
|
||||
@Controller('auth')
|
||||
@ApiResponse({
|
||||
status: HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
description: 'خطای داخلی سرور',
|
||||
schema: {
|
||||
example: {
|
||||
success: false,
|
||||
message: 'خطای ناشناخته در سرور رخ داده است',
|
||||
code: 'SERVER_ERROR',
|
||||
details: {}
|
||||
}
|
||||
}
|
||||
})
|
||||
export class AuthController {
|
||||
constructor(private readonly authService: AuthService) {}
|
||||
|
||||
@Post('send-otp')
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@ApiOperation({ summary: 'ارسال کد تایید پیامکی' })
|
||||
@ApiResponse({ status: 200, description: 'کد با موفقیت ارسال شد' })
|
||||
@ApiOperation({ summary: 'ارسال کد تایید پیامکی (OTP)' })
|
||||
@ApiOkResponse({
|
||||
description: 'کد با موفقیت ارسال شد (کد تایید در پاسخ بازگردانده میشود)',
|
||||
schema: {
|
||||
example: {
|
||||
success: true,
|
||||
message: 'کد تایید ارسال شد',
|
||||
code: '12345'
|
||||
}
|
||||
}
|
||||
})
|
||||
@ApiBadRequestResponse({
|
||||
description: 'فرمت شماره تلفن همراه نامعتبر است',
|
||||
schema: {
|
||||
example: {
|
||||
success: false,
|
||||
message: 'شماره موبایل نامعتبر است',
|
||||
code: 'BAD_REQUEST',
|
||||
details: {
|
||||
message: ['شماره موبایل نامعتبر است']
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
sendOtp(@Body() sendOtpDto: SendOtpDto) {
|
||||
return this.authService.sendOtp(sendOtpDto);
|
||||
}
|
||||
|
||||
@Post('verify-otp')
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@ApiOperation({ summary: 'تایید کد پیامکی و ورود/ثبتنام' })
|
||||
@ApiResponse({ status: 200, description: 'ورود موفق به همراه توکن' })
|
||||
@ApiOperation({ summary: 'تایید کد پیامکی و ورود/ثبتنام کاربر' })
|
||||
@ApiOkResponse({
|
||||
description: 'ورود موفق به همراه توکن دسترسی JWT و اطلاعات کاربر',
|
||||
schema: {
|
||||
example: {
|
||||
success: true,
|
||||
data: {
|
||||
user: {
|
||||
id: 'd8c4e428-cd2f-4c55-bfa3-dfa312bb6480',
|
||||
firstName: 'کاربر',
|
||||
lastName: 'جدید',
|
||||
email: '09123456789@temp.local',
|
||||
mobile: '09123456789',
|
||||
role: 'User_PetOwner',
|
||||
walletBalance: '0.00',
|
||||
charityDonationTotal: '0.00',
|
||||
createdAt: '2026-05-26T15:20:00.000Z',
|
||||
updatedAt: '2026-05-26T15:20:00.000Z'
|
||||
},
|
||||
accessToken: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...'
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
@ApiBadRequestResponse({
|
||||
description: 'کد تایید اشتباه یا منقضی شده است',
|
||||
schema: {
|
||||
example: {
|
||||
success: false,
|
||||
message: 'کد تایید اشتباه است',
|
||||
code: 'OTP_INVALID',
|
||||
details: {}
|
||||
}
|
||||
}
|
||||
})
|
||||
verifyOtp(@Body() verifyOtpDto: VerifyOtpDto) {
|
||||
return this.authService.verifyOtp(verifyOtpDto);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { AuthService } from './auth.service';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { RedisService } from '../redis/redis.service';
|
||||
import { BadRequestException } from '@nestjs/common';
|
||||
|
||||
describe('AuthService', () => {
|
||||
let service: AuthService;
|
||||
let prisma: PrismaService;
|
||||
let jwt: JwtService;
|
||||
let redis: RedisService;
|
||||
|
||||
const mockPrisma = {
|
||||
user: {
|
||||
findUnique: jest.fn(),
|
||||
create: jest.fn(),
|
||||
},
|
||||
};
|
||||
|
||||
const mockJwt = {
|
||||
sign: jest.fn().mockReturnValue('mock-jwt-token'),
|
||||
};
|
||||
|
||||
const mockRedis = {
|
||||
set: jest.fn(),
|
||||
get: jest.fn(),
|
||||
del: jest.fn(),
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [
|
||||
AuthService,
|
||||
{ provide: PrismaService, useValue: mockPrisma },
|
||||
{ provide: JwtService, useValue: mockJwt },
|
||||
{ provide: RedisService, useValue: mockRedis },
|
||||
],
|
||||
}).compile();
|
||||
|
||||
service = module.get<AuthService>(AuthService);
|
||||
prisma = module.get<PrismaService>(PrismaService);
|
||||
jwt = module.get<JwtService>(JwtService);
|
||||
redis = module.get<RedisService>(RedisService);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
|
||||
describe('sendOtp', () => {
|
||||
it('should generate a 5 digit OTP and save it in Redis', async () => {
|
||||
const result = await service.sendOtp({ phoneNumber: '09123456789' });
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.code).toHaveLength(5);
|
||||
expect(redis.set).toHaveBeenCalledWith(
|
||||
'otp:09123456789',
|
||||
result.code,
|
||||
120,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('verifyOtp', () => {
|
||||
it('should throw BadRequestException if OTP is expired/not found', async () => {
|
||||
mockRedis.get.mockResolvedValue(null);
|
||||
await expect(
|
||||
service.verifyOtp({ phoneNumber: '09123456789', code: '12345' }),
|
||||
).rejects.toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
it('should throw BadRequestException if OTP is incorrect', async () => {
|
||||
mockRedis.get.mockResolvedValue('54321');
|
||||
await expect(
|
||||
service.verifyOtp({ phoneNumber: '09123456789', code: '12345' }),
|
||||
).rejects.toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
it('should delete OTP, find or create user and sign JWT', async () => {
|
||||
mockRedis.get.mockResolvedValue('12345');
|
||||
const mockUser = { id: 'user-id', mobile: '09123456789' };
|
||||
mockPrisma.user.findUnique.mockResolvedValue(mockUser);
|
||||
|
||||
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(result.success).toBe(true);
|
||||
expect(result.data.accessToken).toBe('mock-jwt-token');
|
||||
expect(result.data.user).toEqual(mockUser);
|
||||
});
|
||||
|
||||
it('should create new user if user does not exist', async () => {
|
||||
mockRedis.get.mockResolvedValue('12345');
|
||||
mockPrisma.user.findUnique.mockResolvedValue(null);
|
||||
const newUser = { id: 'new-user-id', mobile: '09123456789' };
|
||||
mockPrisma.user.create.mockResolvedValue(newUser);
|
||||
|
||||
const result = await service.verifyOtp({ phoneNumber: '09123456789', code: '12345' });
|
||||
expect(prisma.user.create).toHaveBeenCalled();
|
||||
expect(result.data.user).toEqual(newUser);
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user