test: comprehensive test suites and quality gates pass across backend, storefront and admin
- Backend (NestJS): 82 suites, 641 tests passing; 0 ESLint errors; 0 tsc errors. Hardened SSL cert/key matching, SSRF IP pinning, and eBank validation. - Admin Panel (Vite/React): 48 suites, 300 tests passing; 0 ESLint errors; 0 tsc errors. Full coverage across all pages and settings. - Storefront (Next.js): 62 suites, 368 tests passing; 0 ESLint errors; 0 tsc errors. - Fixed unmount lifecycle guards, promise error handling, and component edge cases.
This commit is contained in:
1 parent
1e73715169
commit
ddbf1ca026
439 files changed
+32911
-6107
No files matched your search
@@ -1,23 +1,23 @@
|
||||
import * as crypto from 'crypto';
|
||||
import * as crypto from "crypto";
|
||||
|
||||
const devAccessSecret =
|
||||
process.env.NODE_ENV !== 'production'
|
||||
? crypto.randomBytes(32).toString('hex')
|
||||
process.env.NODE_ENV !== "production"
|
||||
? crypto.randomBytes(32).toString("hex")
|
||||
: undefined;
|
||||
|
||||
const devRefreshSecret =
|
||||
process.env.NODE_ENV !== 'production'
|
||||
? crypto.randomBytes(32).toString('hex')
|
||||
process.env.NODE_ENV !== "production"
|
||||
? crypto.randomBytes(32).toString("hex")
|
||||
: undefined;
|
||||
|
||||
export const getJwtSecret = (): string => {
|
||||
const secret = process.env.JWT_ACCESS_SECRET || process.env.JWT_SECRET;
|
||||
if (secret) return secret;
|
||||
return 'canina_secure_access_token_jwt_secret_production_2026';
|
||||
return "canina_secure_access_token_jwt_secret_production_2026";
|
||||
};
|
||||
|
||||
export const getJwtRefreshSecret = (): string => {
|
||||
const secret = process.env.JWT_REFRESH_SECRET;
|
||||
if (secret) return secret;
|
||||
return 'canina_secure_refresh_token_jwt_secret_production_2026';
|
||||
return "canina_secure_refresh_token_jwt_secret_production_2026";
|
||||
};
|
||||
@@ -1,18 +1,18 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { AuthController } from './auth.controller';
|
||||
import { AuthService } from './auth.service';
|
||||
import { Test, TestingModule } from "@nestjs/testing";
|
||||
import { AuthController } from "./auth.controller";
|
||||
import { AuthService } from "./auth.service";
|
||||
|
||||
describe('AuthController', () => {
|
||||
describe("AuthController", () => {
|
||||
let controller: AuthController;
|
||||
let service: AuthService;
|
||||
|
||||
const mockAuthService = {
|
||||
sendOtp: jest
|
||||
.fn()
|
||||
.mockResolvedValue({ success: true, message: 'کد تایید ارسال شد' }),
|
||||
.mockResolvedValue({ success: true, message: "کد تایید ارسال شد" }),
|
||||
verifyOtp: jest
|
||||
.fn()
|
||||
.mockResolvedValue({ success: true, data: { accessToken: 'token' } }),
|
||||
.mockResolvedValue({ success: true, data: { accessToken: "token" } }),
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
@@ -29,21 +29,21 @@ describe('AuthController', () => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
it("should be defined", () => {
|
||||
expect(controller).toBeDefined();
|
||||
});
|
||||
|
||||
it('should call sendOtp on service', async () => {
|
||||
const dto = { phoneNumber: '09123456789' };
|
||||
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' };
|
||||
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');
|
||||
expect(result.data.accessToken).toBe("token");
|
||||
});
|
||||
});
|
||||
@@ -7,15 +7,15 @@ import {
|
||||
UseGuards,
|
||||
Req,
|
||||
Res,
|
||||
} from '@nestjs/common';
|
||||
import type { Response } from 'express';
|
||||
import { Throttle } from '@nestjs/throttler';
|
||||
import { AuthService } from './auth.service';
|
||||
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 { JwtAuthGuard } from './jwt-auth.guard';
|
||||
} from "@nestjs/common";
|
||||
import type { Response } from "express";
|
||||
import { Throttle } from "@nestjs/throttler";
|
||||
import { AuthService } from "./auth.service";
|
||||
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 { JwtAuthGuard } from "./jwt-auth.guard";
|
||||
import {
|
||||
ApiTags,
|
||||
ApiOperation,
|
||||
@@ -23,21 +23,21 @@ import {
|
||||
ApiOkResponse,
|
||||
ApiBadRequestResponse,
|
||||
ApiBearerAuth,
|
||||
} from '@nestjs/swagger';
|
||||
} from "@nestjs/swagger";
|
||||
|
||||
import { AdminLoginDto } from './dto/admin-login.dto';
|
||||
import { RefreshTokenDto } from './dto/refresh-token.dto';
|
||||
import { AdminLoginDto } from "./dto/admin-login.dto";
|
||||
import { RefreshTokenDto } from "./dto/refresh-token.dto";
|
||||
|
||||
@ApiTags('Auth - احراز هویت')
|
||||
@Controller('auth')
|
||||
@ApiTags("Auth - احراز هویت")
|
||||
@Controller("auth")
|
||||
@ApiResponse({
|
||||
status: HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
description: 'خطای داخلی سرور',
|
||||
description: "خطای داخلی سرور",
|
||||
schema: {
|
||||
example: {
|
||||
success: false,
|
||||
message: 'خطای ناشناخته در سرور رخ داده است',
|
||||
code: 'SERVER_ERROR',
|
||||
message: "خطای ناشناخته در سرور رخ داده است",
|
||||
code: "SERVER_ERROR",
|
||||
details: {},
|
||||
},
|
||||
},
|
||||
@@ -46,19 +46,19 @@ export class AuthController {
|
||||
constructor(private readonly authService: AuthService) {}
|
||||
|
||||
@Throttle({ default: { limit: 5, ttl: 60000 } })
|
||||
@Post('send-otp')
|
||||
@Post("send-otp")
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@ApiOperation({ summary: 'ارسال کد تایید پیامکی (OTP)' })
|
||||
@ApiOperation({ summary: "ارسال کد تایید پیامکی (OTP)" })
|
||||
@ApiOkResponse({
|
||||
description: 'کد با موفقیت به شماره تلفن همراه پیامک شد',
|
||||
description: "کد با موفقیت به شماره تلفن همراه پیامک شد",
|
||||
schema: {
|
||||
example: {
|
||||
success: true,
|
||||
message: 'کد تایید با موفقیت به شماره شما پیامک شد.',
|
||||
message: "کد تایید با موفقیت به شماره شما پیامک شد.",
|
||||
},
|
||||
},
|
||||
})
|
||||
@ApiBadRequestResponse({ description: 'شماره تلفن همراه نامعتبر است' })
|
||||
@ApiBadRequestResponse({ description: "شماره تلفن همراه نامعتبر است" })
|
||||
sendOtp(@Body() sendOtpDto: SendOtpDto) {
|
||||
return this.authService.sendOtp(sendOtpDto);
|
||||
}
|
||||
@@ -68,52 +68,52 @@ export class AuthController {
|
||||
accessToken?: string,
|
||||
refreshToken?: string,
|
||||
) {
|
||||
if (!res || typeof res.cookie !== 'function') return;
|
||||
const isProd = process.env.NODE_ENV === 'production';
|
||||
if (!res || typeof res.cookie !== "function") return;
|
||||
const isProd = process.env.NODE_ENV === "production";
|
||||
if (accessToken) {
|
||||
res.cookie('accessToken', accessToken, {
|
||||
res.cookie("accessToken", accessToken, {
|
||||
httpOnly: true,
|
||||
secure: isProd,
|
||||
sameSite: 'lax',
|
||||
sameSite: "lax",
|
||||
maxAge: 15 * 60 * 1000, // 15 mins
|
||||
path: '/',
|
||||
path: "/",
|
||||
});
|
||||
}
|
||||
if (refreshToken) {
|
||||
res.cookie('refreshToken', refreshToken, {
|
||||
res.cookie("refreshToken", refreshToken, {
|
||||
httpOnly: true,
|
||||
secure: isProd,
|
||||
sameSite: 'lax',
|
||||
sameSite: "lax",
|
||||
maxAge: 30 * 24 * 60 * 60 * 1000, // 30 days
|
||||
path: '/',
|
||||
path: "/",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private clearAuthCookies(res?: Response) {
|
||||
if (!res || typeof res.clearCookie !== 'function') return;
|
||||
const isProd = process.env.NODE_ENV === 'production';
|
||||
res.clearCookie('accessToken', {
|
||||
if (!res || typeof res.clearCookie !== "function") return;
|
||||
const isProd = process.env.NODE_ENV === "production";
|
||||
res.clearCookie("accessToken", {
|
||||
httpOnly: true,
|
||||
secure: isProd,
|
||||
sameSite: 'lax',
|
||||
path: '/',
|
||||
sameSite: "lax",
|
||||
path: "/",
|
||||
});
|
||||
res.clearCookie('refreshToken', {
|
||||
res.clearCookie("refreshToken", {
|
||||
httpOnly: true,
|
||||
secure: isProd,
|
||||
sameSite: 'lax',
|
||||
path: '/',
|
||||
sameSite: "lax",
|
||||
path: "/",
|
||||
});
|
||||
}
|
||||
|
||||
@Throttle({ default: { limit: 10, ttl: 60000 } })
|
||||
@Post('verify-otp')
|
||||
@Post("verify-otp")
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@ApiOperation({ summary: 'تایید کد پیامکی و ورود به سیستم' })
|
||||
@ApiOkResponse({ description: 'کد تایید شد و ورود با موفقیت انجام گردید' })
|
||||
@ApiOperation({ summary: "تایید کد پیامکی و ورود به سیستم" })
|
||||
@ApiOkResponse({ description: "کد تایید شد و ورود با موفقیت انجام گردید" })
|
||||
@ApiBadRequestResponse({
|
||||
description: 'کد تایید اشتباه است یا منقضی شده است',
|
||||
description: "کد تایید اشتباه است یا منقضی شده است",
|
||||
})
|
||||
async verifyOtp(
|
||||
@Body() verifyOtpDto: VerifyOtpDto,
|
||||
@@ -131,12 +131,12 @@ export class AuthController {
|
||||
}
|
||||
|
||||
@Throttle({ default: { limit: 5, ttl: 60000 } })
|
||||
@Post('register')
|
||||
@Post("register")
|
||||
@HttpCode(HttpStatus.CREATED)
|
||||
@ApiOperation({ summary: 'ثبتنام با ایمیل/موبایل و رمز عبور' })
|
||||
@ApiOkResponse({ description: 'کاربر با موفقیت ثبتنام شد' })
|
||||
@ApiOperation({ summary: "ثبتنام با ایمیل/موبایل و رمز عبور" })
|
||||
@ApiOkResponse({ description: "کاربر با موفقیت ثبتنام شد" })
|
||||
@ApiBadRequestResponse({
|
||||
description: 'اطلاعات ثبتنام نامعتبر است یا کاربر از قبل وجود دارد',
|
||||
description: "اطلاعات ثبتنام نامعتبر است یا کاربر از قبل وجود دارد",
|
||||
})
|
||||
async register(
|
||||
@Body() registerDto: RegisterDto,
|
||||
@@ -154,11 +154,11 @@ export class AuthController {
|
||||
}
|
||||
|
||||
@Throttle({ default: { limit: 5, ttl: 60000 } })
|
||||
@Post('login')
|
||||
@Post("login")
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@ApiOperation({ summary: 'ورود با موبایل و رمز عبور' })
|
||||
@ApiOkResponse({ description: 'ورود موفق به همراه توکن دسترسی' })
|
||||
@ApiBadRequestResponse({ description: 'نام کاربری یا رمز عبور اشتباه است' })
|
||||
@ApiOperation({ summary: "ورود با موبایل و رمز عبور" })
|
||||
@ApiOkResponse({ description: "ورود موفق به همراه توکن دسترسی" })
|
||||
@ApiBadRequestResponse({ description: "نام کاربری یا رمز عبور اشتباه است" })
|
||||
async login(
|
||||
@Body() loginDto: LoginDto,
|
||||
@Res({ passthrough: true }) res?: Response,
|
||||
@@ -175,11 +175,11 @@ export class AuthController {
|
||||
}
|
||||
|
||||
@Throttle({ default: { limit: 5, ttl: 300000 } }) // 5 attempts per 5 minutes
|
||||
@Post('admin-login')
|
||||
@Post("admin-login")
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@ApiOperation({ summary: 'ورود ادمین به پنل مدیریت' })
|
||||
@ApiOkResponse({ description: 'ورود موفق ادمین به همراه توکن' })
|
||||
@ApiBadRequestResponse({ description: 'اطلاعات ورود ادمین اشتباه است' })
|
||||
@ApiOperation({ summary: "ورود ادمین به پنل مدیریت" })
|
||||
@ApiOkResponse({ description: "ورود موفق ادمین به همراه توکن" })
|
||||
@ApiBadRequestResponse({ description: "اطلاعات ورود ادمین اشتباه است" })
|
||||
async adminLogin(
|
||||
@Body() body: AdminLoginDto,
|
||||
@Res({ passthrough: true }) res?: Response,
|
||||
@@ -196,13 +196,13 @@ export class AuthController {
|
||||
}
|
||||
|
||||
@Throttle({ default: { limit: 10, ttl: 60000 } })
|
||||
@Post('refresh-token')
|
||||
@Post("refresh-token")
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@ApiOperation({
|
||||
summary: 'دریافت جفت توکن جدید با استفاده از توکن تازهسازی',
|
||||
summary: "دریافت جفت توکن جدید با استفاده از توکن تازهسازی",
|
||||
})
|
||||
@ApiOkResponse({ description: 'توکنهای جدید با موفقیت صادر شدند' })
|
||||
@ApiBadRequestResponse({ description: 'توکن نامعتبر یا منقضی است' })
|
||||
@ApiOkResponse({ description: "توکنهای جدید با موفقیت صادر شدند" })
|
||||
@ApiBadRequestResponse({ description: "توکن نامعتبر یا منقضی است" })
|
||||
async refreshToken(
|
||||
@Body() body: RefreshTokenDto,
|
||||
@Req() req: any,
|
||||
@@ -226,10 +226,10 @@ export class AuthController {
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Post('refresh')
|
||||
@Post("refresh")
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@ApiOperation({ summary: 'تازهسازی توکن دسترسی (Refresh Token)' })
|
||||
@ApiOkResponse({ description: 'توکن جدید با موفقیت صادر شد' })
|
||||
@ApiOperation({ summary: "تازهسازی توکن دسترسی (Refresh Token)" })
|
||||
@ApiOkResponse({ description: "توکن جدید با موفقیت صادر شد" })
|
||||
async refresh(
|
||||
@Req()
|
||||
req: {
|
||||
@@ -250,15 +250,15 @@ export class AuthController {
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Post('logout')
|
||||
@Post("logout")
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@ApiOperation({ summary: 'خروج از حساب کاربری و ابطال توکن' })
|
||||
@ApiOkResponse({ description: 'با موفقیت خارج شدید' })
|
||||
@ApiOperation({ summary: "خروج از حساب کاربری و ابطال توکن" })
|
||||
@ApiOkResponse({ description: "با موفقیت خارج شدید" })
|
||||
async logout(@Req() req: any, @Res({ passthrough: true }) res?: Response) {
|
||||
let token: string | undefined;
|
||||
const authHeader = req.headers?.authorization;
|
||||
if (authHeader && authHeader.startsWith('Bearer ')) {
|
||||
token = authHeader.replace('Bearer ', '').trim();
|
||||
if (authHeader && authHeader.startsWith("Bearer ")) {
|
||||
token = authHeader.replace("Bearer ", "").trim();
|
||||
} else if (req.headers?.cookie) {
|
||||
const match = req.headers.cookie.match(/(?:^|;\s*)accessToken=([^;]+)/);
|
||||
if (match) token = decodeURIComponent(match[1]);
|
||||
@@ -267,6 +267,6 @@ export class AuthController {
|
||||
await this.authService.blacklistToken(token);
|
||||
}
|
||||
this.clearAuthCookies(res);
|
||||
return { success: true, message: 'با موفقیت خارج شدید' };
|
||||
return { success: true, message: "با موفقیت خارج شدید" };
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,14 @@
|
||||
import { Module, forwardRef } from '@nestjs/common';
|
||||
import { JwtModule } from '@nestjs/jwt';
|
||||
import { PassportModule } from '@nestjs/passport';
|
||||
import { AuthService } from './auth.service';
|
||||
import { AuthController } from './auth.controller';
|
||||
import { JwtStrategy } from './jwt.strategy';
|
||||
import { UsersModule } from '../users/users.module';
|
||||
import { AdminModule } from '../admin/admin.module';
|
||||
import { getJwtSecret } from './auth.constants';
|
||||
import { Module, forwardRef } from "@nestjs/common";
|
||||
import { JwtModule } from "@nestjs/jwt";
|
||||
import { PassportModule } from "@nestjs/passport";
|
||||
import { AuthService } from "./auth.service";
|
||||
import { AuthController } from "./auth.controller";
|
||||
import { JwtStrategy } from "./jwt.strategy";
|
||||
import { UsersModule } from "../users/users.module";
|
||||
import { AdminModule } from "../admin/admin.module";
|
||||
import { getJwtSecret } from "./auth.constants";
|
||||
|
||||
import { RedisModule } from '../redis/redis.module';
|
||||
import { RedisModule } from "../redis/redis.module";
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
@@ -19,7 +19,7 @@ import { RedisModule } from '../redis/redis.module';
|
||||
JwtModule.registerAsync({
|
||||
useFactory: () => ({
|
||||
secret: getJwtSecret(),
|
||||
signOptions: { expiresIn: '2h' },
|
||||
signOptions: { expiresIn: "2h" },
|
||||
}),
|
||||
}),
|
||||
],
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
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 { SmsService } from '../common/services/sms.service';
|
||||
import { BadRequestException } from '@nestjs/common';
|
||||
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 { SmsService } from "../common/services/sms.service";
|
||||
import { BadRequestException } from "@nestjs/common";
|
||||
|
||||
describe('AuthService', () => {
|
||||
describe("AuthService", () => {
|
||||
let service: AuthService;
|
||||
let prisma: PrismaService;
|
||||
let jwt: JwtService;
|
||||
@@ -21,7 +21,7 @@ describe('AuthService', () => {
|
||||
};
|
||||
|
||||
const mockJwt = {
|
||||
sign: jest.fn().mockReturnValue('mock-jwt-token'),
|
||||
sign: jest.fn().mockReturnValue("mock-jwt-token"),
|
||||
};
|
||||
|
||||
const mockRedis = {
|
||||
@@ -57,79 +57,79 @@ describe('AuthService', () => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
it("should be defined", () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
|
||||
describe('sendOtp', () => {
|
||||
it('should generate a 5 digit OTP, save it in Redis, and not expose it in response', async () => {
|
||||
const result = await service.sendOtp({ phoneNumber: '09123456789' });
|
||||
describe("sendOtp", () => {
|
||||
it("should generate a 5 digit OTP, save it in Redis, and not expose it in response", async () => {
|
||||
const result = await service.sendOtp({ phoneNumber: "09123456789" });
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.message).toBe('کد تایید با موفقیت به شماره شما پیامک شد.');
|
||||
expect(result.message).toBe("کد تایید با موفقیت به شماره شما پیامک شد.");
|
||||
// Code should NOT be in the response (security)
|
||||
expect((result as any).code).toBeUndefined();
|
||||
// But it should have been stored in Redis
|
||||
expect(redis.set).toHaveBeenCalledWith(
|
||||
'otp:09123456789',
|
||||
"otp:09123456789",
|
||||
expect.stringMatching(/^\d{5}$/),
|
||||
120,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('verifyOtp', () => {
|
||||
it('should throw BadRequestException if OTP is expired/not found', async () => {
|
||||
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' }),
|
||||
service.verifyOtp({ phoneNumber: "09123456789", code: "12345" }),
|
||||
).rejects.toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
it('should throw BadRequestException if OTP is incorrect', async () => {
|
||||
mockRedis.get.mockResolvedValue('54321');
|
||||
it("should throw BadRequestException if OTP is incorrect", async () => {
|
||||
mockRedis.get.mockResolvedValue("54321");
|
||||
await expect(
|
||||
service.verifyOtp({ phoneNumber: '09123456789', code: '12345' }),
|
||||
service.verifyOtp({ phoneNumber: "09123456789", code: "12345" }),
|
||||
).rejects.toThrow(BadRequestException);
|
||||
});
|
||||
|
||||
it('should delete OTP, find or create user and sign JWT', async () => {
|
||||
mockRedis.get.mockImplementation(async (key: string) => {
|
||||
if (key.startsWith('otp_attempts:')) return null;
|
||||
return '12345';
|
||||
it("should delete OTP, find or create user and sign JWT", async () => {
|
||||
mockRedis.get.mockImplementation((key: string) => {
|
||||
if (key.startsWith("otp_attempts:")) return null;
|
||||
return "12345";
|
||||
});
|
||||
const mockUser = { id: 'user-id', mobile: '09123456789' };
|
||||
const mockUser = { id: "user-id", mobile: "09123456789" };
|
||||
mockPrisma.user.findUnique.mockResolvedValue(mockUser);
|
||||
|
||||
const result = await service.verifyOtp({
|
||||
phoneNumber: '09123456789',
|
||||
code: '12345',
|
||||
phoneNumber: "09123456789",
|
||||
code: "12345",
|
||||
});
|
||||
|
||||
expect(redis.del).toHaveBeenCalledWith('otp:09123456789');
|
||||
expect(redis.del).toHaveBeenCalledWith("otp:09123456789");
|
||||
expect(prisma.user.findUnique).toHaveBeenCalledWith({
|
||||
where: { mobile: '09123456789' },
|
||||
where: { mobile: "09123456789" },
|
||||
});
|
||||
expect(jwt.sign).toHaveBeenCalledWith({
|
||||
sub: 'user-id',
|
||||
phoneNumber: '09123456789',
|
||||
sub: "user-id",
|
||||
phoneNumber: "09123456789",
|
||||
});
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.data.accessToken).toBe('mock-jwt-token');
|
||||
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.mockImplementation(async (key: string) => {
|
||||
if (key.startsWith('otp_attempts:')) return null;
|
||||
return '12345';
|
||||
it("should create new user if user does not exist", async () => {
|
||||
mockRedis.get.mockImplementation((key: string) => {
|
||||
if (key.startsWith("otp_attempts:")) return null;
|
||||
return "12345";
|
||||
});
|
||||
mockPrisma.user.findUnique.mockResolvedValue(null);
|
||||
const newUser = { id: 'new-user-id', mobile: '09123456789' };
|
||||
const newUser = { id: "new-user-id", mobile: "09123456789" };
|
||||
mockPrisma.user.create.mockResolvedValue(newUser);
|
||||
|
||||
const result = await service.verifyOtp({
|
||||
phoneNumber: '09123456789',
|
||||
code: '12345',
|
||||
phoneNumber: "09123456789",
|
||||
code: "12345",
|
||||
});
|
||||
expect(prisma.user.create).toHaveBeenCalled();
|
||||
expect(result.data.user).toEqual(newUser);
|
||||
|
||||
@@ -4,17 +4,17 @@ import {
|
||||
UnauthorizedException,
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
} from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { RedisService } from '../redis/redis.service';
|
||||
import { SendOtpDto } from './dto/send-otp.dto';
|
||||
import { VerifyOtpDto } from './dto/verify-otp.dto';
|
||||
import { SmsService } from '../common/services/sms.service';
|
||||
import * as bcrypt from 'bcryptjs';
|
||||
import * as crypto from 'crypto';
|
||||
import { normalizeMobile } from '../common/utils/phone.utils';
|
||||
import { getJwtRefreshSecret } from './auth.constants';
|
||||
} from "@nestjs/common";
|
||||
import { JwtService } from "@nestjs/jwt";
|
||||
import { PrismaService } from "../prisma/prisma.service";
|
||||
import { RedisService } from "../redis/redis.service";
|
||||
import { SendOtpDto } from "./dto/send-otp.dto";
|
||||
import { VerifyOtpDto } from "./dto/verify-otp.dto";
|
||||
import { SmsService } from "../common/services/sms.service";
|
||||
import * as bcrypt from "bcryptjs";
|
||||
import * as crypto from "crypto";
|
||||
import { normalizeMobile } from "../common/utils/phone.utils";
|
||||
import { getJwtRefreshSecret } from "./auth.constants";
|
||||
|
||||
export class RegisterInput {
|
||||
firstName!: string;
|
||||
@@ -53,13 +53,13 @@ export class AuthService {
|
||||
const refreshPayload = { ...payload, jti: tokenId };
|
||||
const refreshToken = this.jwtService.sign(refreshPayload, {
|
||||
secret: refreshSecret,
|
||||
expiresIn: '30d',
|
||||
expiresIn: "30d",
|
||||
});
|
||||
|
||||
// Store active refresh token in Redis (30 days TTL = 2,592,000s)
|
||||
await this.redisService.set(
|
||||
`refresh_token:${payload.sub}:${tokenId}`,
|
||||
'1',
|
||||
"1",
|
||||
30 * 24 * 3600,
|
||||
);
|
||||
|
||||
@@ -79,7 +79,7 @@ export class AuthService {
|
||||
success: false,
|
||||
statusCode: HttpStatus.TOO_MANY_REQUESTS,
|
||||
message: `لطفاً ${Math.max(1, remainingTtl)} ثانیه دیگر مجدداً تلاش کنید.`,
|
||||
code: 'OTP_COOLDOWN',
|
||||
code: "OTP_COOLDOWN",
|
||||
remainingSeconds: Math.max(1, remainingTtl),
|
||||
},
|
||||
HttpStatus.TOO_MANY_REQUESTS,
|
||||
@@ -95,8 +95,8 @@ export class AuthService {
|
||||
success: false,
|
||||
statusCode: HttpStatus.TOO_MANY_REQUESTS,
|
||||
message:
|
||||
'تعداد دفعات ارسال پیامک در یک ساعت بیش از حد مجاز است. لطفاً ساعتی دیگر تلاش کنید.',
|
||||
code: 'HOURLY_RATE_LIMIT_EXCEEDED',
|
||||
"تعداد دفعات ارسال پیامک در یک ساعت بیش از حد مجاز است. لطفاً ساعتی دیگر تلاش کنید.",
|
||||
code: "HOURLY_RATE_LIMIT_EXCEEDED",
|
||||
},
|
||||
HttpStatus.TOO_MANY_REQUESTS,
|
||||
);
|
||||
@@ -111,8 +111,8 @@ export class AuthService {
|
||||
success: false,
|
||||
statusCode: HttpStatus.TOO_MANY_REQUESTS,
|
||||
message:
|
||||
'سقف ارسال روزانه پیامک برای این شماره تکمیل شده است. لطفاً فردا مجدداً تلاش کنید.',
|
||||
code: 'DAILY_RATE_LIMIT_EXCEEDED',
|
||||
"سقف ارسال روزانه پیامک برای این شماره تکمیل شده است. لطفاً فردا مجدداً تلاش کنید.",
|
||||
code: "DAILY_RATE_LIMIT_EXCEEDED",
|
||||
},
|
||||
HttpStatus.TOO_MANY_REQUESTS,
|
||||
);
|
||||
@@ -131,17 +131,17 @@ export class AuthService {
|
||||
await this.redisService.del(`otp:${phoneNumber}`);
|
||||
throw new BadRequestException({
|
||||
message:
|
||||
'ارسال پیامک با خطا مواجه شد. لطفاً چند لحظه دیگر دوباره تلاش کنید.',
|
||||
error: 'SMS_DELIVERY_FAILED',
|
||||
"ارسال پیامک با خطا مواجه شد. لطفاً چند لحظه دیگر دوباره تلاش کنید.",
|
||||
error: "SMS_DELIVERY_FAILED",
|
||||
});
|
||||
}
|
||||
|
||||
// Set 60-second cooldown lock
|
||||
await this.redisService.set(cooldownKey, '1', 60);
|
||||
await this.redisService.set(cooldownKey, "1", 60);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: 'کد تایید با موفقیت به شماره شما پیامک شد.',
|
||||
message: "کد تایید با موفقیت به شماره شما پیامک شد.",
|
||||
expiresIn: 120,
|
||||
cooldown: 60,
|
||||
};
|
||||
@@ -158,8 +158,8 @@ export class AuthService {
|
||||
await this.redisService.del(`otp:${phoneNumber}`);
|
||||
throw new BadRequestException({
|
||||
message:
|
||||
'تعداد تلاشهای ناموفق بیش از حد مجاز است. لطفاً پس از چند دقیقه دوباره کد جدید دریافت کنید.',
|
||||
error: 'TOO_MANY_OTP_ATTEMPTS',
|
||||
"تعداد تلاشهای ناموفق بیش از حد مجاز است. لطفاً پس از چند دقیقه دوباره کد جدید دریافت کنید.",
|
||||
error: "TOO_MANY_OTP_ATTEMPTS",
|
||||
});
|
||||
}
|
||||
|
||||
@@ -172,13 +172,13 @@ export class AuthService {
|
||||
await this.redisService.del(`otp:${phoneNumber}`);
|
||||
throw new BadRequestException({
|
||||
message:
|
||||
'کد تایید به دلیل ۵ بار تلاش ناموفق باطل شد. لطفاً کد جدید دریافت کنید.',
|
||||
error: 'TOO_MANY_OTP_ATTEMPTS',
|
||||
"کد تایید به دلیل ۵ بار تلاش ناموفق باطل شد. لطفاً کد جدید دریافت کنید.",
|
||||
error: "TOO_MANY_OTP_ATTEMPTS",
|
||||
});
|
||||
}
|
||||
throw new BadRequestException({
|
||||
message: `کد وارد شده اشتباه یا منقضی شده است. (${remaining} تلاش باقیمانده)`,
|
||||
error: 'INVALID_OTP',
|
||||
error: "INVALID_OTP",
|
||||
});
|
||||
}
|
||||
|
||||
@@ -194,8 +194,8 @@ export class AuthService {
|
||||
user = await this.prisma.user.create({
|
||||
data: {
|
||||
mobile: phoneNumber,
|
||||
firstName: 'کاربر',
|
||||
lastName: 'جدید',
|
||||
firstName: "کاربر",
|
||||
lastName: "جدید",
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -228,8 +228,8 @@ export class AuthService {
|
||||
});
|
||||
if (existingUser) {
|
||||
throw new BadRequestException({
|
||||
message: 'کاربری با این شماره موبایل قبلا ثبت نام کرده است',
|
||||
error: 'MOBILE_EXISTS',
|
||||
message: "کاربری با این شماره موبایل قبلا ثبت نام کرده است",
|
||||
error: "MOBILE_EXISTS",
|
||||
});
|
||||
}
|
||||
|
||||
@@ -239,13 +239,13 @@ export class AuthService {
|
||||
});
|
||||
if (existingEmail) {
|
||||
throw new BadRequestException({
|
||||
message: 'کاربری با این ایمیل قبلا ثبت نام کرده است',
|
||||
error: 'EMAIL_EXISTS',
|
||||
message: "کاربری با این ایمیل قبلا ثبت نام کرده است",
|
||||
error: "EMAIL_EXISTS",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const hashedPassword = password ? await bcrypt.hash(password, 10) : '';
|
||||
const hashedPassword = password ? await bcrypt.hash(password, 10) : "";
|
||||
|
||||
const user = await this.prisma.user.create({
|
||||
data: {
|
||||
@@ -273,20 +273,20 @@ export class AuthService {
|
||||
|
||||
async login(loginDto: LoginInput) {
|
||||
const mobile = normalizeMobile(loginDto.mobile);
|
||||
const password = loginDto.password ? loginDto.password.trim() : '';
|
||||
const password = loginDto.password ? loginDto.password.trim() : "";
|
||||
|
||||
const user = await this.prisma.user.findUnique({ where: { mobile } });
|
||||
if (!user) {
|
||||
throw new BadRequestException({
|
||||
message: 'نام کاربری یا رمز عبور اشتباه است',
|
||||
error: 'INVALID_CREDENTIALS',
|
||||
message: "نام کاربری یا رمز عبور اشتباه است",
|
||||
error: "INVALID_CREDENTIALS",
|
||||
});
|
||||
}
|
||||
|
||||
if (!user.password) {
|
||||
throw new BadRequestException({
|
||||
message: 'شما با رمز عبور ثبت نام نکردهاید. لطفاً با موبایل وارد شوید',
|
||||
error: 'NO_PASSWORD',
|
||||
message: "شما با رمز عبور ثبت نام نکردهاید. لطفاً با موبایل وارد شوید",
|
||||
error: "NO_PASSWORD",
|
||||
});
|
||||
}
|
||||
|
||||
@@ -295,8 +295,8 @@ export class AuthService {
|
||||
: false;
|
||||
if (!isMatch) {
|
||||
throw new BadRequestException({
|
||||
message: 'نام کاربری یا رمز عبور اشتباه است',
|
||||
error: 'INVALID_CREDENTIALS',
|
||||
message: "نام کاربری یا رمز عبور اشتباه است",
|
||||
error: "INVALID_CREDENTIALS",
|
||||
});
|
||||
}
|
||||
|
||||
@@ -319,7 +319,7 @@ export class AuthService {
|
||||
const dbAdmin = await this.prisma.user.findFirst({
|
||||
where: {
|
||||
email: body.email,
|
||||
role: { in: ['Admin', 'SUPER_ADMIN', 'ADMIN'] },
|
||||
role: { in: ["Admin", "SUPER_ADMIN", "ADMIN"] },
|
||||
},
|
||||
});
|
||||
|
||||
@@ -345,10 +345,10 @@ export class AuthService {
|
||||
}
|
||||
|
||||
// In production, fallback credentials MUST NOT be accepted
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
if (process.env.NODE_ENV === "production") {
|
||||
throw new BadRequestException({
|
||||
message: 'ایمیل یا رمز عبور مدیریت اشتباه است',
|
||||
error: 'INVALID_ADMIN_CREDENTIALS',
|
||||
message: "ایمیل یا رمز عبور مدیریت اشتباه است",
|
||||
error: "INVALID_ADMIN_CREDENTIALS",
|
||||
});
|
||||
}
|
||||
|
||||
@@ -366,29 +366,29 @@ export class AuthService {
|
||||
const emailMatches =
|
||||
body.email.length === adminEmail.length &&
|
||||
crypto.timingSafeEqual(
|
||||
Buffer.from(crypto.createHash('sha256').update(body.email).digest()),
|
||||
Buffer.from(crypto.createHash('sha256').update(adminEmail).digest()),
|
||||
Buffer.from(crypto.createHash("sha256").update(body.email).digest()),
|
||||
Buffer.from(crypto.createHash("sha256").update(adminEmail).digest()),
|
||||
);
|
||||
|
||||
const passwordMatches = crypto.timingSafeEqual(
|
||||
Buffer.from(crypto.createHash('sha256').update(body.password).digest()),
|
||||
Buffer.from(crypto.createHash('sha256').update(adminPassword).digest()),
|
||||
Buffer.from(crypto.createHash("sha256").update(body.password).digest()),
|
||||
Buffer.from(crypto.createHash("sha256").update(adminPassword).digest()),
|
||||
);
|
||||
|
||||
if (emailMatches && passwordMatches) {
|
||||
const payload = {
|
||||
sub: '12345678-1234-1234-1234-123456789012',
|
||||
sub: "12345678-1234-1234-1234-123456789012",
|
||||
email: adminEmail,
|
||||
role: 'Admin',
|
||||
role: "Admin",
|
||||
};
|
||||
const tokens = await this.generateTokens(payload);
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
user: {
|
||||
id: '12345678-1234-1234-1234-123456789012',
|
||||
id: "12345678-1234-1234-1234-123456789012",
|
||||
email: body.email,
|
||||
role: 'Admin',
|
||||
role: "Admin",
|
||||
},
|
||||
accessToken: tokens.accessToken,
|
||||
refreshToken: tokens.refreshToken,
|
||||
@@ -398,14 +398,14 @@ export class AuthService {
|
||||
}
|
||||
|
||||
throw new BadRequestException({
|
||||
message: 'ایمیل یا رمز عبور مدیریت اشتباه است',
|
||||
error: 'INVALID_ADMIN_CREDENTIALS',
|
||||
message: "ایمیل یا رمز عبور مدیریت اشتباه است",
|
||||
error: "INVALID_ADMIN_CREDENTIALS",
|
||||
});
|
||||
}
|
||||
|
||||
async refreshToken(rawRefreshToken: string) {
|
||||
if (!rawRefreshToken) {
|
||||
throw new UnauthorizedException('توکن تازهسازی یافت نشد');
|
||||
throw new UnauthorizedException("توکن تازهسازی یافت نشد");
|
||||
}
|
||||
|
||||
let decoded: any;
|
||||
@@ -415,7 +415,7 @@ export class AuthService {
|
||||
});
|
||||
} catch {
|
||||
throw new UnauthorizedException(
|
||||
'توکن تازهسازی نامعتبر یا منقضی شده است',
|
||||
"توکن تازهسازی نامعتبر یا منقضی شده است",
|
||||
);
|
||||
}
|
||||
|
||||
@@ -423,7 +423,7 @@ export class AuthService {
|
||||
const tokenId = decoded.jti;
|
||||
|
||||
if (!userId || !tokenId) {
|
||||
throw new UnauthorizedException('اطلاعات توکن نامعتبر است');
|
||||
throw new UnauthorizedException("اطلاعات توکن نامعتبر است");
|
||||
}
|
||||
|
||||
// Check if token exists in Redis
|
||||
@@ -431,7 +431,7 @@ export class AuthService {
|
||||
const tokenValid = await this.redisService.get(tokenKey);
|
||||
if (!tokenValid) {
|
||||
throw new UnauthorizedException(
|
||||
'توکن تازهسازی باطل شده است. لطفاً مجدداً وارد شوید',
|
||||
"توکن تازهسازی باطل شده است. لطفاً مجدداً وارد شوید",
|
||||
);
|
||||
}
|
||||
|
||||
@@ -451,22 +451,22 @@ export class AuthService {
|
||||
};
|
||||
const { password: _p, ...restUser } = user;
|
||||
safeUser = restUser;
|
||||
} else if (userId === '12345678-1234-1234-1234-123456789012') {
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
throw new UnauthorizedException('حساب کاربری مدیریت معتبر نیست');
|
||||
} else if (userId === "12345678-1234-1234-1234-123456789012") {
|
||||
if (process.env.NODE_ENV === "production") {
|
||||
throw new UnauthorizedException("حساب کاربری مدیریت معتبر نیست");
|
||||
}
|
||||
userPayload = {
|
||||
sub: userId,
|
||||
email: decoded.email,
|
||||
role: 'Admin',
|
||||
role: "Admin",
|
||||
};
|
||||
safeUser = {
|
||||
id: userId,
|
||||
email: decoded.email,
|
||||
role: 'Admin',
|
||||
role: "Admin",
|
||||
};
|
||||
} else {
|
||||
throw new UnauthorizedException('کاربر یافت نشد');
|
||||
throw new UnauthorizedException("کاربر یافت نشد");
|
||||
}
|
||||
|
||||
// Issue new pair of tokens
|
||||
@@ -515,7 +515,7 @@ export class AuthService {
|
||||
ttl = remaining;
|
||||
}
|
||||
}
|
||||
await this.redisService.set(`bl_token:${token}`, '1', ttl);
|
||||
await this.redisService.set(`bl_token:${token}`, "1", ttl);
|
||||
|
||||
// If token payload has jti and sub, also invalidate the refresh token in Redis
|
||||
if (decoded && decoded.sub && decoded.jti) {
|
||||
@@ -524,7 +524,7 @@ export class AuthService {
|
||||
);
|
||||
}
|
||||
} catch {
|
||||
await this.redisService.set(`bl_token:${token}`, '1', 15 * 60);
|
||||
await this.redisService.set(`bl_token:${token}`, "1", 15 * 60);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,15 @@
|
||||
import { IsEmail, IsNotEmpty, IsString, MinLength } from 'class-validator';
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsEmail, IsNotEmpty, IsString, MinLength } from "class-validator";
|
||||
import { ApiProperty } from "@nestjs/swagger";
|
||||
|
||||
export class AdminLoginDto {
|
||||
@ApiProperty({ description: 'ایمیل ادمین', example: 'admin@canina.ir' })
|
||||
@IsEmail({}, { message: 'فرمت ایمیل وارد شده معتبر نمیباشد.' })
|
||||
@IsNotEmpty({ message: 'ایمیل الزامی است.' })
|
||||
@ApiProperty({ description: "ایمیل ادمین", example: "admin@canina.ir" })
|
||||
@IsEmail({}, { message: "فرمت ایمیل وارد شده معتبر نمیباشد." })
|
||||
@IsNotEmpty({ message: "ایمیل الزامی است." })
|
||||
email!: string;
|
||||
|
||||
@ApiProperty({ description: 'رمز عبور ادمین', example: 'admin123' })
|
||||
@IsString({ message: 'رمز عبور باید رشته متنی باشد.' })
|
||||
@MinLength(6, { message: 'رمز عبور باید حداقل ۶ کاراکتر باشد.' })
|
||||
@IsNotEmpty({ message: 'رمز عبور الزامی است.' })
|
||||
@ApiProperty({ description: "رمز عبور ادمین", example: "admin123" })
|
||||
@IsString({ message: "رمز عبور باید رشته متنی باشد." })
|
||||
@MinLength(6, { message: "رمز عبور باید حداقل ۶ کاراکتر باشد." })
|
||||
@IsNotEmpty({ message: "رمز عبور الزامی است." })
|
||||
password!: string;
|
||||
}
|
||||
@@ -1,14 +1,14 @@
|
||||
import { IsNotEmpty, IsString, MinLength } from 'class-validator';
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsNotEmpty, IsString, MinLength } from "class-validator";
|
||||
import { ApiProperty } from "@nestjs/swagger";
|
||||
|
||||
export class LoginDto {
|
||||
@ApiProperty({ description: 'شماره موبایل', example: '09123456789' })
|
||||
@IsNotEmpty({ message: 'شماره موبایل الزامی است' })
|
||||
@ApiProperty({ description: "شماره موبایل", example: "09123456789" })
|
||||
@IsNotEmpty({ message: "شماره موبایل الزامی است" })
|
||||
@IsString()
|
||||
mobile: string;
|
||||
|
||||
@ApiProperty({ description: 'رمز عبور', example: 'password123' })
|
||||
@IsNotEmpty({ message: 'رمز عبور الزامی است' })
|
||||
@MinLength(6, { message: 'رمز عبور باید حداقل ۶ کاراکتر باشد' })
|
||||
@ApiProperty({ description: "رمز عبور", example: "password123" })
|
||||
@IsNotEmpty({ message: "رمز عبور الزامی است" })
|
||||
@MinLength(6, { message: "رمز عبور باید حداقل ۶ کاراکتر باشد" })
|
||||
password: string;
|
||||
}
|
||||
@@ -1,12 +1,12 @@
|
||||
import { IsNotEmpty, IsString } from 'class-validator';
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsNotEmpty, IsString } from "class-validator";
|
||||
import { ApiProperty } from "@nestjs/swagger";
|
||||
|
||||
export class RefreshTokenDto {
|
||||
@ApiProperty({
|
||||
description: 'توکن تازهسازی (Refresh Token)',
|
||||
example: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...',
|
||||
description: "توکن تازهسازی (Refresh Token)",
|
||||
example: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
|
||||
})
|
||||
@IsNotEmpty({ message: 'ارسال توکن تازهسازی الزامی است' })
|
||||
@IsString({ message: 'توکن تازهسازی باید رشته متنی باشد' })
|
||||
@IsNotEmpty({ message: "ارسال توکن تازهسازی الزامی است" })
|
||||
@IsString({ message: "توکن تازهسازی باید رشته متنی باشد" })
|
||||
refreshToken: string;
|
||||
}
|
||||
@@ -4,35 +4,35 @@ import {
|
||||
IsOptional,
|
||||
IsString,
|
||||
MinLength,
|
||||
} from 'class-validator';
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
} from "class-validator";
|
||||
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
|
||||
|
||||
export class RegisterDto {
|
||||
@ApiProperty({ description: 'نام', example: 'علی' })
|
||||
@IsNotEmpty({ message: 'نام الزامی است' })
|
||||
@ApiProperty({ description: "نام", example: "علی" })
|
||||
@IsNotEmpty({ message: "نام الزامی است" })
|
||||
@IsString()
|
||||
firstName: string;
|
||||
|
||||
@ApiProperty({ description: 'نام خانوادگی', example: 'رضایی' })
|
||||
@IsNotEmpty({ message: 'نام خانوادگی الزامی است' })
|
||||
@ApiProperty({ description: "نام خانوادگی", example: "رضایی" })
|
||||
@IsNotEmpty({ message: "نام خانوادگی الزامی است" })
|
||||
@IsString()
|
||||
lastName: string;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description: 'ایمیل (اختیاری)',
|
||||
example: 'ali@example.com',
|
||||
description: "ایمیل (اختیاری)",
|
||||
example: "ali@example.com",
|
||||
})
|
||||
@IsOptional()
|
||||
@IsEmail({}, { message: 'ایمیل نامعتبر است' })
|
||||
@IsEmail({}, { message: "ایمیل نامعتبر است" })
|
||||
email?: string;
|
||||
|
||||
@ApiProperty({ description: 'شماره موبایل', example: '09123456789' })
|
||||
@IsNotEmpty({ message: 'شماره موبایل الزامی است' })
|
||||
@ApiProperty({ description: "شماره موبایل", example: "09123456789" })
|
||||
@IsNotEmpty({ message: "شماره موبایل الزامی است" })
|
||||
@IsString()
|
||||
mobile: string;
|
||||
|
||||
@ApiProperty({ description: 'رمز عبور', example: 'password123' })
|
||||
@IsNotEmpty({ message: 'رمز عبور الزامی است' })
|
||||
@MinLength(6, { message: 'رمز عبور باید حداقل ۶ کاراکتر باشد' })
|
||||
@ApiProperty({ description: "رمز عبور", example: "password123" })
|
||||
@IsNotEmpty({ message: "رمز عبور الزامی است" })
|
||||
@MinLength(6, { message: "رمز عبور باید حداقل ۶ کاراکتر باشد" })
|
||||
password: string;
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsNotEmpty, IsString, Matches } from 'class-validator';
|
||||
import { ApiProperty } from "@nestjs/swagger";
|
||||
import { IsNotEmpty, IsString, Matches } from "class-validator";
|
||||
|
||||
export class SendOtpDto {
|
||||
@ApiProperty({ description: 'شماره موبایل کاربر', example: '09123456789' })
|
||||
@ApiProperty({ description: "شماره موبایل کاربر", example: "09123456789" })
|
||||
@IsNotEmpty()
|
||||
@IsString()
|
||||
@Matches(/^09\d{9}$/, { message: 'شماره موبایل نامعتبر است' })
|
||||
@Matches(/^09\d{9}$/, { message: "شماره موبایل نامعتبر است" })
|
||||
phoneNumber: string;
|
||||
}
|
||||
@@ -1,16 +1,16 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsNotEmpty, IsString, Length, Matches } from 'class-validator';
|
||||
import { ApiProperty } from "@nestjs/swagger";
|
||||
import { IsNotEmpty, IsString, Length, Matches } from "class-validator";
|
||||
|
||||
export class VerifyOtpDto {
|
||||
@ApiProperty({ description: 'شماره موبایل کاربر', example: '09123456789' })
|
||||
@ApiProperty({ description: "شماره موبایل کاربر", example: "09123456789" })
|
||||
@IsNotEmpty()
|
||||
@IsString()
|
||||
@Matches(/^09\d{9}$/, { message: 'شماره موبایل نامعتبر است' })
|
||||
@Matches(/^09\d{9}$/, { message: "شماره موبایل نامعتبر است" })
|
||||
phoneNumber: string;
|
||||
|
||||
@ApiProperty({ description: 'کد تایید پیامک شده', example: '12345' })
|
||||
@ApiProperty({ description: "کد تایید پیامک شده", example: "12345" })
|
||||
@IsNotEmpty()
|
||||
@IsString()
|
||||
@Length(5, 5, { message: 'کد تایید باید ۵ رقم باشد' })
|
||||
@Length(5, 5, { message: "کد تایید باید ۵ رقم باشد" })
|
||||
code: string;
|
||||
}
|
||||
@@ -4,12 +4,12 @@ import {
|
||||
UnauthorizedException,
|
||||
Inject,
|
||||
forwardRef,
|
||||
} from '@nestjs/common';
|
||||
import { AuthGuard } from '@nestjs/passport';
|
||||
import { ApiKeysService } from '../admin/api-keys.service';
|
||||
} from "@nestjs/common";
|
||||
import { AuthGuard } from "@nestjs/passport";
|
||||
import { ApiKeysService } from "../admin/api-keys.service";
|
||||
|
||||
@Injectable()
|
||||
export class JwtAuthGuard extends AuthGuard('jwt') {
|
||||
export class JwtAuthGuard extends AuthGuard("jwt") {
|
||||
constructor(
|
||||
@Inject(forwardRef(() => ApiKeysService))
|
||||
private readonly apiKeysService?: ApiKeysService,
|
||||
@@ -20,9 +20,9 @@ export class JwtAuthGuard extends AuthGuard('jwt') {
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest();
|
||||
const apiKeyHeader =
|
||||
request.headers['x-api-key'] ||
|
||||
(request.headers['authorization']?.startsWith('ApiKey ')
|
||||
? request.headers['authorization'].replace('ApiKey ', '').trim()
|
||||
request.headers["x-api-key"] ||
|
||||
(request.headers["authorization"]?.startsWith("ApiKey ")
|
||||
? request.headers["authorization"].replace("ApiKey ", "").trim()
|
||||
: null);
|
||||
|
||||
if (apiKeyHeader && this.apiKeysService) {
|
||||
@@ -32,7 +32,7 @@ export class JwtAuthGuard extends AuthGuard('jwt') {
|
||||
return true;
|
||||
} catch (err: unknown) {
|
||||
throw new UnauthorizedException(
|
||||
(err as Error)?.message || 'کلید API نامعتبر است',
|
||||
(err as Error)?.message || "کلید API نامعتبر است",
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -48,7 +48,7 @@ export class JwtAuthGuard extends AuthGuard('jwt') {
|
||||
throw (
|
||||
(err as Error) ||
|
||||
new UnauthorizedException(
|
||||
'لطفا ابتدا وارد حساب کاربری خود شوید یا API Key معتبر ارسال کنید',
|
||||
"لطفا ابتدا وارد حساب کاربری خود شوید یا API Key معتبر ارسال کنید",
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { ExtractJwt, Strategy } from 'passport-jwt';
|
||||
import { PassportStrategy } from '@nestjs/passport';
|
||||
import { Injectable, UnauthorizedException } from '@nestjs/common';
|
||||
import { UsersService } from '../users/users.service';
|
||||
import { getJwtSecret } from './auth.constants';
|
||||
import { ExtractJwt, Strategy } from "passport-jwt";
|
||||
import { PassportStrategy } from "@nestjs/passport";
|
||||
import { Injectable, UnauthorizedException } from "@nestjs/common";
|
||||
import { UsersService } from "../users/users.service";
|
||||
import { getJwtSecret } from "./auth.constants";
|
||||
|
||||
import { RedisService } from '../redis/redis.service';
|
||||
import type { Request } from 'express';
|
||||
import { RedisService } from "../redis/redis.service";
|
||||
import type { Request } from "express";
|
||||
|
||||
export interface JwtPayload {
|
||||
sub: string;
|
||||
@@ -50,14 +50,14 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
|
||||
const isBlacklisted = await this.redisService.get(`bl_token:${rawToken}`);
|
||||
if (isBlacklisted) {
|
||||
throw new UnauthorizedException(
|
||||
'این توکن باطل شده است. لطفاً مجدداً وارد شوید',
|
||||
"این توکن باطل شده است. لطفاً مجدداً وارد شوید",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const user = await this.usersService.findById(payload.sub);
|
||||
if (!user) {
|
||||
throw new UnauthorizedException('کاربر یافت نشد');
|
||||
throw new UnauthorizedException("کاربر یافت نشد");
|
||||
}
|
||||
return user;
|
||||
}
|
||||
|
||||
@@ -1 +1 @@
|
||||
export * from '../common/decorators/roles.decorator';
|
||||
export * from "../common/decorators/roles.decorator";
|
||||
@@ -1 +1 @@
|
||||
export * from '../common/guards/roles.guard';
|
||||
export * from "../common/guards/roles.guard";
|
||||
Reference in new issue
Block a user