Compare commits

...

5 Commits

Author SHA1 Message Date
morteza b8e4b5fe95 order
deploy to danak / build_and_deploy (push) Has been cancelled
2026-07-24 18:34:26 +03:30
morteza ac58fcfd66 update
deploy to danak / build_and_deploy (push) Has been cancelled
2026-07-24 18:16:36 +03:30
morteza b793dad234 admin perms decorator
deploy to danak / build_and_deploy (push) Has been cancelled
2026-07-24 17:16:54 +03:30
morteza 857d10bf44 auth module
deploy to danak / build_and_deploy (push) Has been cancelled
2026-07-24 13:24:00 +03:30
morteza bf203a579d menu count
deploy to danak / build_and_deploy (push) Has been cancelled
2026-07-23 19:39:39 +03:30
17 changed files with 175 additions and 107 deletions
+1 -1
View File
@@ -31,9 +31,9 @@ import { cacheConfig } from './config/cache.config';
ConfigModule.forRoot({ isGlobal: true, cache: true }),
CacheModule.registerAsync(cacheConfig()),
MikroOrmModule.forRootAsync(dataBaseConfig),
AuthModule,
UserModule,
UtilsModule,
AuthModule,
UploaderModule,
AdminModule,
ThrottlerModule.forRoot([
@@ -0,0 +1,18 @@
import { createParamDecorator, type ExecutionContext } from '@nestjs/common';
import type { Request } from 'express';
/**
* Decorator to extract userId from the authenticated request.
* Must be used after AdminAuthGuard or AuthGuard that sets request.userId.
*
* @example
* @Get('/profile')
* @UseGuards(AdminAuthGuard)
* getProfile(@UserId() userId: string) {
* return this.userService.findById(userId);
* }
*/
export const AdminPerms = createParamDecorator((data: unknown, ctx: ExecutionContext): string[] => {
const request = ctx.switchToHttp().getRequest<Request & { permissions?: string[] }>();
return request.permissions || [];
});
+3
View File
@@ -1,5 +1,7 @@
export enum PermissionEnum {
DASHBOARD = 'dashboard',
MANAGE_PRODUCTS = 'manage_products',
MANAGE_CATEGORIES = 'manage_categories',
@@ -60,6 +62,7 @@ export enum PermissionEnum {
export const PermissionTitles: Record<PermissionEnum, string> = {
[PermissionEnum.DASHBOARD]: 'مشاهده داشبورد',
[PermissionEnum.MANAGE_PRODUCTS]: 'مدیریت محصولات',
[PermissionEnum.MANAGE_CATEGORIES]: 'مدیریت دسته‌بندی‌ها',
@@ -9,6 +9,7 @@ import { AdminId } from 'src/common/decorators/admin-id.decorator';
import { Admin } from '../entities/admin.entity';
import { PermissionEnum } from 'src/common/enums/permission.enum';
import { Permissions } from 'src/common/decorators/permissions.decorator';
import { AdminPerms } from 'src/common/decorators/admin-perms.decorator';
@Controller()
@ApiTags('admin')
@@ -20,7 +21,7 @@ export class AdminController {
@Post('admin/admin')
@Permissions(PermissionEnum.MANAGE_ADMINS)
@ApiOperation({ summary: 'Create a new admin' })
async create(@Body() dto: CreateAdminDto,) {
async create(@Body() dto: CreateAdminDto) {
const admin = await this.adminService.create(dto);
return admin;
}
@@ -40,55 +41,55 @@ export class AdminController {
@Get('admin/admins/me')
@ApiOperation({ summary: 'Get current authenticated admin profile' })
async getMe(@AdminId() adminId: string,) {
const admin = await this.adminService.findById(adminId,);
async getMe(@AdminId() adminId: string) {
const admin = await this.adminService.findById(adminId);
return admin;
}
@Patch('admin/admins/me')
@ApiOperation({ summary: 'Update current authenticated admin profile' })
updateMe(@AdminId() adminId: string, @Body() dto: UpdateAdminMeDto,): Promise<Admin> {
updateMe(@AdminId() adminId: string, @Body() dto: UpdateAdminMeDto): Promise<Admin> {
return this.adminService.updateMe(adminId, dto);
}
@Get('admin/dashboard/counts')
@ApiOperation({ summary: 'Get dashboard entity counts for admin panel' })
getDashboardCounts() {
return this.adminService.getDashboardCounts();
@Get('admin/menu/counts')
@ApiOperation({ summary: 'Get metrics for admin panel' })
getDashboardCounts(@AdminId() adminId: string, @AdminPerms() permissions: string[]) {
return this.adminService.getDashboardCounts(adminId, permissions);
}
@Get('admin/home/stats')
@Permissions(PermissionEnum.DASHBOARD)
@ApiOperation({ summary: 'Get home page stats for admin panel' })
getHomeStats() {
return this.adminService.getHomeStats();
}
@Get('admin/home/weekly-orders')
@Permissions(PermissionEnum.DASHBOARD)
@ApiOperation({ summary: 'Get weekly order counts for admin home page chart' })
getWeeklyOrders() {
return this.adminService.getWeeklyOrders();
}
@Patch('admin/admins/:adminId')
@Permissions(PermissionEnum.MANAGE_ADMINS)
@ApiOperation({ summary: 'Update an admin' })
update(@Param('adminId') adminId: string, @Body() dto: UpdateAdminDto,): Promise<Admin> {
update(@Param('adminId') adminId: string, @Body() dto: UpdateAdminDto): Promise<Admin> {
return this.adminService.update(adminId, dto);
}
@Get('admin/admins/:adminId')
@Permissions(PermissionEnum.MANAGE_ADMINS)
@ApiOperation({ summary: 'Get an admin by ID' })
getById(@Param('adminId') adminId: string,): Promise<Admin | null> {
return this.adminService.findById(adminId,);
getById(@Param('adminId') adminId: string): Promise<Admin | null> {
return this.adminService.findById(adminId);
}
@Delete('admin/admins/:adminId')
@Permissions(PermissionEnum.MANAGE_ADMINS)
@ApiOperation({ summary: 'Delete an admin by ID' })
deleteById(@Param('adminId') adminId: string,): Promise<void> {
return this.adminService.softDelete(adminId,);
deleteById(@Param('adminId') adminId: string): Promise<void> {
return this.adminService.softDelete(adminId);
}
}
+13 -18
View File
@@ -102,7 +102,7 @@ export class AdminService {
}
if (rest.phone !== undefined && rest.phone !== admin.phone) {
const exists = await this.adminRepository.findOne({ phone: rest.phone,id: { $ne: adminId } });
const exists = await this.adminRepository.findOne({ phone: rest.phone, id: { $ne: adminId } });
if (exists) {
throw new ConflictException('This Phone Number is already taken');
}
@@ -148,28 +148,23 @@ export class AdminService {
}
return admins
}
async ownedPermissions(adminId: string, permissionNames: PermissionEnum[]): Promise<PermissionEnum[]> {
if (permissionNames.length === 0) return []
async getDashboardCounts(adminId: string, permissions: string[]) {
const canViewAnyOrder = permissions.includes(PermissionEnum.VIEW_ORDERS);
const canViewAssignedOrder = permissions.includes(PermissionEnum.VIEW_ASSIGNED_ORDERS);
const admin = await this.adminRepository.findOne(
{ id: adminId },
{ populate: ['role', 'role.permissions'] },
)
const ordersCountPromise = canViewAnyOrder
? this.em.count(Order)
: canViewAssignedOrder
? this.em.count(Order, { designers: { designer: { id: adminId } } })
: Promise.resolve(0);
if (!admin?.role?.permissions) return []
const adminPermissionNames = new Set(
admin.role.permissions.getItems().map((p) => p.name),
)
return permissionNames.filter((name) => adminPermissionNames.has(name))
}
async getDashboardCounts() {
const [requestsCount, invoicesCount, ordersCount, paymentsCount] = await Promise.all([
this.em.count(Request),
this.em.count(Invoice),
this.em.count(Order),
this.em.count(Invoice, { status: { $nin: [InvoiceConfirmStatusEnum.ARCHIVED] } }),
ordersCountPromise,
this.em.count(Payment),
]);
+3 -2
View File
@@ -1,4 +1,4 @@
import { Module, forwardRef } from '@nestjs/common';
import { Global, Module, forwardRef } from '@nestjs/common';
import { AuthService } from './services/auth.service';
import { AuthController } from './controllers/auth.controller';
import { UtilsModule } from '../util/utils.module';
@@ -13,6 +13,7 @@ import { RefreshToken } from './entities/refresh-token.entity';
import { NotificationsModule } from '../notification/notifications.module';
import { OtpService } from './services/otp.service';
@Global()
@Module({
imports: [
UtilsModule,
@@ -38,6 +39,6 @@ import { OtpService } from './services/otp.service';
],
controllers: [AuthController],
providers: [AuthService, TokensService, AdminAuthGuard, OtpService],
exports: [AdminAuthGuard],
exports: [AdminAuthGuard, AuthService],
})
export class AuthModule { }
+16 -24
View File
@@ -13,10 +13,11 @@ import { JwtService } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config';
import { IAdminTokenPayload } from '../interfaces/IToken-payload';
import { PERMISSIONS_KEY } from '../../../common/decorators/permissions.decorator';
import { PermissionService } from 'src/modules/roles/providers/permissions.service';
import { AuthService } from '../services/auth.service';
export interface AdminAuthRequest extends Request {
adminId: string;
permissions: string[];
}
@Injectable()
@@ -28,7 +29,7 @@ export class AdminAuthGuard implements CanActivate {
private readonly jwtService: JwtService,
@Inject(ConfigService)
private readonly configService: ConfigService,
private readonly permissionsService: PermissionService,
private readonly authService: AuthService,
private readonly reflector: Reflector,
) { }
@@ -61,34 +62,25 @@ export class AdminAuthGuard implements CanActivate {
request['adminId'] = payload.adminId;
const adminPermissions = await this.authService.getAdminPermissionsFromCache(payload.adminId);
request['permissions'] = adminPermissions;
// check if the user has the required permissions
const requiredPermissions =
this.reflector.getAllAndOverride<string[]>(PERMISSIONS_KEY, [context.getHandler(), context.getClass()]) ?? [];
if (!requiredPermissions || requiredPermissions.length === 0) {
return true;
if (requiredPermissions.length > 0) {
const hasPermission = requiredPermissions.every(p => adminPermissions.includes(p));
if (!hasPermission) {
this.logger.warn('Insufficient permissions', {
adminId: payload.adminId,
required: requiredPermissions,
has: hasPermission,
});
throw new ForbiddenException('You are not authorized to access this resource');
}
}
//TODO : admin permissions must get it from cache
// const adminPermission = (await this.permissionsService.getAdminPermissions(payload.adminId))
// if (!adminPermission || !Array.isArray(adminPermission)) {
// this.logger.error('No permissions found', { adminId: payload.adminId });
// throw new ForbiddenException('No permissions found');
// }
// const adminPermissionNames = adminPermission.map(p => p.name)
// const hasPermission = requiredPermissions.every(p => adminPermissionNames.includes(p));
// if (!hasPermission) {
// this.logger.warn('Insufficient permissions', {
// adminId: payload.adminId,
// required: requiredPermissions,
// has: adminPermission,
// });
// throw new ForbiddenException('You are not authorized to access this resource');
// }
return true;
} catch (err) {
+39 -5
View File
@@ -10,10 +10,12 @@ import { AdminLoginTransformer } from '../transformers/admin-login.transformer';
import { UserLoginTransformer } from '../transformers/user-login.transformer';
import { OtpService } from './otp.service';
import { normalizePhoneToLocal } from 'src/modules/util/phone.util';
import { CacheService } from 'src/modules/util/cache.service';
import { PermissionService } from 'src/modules/roles/providers/permissions.service';
@Injectable()
export class AuthService {
readonly ADMIN_PERMISSIONS_KEY = 'admin-perms';
readonly ADMIN_PERMISSIONS_EXPIRATION_TIME = 1800;
constructor(
private readonly smsService: SmsService,
@@ -21,8 +23,10 @@ export class AuthService {
private readonly tokensService: TokensService,
private readonly adminRepository: AdminRepository,
private readonly otpService: OtpService,
private readonly cacheService: CacheService,
private readonly permissionService: PermissionService,
) {
}
async requestOtp(dto: RequestOtpDto, isAdmin: boolean) {
@@ -33,9 +37,9 @@ export class AuthService {
}
const code = this.generateOtpCode();
await this.otpService.set(phone, code)
// await this.smsService.sendotp(phone, code);
return { code };
@@ -82,6 +86,10 @@ export class AuthService {
const tokens = await this.tokensService.generateAccessAndRefreshToken(admin.id, true);
const permissionNames = admin.role.permissions.map(p => p.name);
const adminResponse = await AdminLoginTransformer.transform(admin);
return { tokens, admin: adminResponse };
@@ -103,4 +111,30 @@ export class AuthService {
}
}
}
async setAdminPermissionsInCache(adminId: string, permissionNames: string[]) {
await this.cacheService.set(
this.getAdminPermissionsCacheKey(adminId),
JSON.stringify(permissionNames),
this.ADMIN_PERMISSIONS_EXPIRATION_TIME,
);
return { success: true };
}
async getAdminPermissionsFromCache(adminId: string): Promise<string[]> {
const cacheKey = this.getAdminPermissionsCacheKey(adminId);
const cached = await this.cacheService.get<string>(cacheKey);
if (cached !== undefined) {
return JSON.parse(cached) as string[];
}
const permissions = await this.permissionService.getAdminPermissionsName(adminId);
await this.setAdminPermissionsInCache(adminId, permissions);
return permissions;
}
private getAdminPermissionsCacheKey(adminId: string): string {
return `admin:${adminId}:permissions`;
}
}
@@ -7,6 +7,7 @@ import { FindOrdersDto } from '../dto/find-orders.dto';
import { CreateOrderAsAdminDto } from '../dto/create-order.dto';
import { UpdateOrderAsAdminDto } from '../dto/update-order.dto';
import { AdminId } from 'src/common/decorators/admin-id.decorator';
import { AdminPerms } from 'src/common/decorators/admin-perms.decorator';
import { AdminAuthGuard } from 'src/modules/auth/guards/adminAuth.guard';
import { Permissions } from 'src/common/decorators/permissions.decorator';
import { PermissionEnum } from 'src/common/enums/permission.enum';
@@ -39,7 +40,7 @@ export class OrderController {
@Get('public/orders/stats')
@UseGuards(AuthGuard)
@ApiOperation({ summary: 'Get User Orders stats' })
getStats( @UserId() userId: string) {
getStats(@UserId() userId: string) {
return this.orderService.getStats(userId);
}
/*========================== Admin Routes =====================*/
@@ -55,17 +56,24 @@ export class OrderController {
// Permission handled inside service
@Get('admin/orders')
@UseGuards(AdminAuthGuard)
// @Permissions(PermissionEnum.VIEW_ORDERS)
@ApiOperation({ summary: 'Get all orders with pagination and filters' })
findAllAsAdmin(@Query() dto: FindOrdersDto, @AdminId() adminId: string) {
return this.orderService.findOrdersAsAdmin(adminId, dto);
findAllAsAdmin(
@Query() dto: FindOrdersDto,
@AdminId() adminId: string,
@AdminPerms() permissions: string[],
) {
return this.orderService.findOrdersAsAdmin(adminId, permissions, dto);
}
@Get('admin/orders/tab-counts')
@UseGuards(AdminAuthGuard)
@ApiOperation({ summary: 'Get order tab counts for admin order list' })
getAdminOrderTabCounts(@Query() dto: FindOrdersDto, @AdminId() adminId: string) {
return this.orderService.getAdminOrderTabCounts(adminId, dto);
getAdminOrderTabCounts(
@Query() dto: FindOrdersDto,
@AdminId() adminId: string,
@AdminPerms() permissions: string[],
) {
return this.orderService.getAdminOrderTabCounts(adminId, permissions, dto);
}
@Get('admin/orders/:id')
@@ -106,8 +114,13 @@ export class OrderController {
@Post('admin/orders/:orderId/status')
@UseGuards(AdminAuthGuard)
@ApiOperation({ summary: 'Assign Order Designer ' })
updateStatus(@Param('orderId') orderId: string,@AdminId()adminId:string, @Body() dto: UpdateStatusDto) {
return this.orderService.updateStatus(orderId,adminId, dto);
updateStatus(
@Param('orderId') orderId: string,
@AdminId() adminId: string,
@AdminPerms() permissions: string[],
@Body() dto: UpdateStatusDto,
) {
return this.orderService.updateStatus(orderId, adminId, permissions, dto);
}
+16 -22
View File
@@ -158,10 +158,11 @@ export class OrderService {
})
}
async findOrdersAsAdmin(adminId: string, dto: FindOrdersDto): Promise<PaginatedResult<Order>> {
const permissions = await this.adminService.ownedPermissions(adminId,
[PermissionEnum.VIEW_ORDERS, PermissionEnum.VIEW_ASSIGNED_ORDERS])
async findOrdersAsAdmin(
adminId: string,
permissions: string[],
dto: FindOrdersDto,
): Promise<PaginatedResult<Order>> {
if (permissions.includes(PermissionEnum.VIEW_ORDERS)) {
return this.orderRepository.findAllPaginated(dto)
@@ -179,12 +180,11 @@ export class OrderService {
}
}
async getAdminOrderTabCounts(adminId: string, dto: FindOrdersDto): Promise<AdminOrderTabCounts> {
const permissions = await this.adminService.ownedPermissions(adminId, [
PermissionEnum.VIEW_ORDERS,
PermissionEnum.VIEW_ASSIGNED_ORDERS,
]);
async getAdminOrderTabCounts(
adminId: string,
permissions: string[],
dto: FindOrdersDto,
): Promise<AdminOrderTabCounts> {
const canViewAnyOrder = permissions.includes(PermissionEnum.VIEW_ORDERS);
const canViewAssignedOrder = permissions.includes(PermissionEnum.VIEW_ASSIGNED_ORDERS);
@@ -300,18 +300,12 @@ export class OrderService {
async updateStatus(orderId: string, adminId: string, dto: UpdateStatusDto): Promise<Order> {
const statusPermissions = [
PermissionEnum.CHANGE_ORDER_STATUS_FROM_ANY_TO_ANY,
PermissionEnum.CHANGE_ORDER_STATUS_TO_CANCELLED,
PermissionEnum.CHANGE_ORDER_STATUS_IN_PROGRESS,
PermissionEnum.CHANGE_ORDER_STATUS_FROM_IN_PROGRESS_TO_FINISHED,
PermissionEnum.CHANGE_ORDER_STATUS_FROM_FINISHED_TO_INVOICED,
];
const permissions = await this.adminService.ownedPermissions(adminId,
[PermissionEnum.VIEW_ORDERS, PermissionEnum.VIEW_ASSIGNED_ORDERS, ...statusPermissions]);
async updateStatus(
orderId: string,
adminId: string,
permissions: string[],
dto: UpdateStatusDto,
): Promise<Order> {
const canViewAnyOrder = permissions.includes(PermissionEnum.VIEW_ORDERS);
const canViewAssignedOrder = permissions.includes(PermissionEnum.VIEW_ASSIGNED_ORDERS);
@@ -50,6 +50,7 @@ export class ProductController {
@ApiQuery({ name: 'orderBy', required: false, type: String })
@ApiQuery({ name: 'order', required: false, enum: ['asc', 'desc'] })
@ApiQuery({ name: 'isActive', required: false, type: Boolean })
@ApiQuery({ name: 'parentId', required: false, type: String, description: 'Parent category id, or "null" for roots' })
async findAllCategories(@Query() dto: FindCategoriesDto) {
const result = await this.categoryService.findAll(dto);
return result;
@@ -36,4 +36,12 @@ export class FindCategoriesDto {
@Type(() => Boolean)
@ApiPropertyOptional({ example: true })
isActive?: boolean;
@IsOptional()
@IsString()
@ApiPropertyOptional({
description: 'Filter by parent category id. Use "null" for root categories only.',
example: 'null',
})
parentId?: string;
}
@@ -11,6 +11,7 @@ type FindCategoriesOpts = {
orderBy?: string;
order?: 'asc' | 'desc';
isActive?: boolean;
parentId?: string;
};
export type CategoryTreeNode = {
@@ -73,7 +74,7 @@ export class CategoryRepository extends EntityRepository<Category> {
}
async findAllPaginated(opts: FindCategoriesOpts = {}): Promise<PaginatedResult<Category>> {
const { page = 1, limit = 10, search, orderBy = 'createdAt', order = 'desc', isActive } = opts;
const { page = 1, limit = 10, search, orderBy = 'order', order = 'asc', isActive, parentId } = opts;
const offset = (page - 1) * limit;
@@ -83,6 +84,12 @@ export class CategoryRepository extends EntityRepository<Category> {
where.isActive = isActive;
}
if (parentId === 'null') {
where.parent = null;
} else if (parentId) {
where.parent = parentId;
}
if (search) {
where.$or = [
{ title: { $ilike: `%${search}%` } },
@@ -91,7 +98,7 @@ export class CategoryRepository extends EntityRepository<Category> {
const allCategories = await this.find(where, {
orderBy: { [orderBy]: order.toLowerCase() as 'asc' | 'desc' },
populate: ['parent'],
populate: ['parent', 'children'],
});
const total = allCategories.length;
@@ -21,7 +21,7 @@ export class ProductRepository extends EntityRepository<Product> {
}
async findAllPaginated(opts: FindproductsOpts = {}): Promise<PaginatedResult<Product>> {
const { page = 1, limit = 10, search, orderBy = 'createdAt', order = 'desc', categoryId, isActive } = opts;
const { page = 1, limit = 10, search, orderBy = 'order', order = 'asc', categoryId, isActive } = opts;
const offset = (page - 1) * limit;
@@ -39,9 +39,9 @@ export class UsersController {
return user;
}
@Get('public/dashboard/counts')
@Get('public/menu/counts')
@UseGuards(AuthGuard)
@ApiOperation({ summary: 'Get dashboard entity counts for user panel' })
@ApiOperation({ summary: 'Get metrics for user panel' })
getDashboardCounts(@UserId() userId: string) {
return this.userService.getDashboardCounts(userId);
}
+2 -1
View File
@@ -13,6 +13,7 @@ import { Request } from 'src/modules/request/entities/request.entity';
import { Invoice } from 'src/modules/invoice/entities/invoice.entity';
import { Order } from 'src/modules/order/entities/order.entity';
import { Payment } from 'src/modules/payment/entities/payment.entity';
import { InvoiceConfirmStatusEnum } from 'src/modules/invoice/enum/invoice-confirm-status.enum';
@Injectable()
export class UserService {
@@ -125,7 +126,7 @@ export class UserService {
async getDashboardCounts(userId: string) {
const [requestsCount, invoicesCount, ordersCount, paymentsCount] = await Promise.all([
this.em.count(Request, { user: { id: userId } }),
this.em.count(Invoice, { user: { id: userId } }),
this.em.count(Invoice, { user: { id: userId }, status: { $nin: [InvoiceConfirmStatusEnum.ARCHIVED] } }),
this.em.count(Order, { user: { id: userId } }),
this.em.count(Payment, { invoice: { user: { id: userId } } }),
]);
+6 -6
View File
@@ -13,13 +13,13 @@ export const adminsData: AdminData[] = [
roleName: 'admin',
},
{
phone: '09121724095',
firstName: 'آقای',
lastName: 'نواعتقاد',
roleName: 'admin',
// {
// phone: '09121724095',
// firstName: 'آقای',
// lastName: 'نواعتقاد',
// roleName: 'admin',
},
// },
// {
// phone: '09185290775',
// firstName: 'حمید',