This commit is contained in:
+1
-1
@@ -31,9 +31,9 @@ import { cacheConfig } from './config/cache.config';
|
|||||||
ConfigModule.forRoot({ isGlobal: true, cache: true }),
|
ConfigModule.forRoot({ isGlobal: true, cache: true }),
|
||||||
CacheModule.registerAsync(cacheConfig()),
|
CacheModule.registerAsync(cacheConfig()),
|
||||||
MikroOrmModule.forRootAsync(dataBaseConfig),
|
MikroOrmModule.forRootAsync(dataBaseConfig),
|
||||||
|
AuthModule,
|
||||||
UserModule,
|
UserModule,
|
||||||
UtilsModule,
|
UtilsModule,
|
||||||
AuthModule,
|
|
||||||
UploaderModule,
|
UploaderModule,
|
||||||
AdminModule,
|
AdminModule,
|
||||||
ThrottlerModule.forRoot([
|
ThrottlerModule.forRoot([
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
export enum PermissionEnum {
|
export enum PermissionEnum {
|
||||||
|
|
||||||
|
DASHBOARD = 'dashboard',
|
||||||
|
|
||||||
MANAGE_PRODUCTS = 'manage_products',
|
MANAGE_PRODUCTS = 'manage_products',
|
||||||
MANAGE_CATEGORIES = 'manage_categories',
|
MANAGE_CATEGORIES = 'manage_categories',
|
||||||
|
|
||||||
@@ -60,6 +62,7 @@ export enum PermissionEnum {
|
|||||||
|
|
||||||
|
|
||||||
export const PermissionTitles: Record<PermissionEnum, string> = {
|
export const PermissionTitles: Record<PermissionEnum, string> = {
|
||||||
|
[PermissionEnum.DASHBOARD]: 'مشاهده داشبورد',
|
||||||
[PermissionEnum.MANAGE_PRODUCTS]: 'مدیریت محصولات',
|
[PermissionEnum.MANAGE_PRODUCTS]: 'مدیریت محصولات',
|
||||||
[PermissionEnum.MANAGE_CATEGORIES]: 'مدیریت دستهبندیها',
|
[PermissionEnum.MANAGE_CATEGORIES]: 'مدیریت دستهبندیها',
|
||||||
|
|
||||||
|
|||||||
@@ -58,12 +58,14 @@ export class AdminController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Get('admin/home/stats')
|
@Get('admin/home/stats')
|
||||||
|
@Permissions(PermissionEnum.DASHBOARD)
|
||||||
@ApiOperation({ summary: 'Get home page stats for admin panel' })
|
@ApiOperation({ summary: 'Get home page stats for admin panel' })
|
||||||
getHomeStats() {
|
getHomeStats() {
|
||||||
return this.adminService.getHomeStats();
|
return this.adminService.getHomeStats();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get('admin/home/weekly-orders')
|
@Get('admin/home/weekly-orders')
|
||||||
|
@Permissions(PermissionEnum.DASHBOARD)
|
||||||
@ApiOperation({ summary: 'Get weekly order counts for admin home page chart' })
|
@ApiOperation({ summary: 'Get weekly order counts for admin home page chart' })
|
||||||
getWeeklyOrders() {
|
getWeeklyOrders() {
|
||||||
return this.adminService.getWeeklyOrders();
|
return this.adminService.getWeeklyOrders();
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { Module, forwardRef } from '@nestjs/common';
|
import { Global, Module, forwardRef } from '@nestjs/common';
|
||||||
import { AuthService } from './services/auth.service';
|
import { AuthService } from './services/auth.service';
|
||||||
import { AuthController } from './controllers/auth.controller';
|
import { AuthController } from './controllers/auth.controller';
|
||||||
import { UtilsModule } from '../util/utils.module';
|
import { UtilsModule } from '../util/utils.module';
|
||||||
@@ -13,6 +13,7 @@ import { RefreshToken } from './entities/refresh-token.entity';
|
|||||||
import { NotificationsModule } from '../notification/notifications.module';
|
import { NotificationsModule } from '../notification/notifications.module';
|
||||||
import { OtpService } from './services/otp.service';
|
import { OtpService } from './services/otp.service';
|
||||||
|
|
||||||
|
@Global()
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
UtilsModule,
|
UtilsModule,
|
||||||
@@ -38,6 +39,6 @@ import { OtpService } from './services/otp.service';
|
|||||||
],
|
],
|
||||||
controllers: [AuthController],
|
controllers: [AuthController],
|
||||||
providers: [AuthService, TokensService, AdminAuthGuard, OtpService],
|
providers: [AuthService, TokensService, AdminAuthGuard, OtpService],
|
||||||
exports: [AdminAuthGuard],
|
exports: [AdminAuthGuard, AuthService],
|
||||||
})
|
})
|
||||||
export class AuthModule { }
|
export class AuthModule { }
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ import { JwtService } from '@nestjs/jwt';
|
|||||||
import { ConfigService } from '@nestjs/config';
|
import { ConfigService } from '@nestjs/config';
|
||||||
import { IAdminTokenPayload } from '../interfaces/IToken-payload';
|
import { IAdminTokenPayload } from '../interfaces/IToken-payload';
|
||||||
import { PERMISSIONS_KEY } from '../../../common/decorators/permissions.decorator';
|
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 {
|
export interface AdminAuthRequest extends Request {
|
||||||
adminId: string;
|
adminId: string;
|
||||||
@@ -28,7 +28,7 @@ export class AdminAuthGuard implements CanActivate {
|
|||||||
private readonly jwtService: JwtService,
|
private readonly jwtService: JwtService,
|
||||||
@Inject(ConfigService)
|
@Inject(ConfigService)
|
||||||
private readonly configService: ConfigService,
|
private readonly configService: ConfigService,
|
||||||
private readonly permissionsService: PermissionService,
|
private readonly authService: AuthService,
|
||||||
private readonly reflector: Reflector,
|
private readonly reflector: Reflector,
|
||||||
) { }
|
) { }
|
||||||
|
|
||||||
@@ -69,26 +69,19 @@ export class AdminAuthGuard implements CanActivate {
|
|||||||
if (!requiredPermissions || requiredPermissions.length === 0) {
|
if (!requiredPermissions || requiredPermissions.length === 0) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
//TODO : admin permissions must get it from cache
|
|
||||||
// const adminPermission = (await this.permissionsService.getAdminPermissions(payload.adminId))
|
|
||||||
|
|
||||||
// if (!adminPermission || !Array.isArray(adminPermission)) {
|
const adminPermissions = await this.authService.getAdminPermissionsFromCache(payload.adminId)
|
||||||
// this.logger.error('No permissions found', { adminId: payload.adminId });
|
|
||||||
// throw new ForbiddenException('No permissions found');
|
const hasPermission = requiredPermissions.every(p => adminPermissions.includes(p));
|
||||||
// }
|
|
||||||
|
|
||||||
// const adminPermissionNames = adminPermission.map(p => p.name)
|
if (!hasPermission) {
|
||||||
|
this.logger.warn('Insufficient permissions', {
|
||||||
// const hasPermission = requiredPermissions.every(p => adminPermissionNames.includes(p));
|
adminId: payload.adminId,
|
||||||
|
required: requiredPermissions,
|
||||||
// if (!hasPermission) {
|
has: hasPermission,
|
||||||
// this.logger.warn('Insufficient permissions', {
|
});
|
||||||
// adminId: payload.adminId,
|
throw new ForbiddenException('You are not authorized to access this resource');
|
||||||
// required: requiredPermissions,
|
}
|
||||||
// has: adminPermission,
|
|
||||||
// });
|
|
||||||
// throw new ForbiddenException('You are not authorized to access this resource');
|
|
||||||
// }
|
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
|||||||
@@ -10,10 +10,12 @@ import { AdminLoginTransformer } from '../transformers/admin-login.transformer';
|
|||||||
import { UserLoginTransformer } from '../transformers/user-login.transformer';
|
import { UserLoginTransformer } from '../transformers/user-login.transformer';
|
||||||
import { OtpService } from './otp.service';
|
import { OtpService } from './otp.service';
|
||||||
import { normalizePhoneToLocal } from 'src/modules/util/phone.util';
|
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()
|
@Injectable()
|
||||||
export class AuthService {
|
export class AuthService {
|
||||||
readonly ADMIN_PERMISSIONS_KEY = 'admin-perms';
|
readonly ADMIN_PERMISSIONS_EXPIRATION_TIME = 1800;
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private readonly smsService: SmsService,
|
private readonly smsService: SmsService,
|
||||||
@@ -21,8 +23,10 @@ export class AuthService {
|
|||||||
private readonly tokensService: TokensService,
|
private readonly tokensService: TokensService,
|
||||||
private readonly adminRepository: AdminRepository,
|
private readonly adminRepository: AdminRepository,
|
||||||
private readonly otpService: OtpService,
|
private readonly otpService: OtpService,
|
||||||
|
private readonly cacheService: CacheService,
|
||||||
|
private readonly permissionService: PermissionService,
|
||||||
) {
|
) {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async requestOtp(dto: RequestOtpDto, isAdmin: boolean) {
|
async requestOtp(dto: RequestOtpDto, isAdmin: boolean) {
|
||||||
@@ -33,9 +37,9 @@ export class AuthService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const code = this.generateOtpCode();
|
const code = this.generateOtpCode();
|
||||||
|
|
||||||
await this.otpService.set(phone, code)
|
await this.otpService.set(phone, code)
|
||||||
|
|
||||||
// await this.smsService.sendotp(phone, code);
|
// await this.smsService.sendotp(phone, code);
|
||||||
|
|
||||||
return { code };
|
return { code };
|
||||||
@@ -82,6 +86,10 @@ export class AuthService {
|
|||||||
|
|
||||||
const tokens = await this.tokensService.generateAccessAndRefreshToken(admin.id, true);
|
const tokens = await this.tokensService.generateAccessAndRefreshToken(admin.id, true);
|
||||||
|
|
||||||
|
const permissionNames = admin.role.permissions.map(p => p.name);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
const adminResponse = await AdminLoginTransformer.transform(admin);
|
const adminResponse = await AdminLoginTransformer.transform(admin);
|
||||||
|
|
||||||
return { tokens, admin: adminResponse };
|
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`;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -13,13 +13,13 @@ export const adminsData: AdminData[] = [
|
|||||||
roleName: 'admin',
|
roleName: 'admin',
|
||||||
|
|
||||||
},
|
},
|
||||||
{
|
// {
|
||||||
phone: '09121724095',
|
// phone: '09121724095',
|
||||||
firstName: 'آقای',
|
// firstName: 'آقای',
|
||||||
lastName: 'نواعتقاد',
|
// lastName: 'نواعتقاد',
|
||||||
roleName: 'admin',
|
// roleName: 'admin',
|
||||||
|
|
||||||
},
|
// },
|
||||||
// {
|
// {
|
||||||
// phone: '09185290775',
|
// phone: '09185290775',
|
||||||
// firstName: 'حمید',
|
// firstName: 'حمید',
|
||||||
|
|||||||
Reference in New Issue
Block a user