feat(phase2): implement database optimization and RBAC enforcement
Deploy Canina / deploy (push) Failing after 28s
Deploy Canina / deploy (push) Failing after 28s
- TASK-FIN-001: Eliminate N+1 query loop in OrdersService.create with batched findMany query.
- Perform monetary calculations strictly using Prisma.Decimal methods (.add(), .mul(), .sub()).
- Add validation for duplicate product IDs and invalid quantities in order items.
- Implement global DecimalInterceptor registered in main.ts to serialize Prisma.Decimal values into exact string representations in API responses.
- TASK-SEC-003: Create roles.decorator.ts and roles.guard.ts in common directory with backward-compatible re-exports in auth directory.
- Enforce RBAC on SettingsController with @UseGuards(JwtAuthGuard, RolesGuard) and @Roles('Admin').
- Add unit specs for DecimalInterceptor, RolesGuard, SettingsController, and OrdersService Decimal batch operations.
This commit is contained in:
1 parent
a64291a19a
commit
809c69f923
13 files changed
+403
-128
No files matched your search
@@ -0,0 +1,4 @@
|
||||
import { SetMetadata } from '@nestjs/common';
|
||||
|
||||
export const ROLES_KEY = 'roles';
|
||||
export const Roles = (...roles: string[]) => SetMetadata(ROLES_KEY, roles);
|
||||
@@ -0,0 +1,71 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { RolesGuard } from './roles.guard';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import { ExecutionContext, ForbiddenException } from '@nestjs/common';
|
||||
import { ROLES_KEY } from '../decorators/roles.decorator';
|
||||
|
||||
describe('RolesGuard', () => {
|
||||
let guard: RolesGuard;
|
||||
let reflector: Reflector;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [
|
||||
RolesGuard,
|
||||
{
|
||||
provide: Reflector,
|
||||
useValue: {
|
||||
getAllAndOverride: jest.fn(),
|
||||
},
|
||||
},
|
||||
],
|
||||
}).compile();
|
||||
|
||||
guard = module.get<RolesGuard>(RolesGuard);
|
||||
reflector = module.get<Reflector>(Reflector);
|
||||
});
|
||||
|
||||
const createMockContext = (user?: any): ExecutionContext => {
|
||||
return {
|
||||
getHandler: jest.fn(),
|
||||
getClass: jest.fn(),
|
||||
switchToHttp: () => ({
|
||||
getRequest: () => ({ user }),
|
||||
}),
|
||||
} as any;
|
||||
};
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(guard).toBeDefined();
|
||||
});
|
||||
|
||||
it('should allow access if no roles are required', () => {
|
||||
jest.spyOn(reflector, 'getAllAndOverride').mockReturnValue(undefined);
|
||||
const context = createMockContext({ role: 'User_PetOwner' });
|
||||
expect(guard.canActivate(context)).toBe(true);
|
||||
});
|
||||
|
||||
it('should throw ForbiddenException if user is missing', () => {
|
||||
jest.spyOn(reflector, 'getAllAndOverride').mockReturnValue(['Admin']);
|
||||
const context = createMockContext(undefined);
|
||||
expect(() => guard.canActivate(context)).toThrow(ForbiddenException);
|
||||
});
|
||||
|
||||
it('should throw ForbiddenException if user has non-matching role', () => {
|
||||
jest.spyOn(reflector, 'getAllAndOverride').mockReturnValue(['Admin']);
|
||||
const context = createMockContext({ role: 'User_PetOwner' });
|
||||
expect(() => guard.canActivate(context)).toThrow(ForbiddenException);
|
||||
});
|
||||
|
||||
it('should allow access if user has matching role', () => {
|
||||
jest.spyOn(reflector, 'getAllAndOverride').mockReturnValue(['Admin']);
|
||||
const context = createMockContext({ role: 'Admin' });
|
||||
expect(guard.canActivate(context)).toBe(true);
|
||||
});
|
||||
|
||||
it('should allow access if user has case-insensitive matching admin role', () => {
|
||||
jest.spyOn(reflector, 'getAllAndOverride').mockReturnValue(['Admin']);
|
||||
const context = createMockContext({ role: 'SUPER_ADMIN' });
|
||||
expect(guard.canActivate(context)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
import {
|
||||
Injectable,
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
ForbiddenException,
|
||||
} from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import { ROLES_KEY } from '../decorators/roles.decorator';
|
||||
|
||||
@Injectable()
|
||||
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()],
|
||||
);
|
||||
|
||||
if (!requiredRoles || requiredRoles.length === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const { user } = context.switchToHttp().getRequest();
|
||||
if (!user || !user.role) {
|
||||
throw new ForbiddenException('شما دسترسی لازم برای این بخش را ندارید');
|
||||
}
|
||||
|
||||
const userRoleLower = user.role.toLowerCase();
|
||||
const hasRole = requiredRoles.some(
|
||||
(r) =>
|
||||
r.toLowerCase() === userRoleLower ||
|
||||
(userRoleLower.includes('admin') && r.toLowerCase().includes('admin')),
|
||||
);
|
||||
if (!hasRole) {
|
||||
throw new ForbiddenException('سطح دسترسی شما کافی نیست');
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { DecimalInterceptor } from './decimal.interceptor';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { of } from 'rxjs';
|
||||
|
||||
describe('DecimalInterceptor', () => {
|
||||
let interceptor: DecimalInterceptor;
|
||||
|
||||
beforeEach(() => {
|
||||
interceptor = new DecimalInterceptor();
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(interceptor).toBeDefined();
|
||||
});
|
||||
|
||||
it('should transform Prisma.Decimal instances to exact string representations', (done) => {
|
||||
const mockData = {
|
||||
id: 'order-1',
|
||||
totalAmount: new Prisma.Decimal('64.98'),
|
||||
items: [
|
||||
{
|
||||
id: 'item-1',
|
||||
unitPrice: new Prisma.Decimal('32.49'),
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const executionContext: any = {};
|
||||
const callHandler: any = {
|
||||
handle: () => of(mockData),
|
||||
};
|
||||
|
||||
interceptor.intercept(executionContext, callHandler).subscribe((result) => {
|
||||
expect(result).toEqual({
|
||||
id: 'order-1',
|
||||
totalAmount: '64.98',
|
||||
items: [
|
||||
{
|
||||
id: 'item-1',
|
||||
unitPrice: '32.49',
|
||||
},
|
||||
],
|
||||
});
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
it('should leave non-decimal values unchanged', (done) => {
|
||||
const mockData = {
|
||||
name: 'Test',
|
||||
age: 5,
|
||||
isActive: true,
|
||||
createdAt: new Date('2026-01-01T00:00:00.000Z'),
|
||||
};
|
||||
|
||||
const callHandler: any = {
|
||||
handle: () => of(mockData),
|
||||
};
|
||||
|
||||
interceptor.intercept({} as any, callHandler).subscribe((result) => {
|
||||
expect(result).toEqual(mockData);
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
import {
|
||||
Injectable,
|
||||
NestInterceptor,
|
||||
ExecutionContext,
|
||||
CallHandler,
|
||||
} from '@nestjs/common';
|
||||
import { Observable } from 'rxjs';
|
||||
import { map } from 'rxjs/operators';
|
||||
import { Prisma } from '@prisma/client';
|
||||
|
||||
@Injectable()
|
||||
export class DecimalInterceptor implements NestInterceptor {
|
||||
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
|
||||
return next.handle().pipe(map((data) => this.transform(data)));
|
||||
}
|
||||
|
||||
private transform(data: any): any {
|
||||
if (data === null || data === undefined) {
|
||||
return data;
|
||||
}
|
||||
|
||||
if (Prisma.Decimal.isDecimal(data)) {
|
||||
return data.toString();
|
||||
}
|
||||
|
||||
if (Array.isArray(data)) {
|
||||
return data.map((item) => this.transform(item));
|
||||
}
|
||||
|
||||
if (typeof data === 'object' && !(data instanceof Date)) {
|
||||
const transformedObj: Record<string, any> = {};
|
||||
for (const key of Object.keys(data)) {
|
||||
transformedObj[key] = this.transform(data[key]);
|
||||
}
|
||||
return transformedObj;
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user