forked from Yara724/api
YARA-986
This commit is contained in:
76
src/super-admin/dto/super-admin.dto.ts
Normal file
76
src/super-admin/dto/super-admin.dto.ts
Normal file
@@ -0,0 +1,76 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { IsEmail, IsNotEmpty, IsOptional, IsString } from "class-validator";
|
||||
|
||||
export class CreateSuperAdminDto {
|
||||
@ApiProperty({
|
||||
example: "ops@yara724.ir",
|
||||
description: "Email address for the new super-admin account.",
|
||||
})
|
||||
@IsEmail()
|
||||
email: string;
|
||||
|
||||
@ApiProperty({ example: "Str0ngP@ss!" })
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
password: string;
|
||||
|
||||
@ApiPropertyOptional({ example: "Operations" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
firstName?: string;
|
||||
|
||||
@ApiPropertyOptional({ example: "Team" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
lastName?: string;
|
||||
}
|
||||
|
||||
export class CreateFieldExpertAdminDto {
|
||||
@ApiProperty({ example: "expert@insurer.ir" })
|
||||
@IsEmail()
|
||||
email: string;
|
||||
|
||||
@ApiProperty({ example: "Expert@724" })
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
password: string;
|
||||
|
||||
@ApiProperty({ example: "Ali" })
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
firstName: string;
|
||||
|
||||
@ApiProperty({ example: "Mohammadi" })
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
lastName: string;
|
||||
|
||||
@ApiProperty({ example: "09121234567" })
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
mobile: string;
|
||||
|
||||
@ApiPropertyOptional({ example: "02112345678" })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
phone?: string;
|
||||
}
|
||||
|
||||
export class CreateRegistrarAdminDto {
|
||||
@ApiProperty({ example: "registrar@insurer.ir" })
|
||||
@IsEmail()
|
||||
email: string;
|
||||
|
||||
@ApiProperty({ example: "Registrar@724" })
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
password: string;
|
||||
|
||||
@ApiProperty({
|
||||
example: "664a1b2c3d4e5f6789012345",
|
||||
description: "Mongo ObjectId of the insurer client this registrar belongs to.",
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
clientId: string;
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import { Injectable, Logger, OnModuleInit } from "@nestjs/common";
|
||||
import { InjectModel } from "@nestjs/mongoose";
|
||||
import { FilterQuery, Model } from "mongoose";
|
||||
import { HashService } from "src/utils/hash/hash.service";
|
||||
import {
|
||||
SuperAdminModel,
|
||||
SuperAdminDocument,
|
||||
} from "../schema/super-admin.schema";
|
||||
import { RoleEnum } from "src/Types&Enums/role.enum";
|
||||
|
||||
@Injectable()
|
||||
export class SuperAdminDbService implements OnModuleInit {
|
||||
private readonly logger = new Logger(SuperAdminDbService.name);
|
||||
|
||||
constructor(
|
||||
@InjectModel(SuperAdminModel.name)
|
||||
private readonly superAdminModel: Model<SuperAdminDocument>,
|
||||
private readonly hashService: HashService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Seeds the default super-admin account on first boot.
|
||||
* Reads credentials from environment variables:
|
||||
* SUPER_ADMIN_EMAIL (default: super-admin@yara724.ir)
|
||||
* SUPER_ADMIN_PASSWORD (default: SuperAdmin@724)
|
||||
*/
|
||||
async onModuleInit() {
|
||||
const email = (
|
||||
process.env.SUPER_ADMIN_EMAIL ?? "super-admin@yara724.ir"
|
||||
).toLowerCase().trim();
|
||||
|
||||
const existing = await this.superAdminModel.findOne({ email }).lean();
|
||||
if (existing) {
|
||||
this.logger.log(`Super-admin already exists (email=${email}), skipping seed.`);
|
||||
return;
|
||||
}
|
||||
|
||||
const rawPassword = process.env.SUPER_ADMIN_PASSWORD ?? "SuperAdmin@724";
|
||||
const password = await this.hashService.hash(rawPassword);
|
||||
|
||||
await this.superAdminModel.create({
|
||||
email,
|
||||
password,
|
||||
role: RoleEnum.SUPER_ADMIN,
|
||||
firstName: "Super",
|
||||
lastName: "Admin",
|
||||
});
|
||||
|
||||
this.logger.log(`Default super-admin seeded (email=${email}).`);
|
||||
}
|
||||
|
||||
async findOne(
|
||||
filter: FilterQuery<SuperAdminDocument>,
|
||||
): Promise<SuperAdminDocument | null> {
|
||||
return this.superAdminModel.findOne(filter).lean() as any;
|
||||
}
|
||||
|
||||
async findByLoginIdentifier(identifier: string): Promise<SuperAdminDocument | null> {
|
||||
const id = identifier.trim();
|
||||
return this.superAdminModel.findOne({ email: id }).lean() as any;
|
||||
}
|
||||
|
||||
async create(data: Partial<SuperAdminModel>): Promise<SuperAdminDocument> {
|
||||
return this.superAdminModel.create(data);
|
||||
}
|
||||
|
||||
async updateOne(filter: FilterQuery<SuperAdminDocument>, update: any) {
|
||||
return this.superAdminModel.updateOne(filter, update);
|
||||
}
|
||||
|
||||
async findAll(): Promise<SuperAdminDocument[]> {
|
||||
return this.superAdminModel.find().lean() as any;
|
||||
}
|
||||
}
|
||||
30
src/super-admin/entities/schema/super-admin.schema.ts
Normal file
30
src/super-admin/entities/schema/super-admin.schema.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose";
|
||||
import { HydratedDocument } from "mongoose";
|
||||
import { RoleEnum } from "src/Types&Enums/role.enum";
|
||||
|
||||
@Schema({
|
||||
collection: "super-admins",
|
||||
versionKey: false,
|
||||
timestamps: true,
|
||||
})
|
||||
export class SuperAdminModel {
|
||||
@Prop({ required: true, unique: true, index: true })
|
||||
email: string;
|
||||
|
||||
@Prop({ required: true })
|
||||
password: string;
|
||||
|
||||
@Prop({ required: true, default: RoleEnum.SUPER_ADMIN })
|
||||
role: RoleEnum;
|
||||
|
||||
@Prop()
|
||||
firstName?: string;
|
||||
|
||||
@Prop()
|
||||
lastName?: string;
|
||||
|
||||
createdAt: Date;
|
||||
}
|
||||
|
||||
export type SuperAdminDocument = HydratedDocument<SuperAdminModel>;
|
||||
export const SuperAdminSchema = SchemaFactory.createForClass(SuperAdminModel);
|
||||
49
src/super-admin/guards/super-admin.guard.ts
Normal file
49
src/super-admin/guards/super-admin.guard.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
UnauthorizedException,
|
||||
} from "@nestjs/common";
|
||||
import { JwtService } from "@nestjs/jwt";
|
||||
import { Request } from "express";
|
||||
import { RoleEnum } from "src/Types&Enums/role.enum";
|
||||
|
||||
/**
|
||||
* Verifies a Bearer JWT and restricts access to `super_admin` role only.
|
||||
* Use this guard on all endpoints that should be reachable only by the
|
||||
* super-admin panel.
|
||||
*/
|
||||
@Injectable()
|
||||
export class SuperAdminGuard implements CanActivate {
|
||||
constructor(private readonly jwtService: JwtService) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest<Request>();
|
||||
const token = this.extractTokenFromHeader(request);
|
||||
if (!token) {
|
||||
throw new UnauthorizedException("Token not found");
|
||||
}
|
||||
|
||||
let payload: any;
|
||||
try {
|
||||
payload = await this.jwtService.verifyAsync(token, {
|
||||
secret: `${process.env.JWT_SECRET}`,
|
||||
});
|
||||
} catch {
|
||||
throw new UnauthorizedException("Invalid or expired token");
|
||||
}
|
||||
|
||||
if (payload?.role !== RoleEnum.SUPER_ADMIN) {
|
||||
throw new UnauthorizedException("Super-admin access required");
|
||||
}
|
||||
|
||||
(request as any).user = payload;
|
||||
(request as any).identity = payload;
|
||||
return true;
|
||||
}
|
||||
|
||||
private extractTokenFromHeader(request: Request): string | undefined {
|
||||
const [type, token] = request.headers.authorization?.split(" ") ?? [];
|
||||
return type === "Bearer" ? token : undefined;
|
||||
}
|
||||
}
|
||||
162
src/super-admin/super-admin.controller.ts
Normal file
162
src/super-admin/super-admin.controller.ts
Normal file
@@ -0,0 +1,162 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
Patch,
|
||||
Post,
|
||||
UseGuards,
|
||||
} from "@nestjs/common";
|
||||
import {
|
||||
ApiBearerAuth,
|
||||
ApiBody,
|
||||
ApiOperation,
|
||||
ApiResponse,
|
||||
ApiTags,
|
||||
} from "@nestjs/swagger";
|
||||
import { SuperAdminGuard } from "./guards/super-admin.guard";
|
||||
import { SuperAdminService } from "./super-admin.service";
|
||||
import {
|
||||
CreateSuperAdminDto,
|
||||
CreateFieldExpertAdminDto,
|
||||
CreateRegistrarAdminDto,
|
||||
} from "./dto/super-admin.dto";
|
||||
import { ClientDto } from "src/client/dto/create-client.dto";
|
||||
import {
|
||||
InsurerRegisterDto,
|
||||
GenuineRegisterDto,
|
||||
LegalRegisterDto,
|
||||
} from "src/auth/dto/actor/register.actor.dto";
|
||||
import { SystemSettingsService } from "src/system-settings/system-settings.service";
|
||||
import {
|
||||
SystemSettingsResponseDto,
|
||||
UpdateSystemSettingsDto,
|
||||
} from "src/system-settings/dto/system-settings.dto";
|
||||
import { SetExternalInquiriesLiveDto } from "src/client/dto/external-inquiries-live.dto";
|
||||
|
||||
@ApiTags("super-admin")
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(SuperAdminGuard)
|
||||
@Controller("super-admin")
|
||||
export class SuperAdminController {
|
||||
constructor(
|
||||
private readonly superAdminService: SuperAdminService,
|
||||
private readonly systemSettingsService: SystemSettingsService,
|
||||
) {}
|
||||
|
||||
// ── Super-admin account management ───────────────────────────────────────
|
||||
|
||||
@Get("accounts")
|
||||
@ApiOperation({ summary: "List all super-admin accounts" })
|
||||
listSuperAdmins() {
|
||||
return this.superAdminService.listSuperAdmins();
|
||||
}
|
||||
|
||||
@Post("accounts")
|
||||
@ApiOperation({ summary: "Create an additional super-admin account" })
|
||||
@ApiBody({ type: CreateSuperAdminDto })
|
||||
createSuperAdmin(@Body() body: CreateSuperAdminDto) {
|
||||
return this.superAdminService.createSuperAdmin(body);
|
||||
}
|
||||
|
||||
// ── Client / insurer management ──────────────────────────────────────────
|
||||
|
||||
@Post("clients")
|
||||
@ApiOperation({
|
||||
summary: "Create a new insurer client",
|
||||
description: "Registers a new insurer (client) in the platform.",
|
||||
})
|
||||
@ApiBody({ type: ClientDto })
|
||||
createClient(@Body() body: ClientDto) {
|
||||
return this.superAdminService.createClient(body);
|
||||
}
|
||||
|
||||
@Get("clients")
|
||||
@ApiOperation({ summary: "List all insurer clients" })
|
||||
listClients() {
|
||||
return this.superAdminService.listClients();
|
||||
}
|
||||
|
||||
@Get("clients/names")
|
||||
@ApiOperation({ summary: "List insurer client names and IDs" })
|
||||
listClientNames() {
|
||||
return this.superAdminService.listClientNames();
|
||||
}
|
||||
|
||||
// ── Actor registration ───────────────────────────────────────────────────
|
||||
|
||||
@Post("register/insurer")
|
||||
@ApiOperation({ summary: "Register a new insurer (company) actor" })
|
||||
@ApiBody({ type: InsurerRegisterDto })
|
||||
registerInsurer(@Body() body: InsurerRegisterDto) {
|
||||
return this.superAdminService.registerInsurer(body);
|
||||
}
|
||||
|
||||
@Post("register/genuine")
|
||||
@ApiOperation({
|
||||
deprecated: true,
|
||||
summary: "[DEPRECATED] Register a genuine actor",
|
||||
description:
|
||||
"Kept for legacy clients. Use the unified onboarding flow instead.",
|
||||
})
|
||||
@ApiBody({ type: GenuineRegisterDto })
|
||||
registerGenuine(@Body() body: GenuineRegisterDto) {
|
||||
return this.superAdminService.registerGenuine(body);
|
||||
}
|
||||
|
||||
@Post("register/legal")
|
||||
@ApiOperation({
|
||||
deprecated: true,
|
||||
summary: "[DEPRECATED] Register a legal actor",
|
||||
description:
|
||||
"Kept for legacy clients. Use the unified onboarding flow instead.",
|
||||
})
|
||||
@ApiBody({ type: LegalRegisterDto })
|
||||
registerLegal(@Body() body: LegalRegisterDto) {
|
||||
return this.superAdminService.registerLegal(body);
|
||||
}
|
||||
|
||||
@Post("create-field-expert")
|
||||
@ApiOperation({ summary: "Create a field expert" })
|
||||
@ApiBody({ type: CreateFieldExpertAdminDto })
|
||||
createFieldExpert(@Body() body: CreateFieldExpertAdminDto) {
|
||||
return this.superAdminService.createFieldExpert(body);
|
||||
}
|
||||
|
||||
@Post("create-registrar")
|
||||
@ApiOperation({ summary: "Create a registrar" })
|
||||
@ApiBody({ type: CreateRegistrarAdminDto })
|
||||
createRegistrar(@Body() body: CreateRegistrarAdminDto) {
|
||||
return this.superAdminService.createRegistrar(body);
|
||||
}
|
||||
|
||||
// ── System settings ──────────────────────────────────────────────────────
|
||||
|
||||
@Get("system-settings")
|
||||
@ApiOperation({ summary: "Get global system settings" })
|
||||
@ApiResponse({ status: 200, type: SystemSettingsResponseDto })
|
||||
getSystemSettings() {
|
||||
return this.systemSettingsService.getSettingsView();
|
||||
}
|
||||
|
||||
@Patch("system-settings")
|
||||
@ApiOperation({ summary: "Update global system settings" })
|
||||
@ApiBody({ type: UpdateSystemSettingsDto })
|
||||
@ApiResponse({ status: 200, type: SystemSettingsResponseDto })
|
||||
updateSystemSettings(@Body() body: UpdateSystemSettingsDto) {
|
||||
return this.systemSettingsService.updateSettings(body);
|
||||
}
|
||||
|
||||
@Patch("external-inquiries-live")
|
||||
@ApiOperation({
|
||||
summary: "Enable or disable live external inquiries globally",
|
||||
description:
|
||||
"Updates `system_settings.externalApis.sandHubUseLiveApi`. When disabled, all inquiry flows use mocks.",
|
||||
})
|
||||
@ApiBody({ type: SetExternalInquiriesLiveDto })
|
||||
@ApiResponse({ status: 200, type: SystemSettingsResponseDto })
|
||||
setExternalInquiriesLive(@Body() body: SetExternalInquiriesLiveDto) {
|
||||
return this.systemSettingsService.updateSettings({
|
||||
externalApis: { sandHubUseLiveApi: body?.enabled === true },
|
||||
});
|
||||
}
|
||||
}
|
||||
34
src/super-admin/super-admin.module.ts
Normal file
34
src/super-admin/super-admin.module.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import { Module } from "@nestjs/common";
|
||||
import { ClientModule } from "src/client/client.module";
|
||||
import { SystemSettingsModule } from "src/system-settings/system-settings.module";
|
||||
import { HashModule } from "src/utils/hash/hash.module";
|
||||
import { UsersModule } from "src/users/users.module";
|
||||
import { SuperAdminController } from "./super-admin.controller";
|
||||
import { SuperAdminService } from "./super-admin.service";
|
||||
import { SuperAdminGuard } from "./guards/super-admin.guard";
|
||||
|
||||
/**
|
||||
* Super-admin feature module.
|
||||
*
|
||||
* The `SuperAdminDbService` and its Mongoose model are registered in `AuthModule`
|
||||
* (which is `@Global()`) to keep login routing central. This module only needs
|
||||
* to import the other feature modules it proxies.
|
||||
*
|
||||
* Dependency chain:
|
||||
* SuperAdminGuard ← JwtService (global via AuthModule JwtModule)
|
||||
* SuperAdminService ← ActorAuthService (global), ClientService (ClientModule),
|
||||
* SuperAdminDbService (global via AuthModule),
|
||||
* FieldExpertDbService + RegistrarDbService (UsersModule)
|
||||
*/
|
||||
@Module({
|
||||
imports: [
|
||||
ClientModule,
|
||||
SystemSettingsModule,
|
||||
HashModule,
|
||||
UsersModule,
|
||||
],
|
||||
controllers: [SuperAdminController],
|
||||
providers: [SuperAdminService, SuperAdminGuard],
|
||||
exports: [SuperAdminService, SuperAdminGuard],
|
||||
})
|
||||
export class SuperAdminModule {}
|
||||
102
src/super-admin/super-admin.service.ts
Normal file
102
src/super-admin/super-admin.service.ts
Normal file
@@ -0,0 +1,102 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from "@nestjs/common";
|
||||
import { Types } from "mongoose";
|
||||
import { HashService } from "src/utils/hash/hash.service";
|
||||
import { ClientService } from "src/client/client.service";
|
||||
import { ClientDto } from "src/client/dto/create-client.dto";
|
||||
import { ActorAuthService } from "src/auth/auth-services/actor.auth.service";
|
||||
import {
|
||||
InsurerRegisterDto,
|
||||
GenuineRegisterDto,
|
||||
LegalRegisterDto,
|
||||
} from "src/auth/dto/actor/register.actor.dto";
|
||||
import { SuperAdminDbService } from "./entities/db-service/super-admin.db.service";
|
||||
import {
|
||||
CreateSuperAdminDto,
|
||||
CreateFieldExpertAdminDto,
|
||||
CreateRegistrarAdminDto,
|
||||
} from "./dto/super-admin.dto";
|
||||
import { RoleEnum } from "src/Types&Enums/role.enum";
|
||||
import { FieldExpertDbService } from "src/users/entities/db-service/field-expert.db.service";
|
||||
import { RegistrarDbService } from "src/users/entities/db-service/registrar.db.service";
|
||||
|
||||
@Injectable()
|
||||
export class SuperAdminService {
|
||||
constructor(
|
||||
private readonly superAdminDbService: SuperAdminDbService,
|
||||
private readonly hashService: HashService,
|
||||
private readonly clientService: ClientService,
|
||||
private readonly actorAuthService: ActorAuthService,
|
||||
private readonly fieldExpertDbService: FieldExpertDbService,
|
||||
private readonly registrarDbService: RegistrarDbService,
|
||||
) {}
|
||||
|
||||
/** List all super-admin accounts (sans password). */
|
||||
async listSuperAdmins() {
|
||||
const admins = await this.superAdminDbService.findAll();
|
||||
return admins.map(({ password: _pw, ...rest }) => rest);
|
||||
}
|
||||
|
||||
/** Create an additional super-admin account. */
|
||||
async createSuperAdmin(body: CreateSuperAdminDto) {
|
||||
const email = body.email.toLowerCase().trim();
|
||||
const existing = await this.superAdminDbService.findOne({ email });
|
||||
if (existing) {
|
||||
throw new ConflictException(
|
||||
"A super-admin with this email already exists.",
|
||||
);
|
||||
}
|
||||
const password = await this.hashService.hash(body.password);
|
||||
const created = await this.superAdminDbService.create({
|
||||
email,
|
||||
password,
|
||||
role: RoleEnum.SUPER_ADMIN,
|
||||
firstName: body.firstName,
|
||||
lastName: body.lastName,
|
||||
});
|
||||
const { password: _pw, ...rest } = (created as any).toObject
|
||||
? (created as any).toObject()
|
||||
: (created as any);
|
||||
return rest;
|
||||
}
|
||||
|
||||
// ── Client management ────────────────────────────────────────────────────
|
||||
|
||||
async createClient(body: ClientDto) {
|
||||
return this.clientService.addClient(body);
|
||||
}
|
||||
|
||||
async listClients() {
|
||||
return this.clientService.getClients();
|
||||
}
|
||||
|
||||
async listClientNames() {
|
||||
return this.clientService.getClientList();
|
||||
}
|
||||
|
||||
// ── Actor registration proxies ───────────────────────────────────────────
|
||||
|
||||
async registerInsurer(body: InsurerRegisterDto) {
|
||||
return this.actorAuthService.insurerRegister(body);
|
||||
}
|
||||
|
||||
async registerGenuine(body: GenuineRegisterDto) {
|
||||
return this.actorAuthService.genuineRegister(body);
|
||||
}
|
||||
|
||||
async registerLegal(body: LegalRegisterDto) {
|
||||
return this.actorAuthService.legalRegister(body);
|
||||
}
|
||||
|
||||
async createFieldExpert(body: CreateFieldExpertAdminDto) {
|
||||
return this.actorAuthService.createFieldExpertMock(body);
|
||||
}
|
||||
|
||||
async createRegistrar(body: CreateRegistrarAdminDto) {
|
||||
return this.actorAuthService.createRegistrarMock(body);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user