This commit is contained in:
SepehrYahyaee
2026-07-11 17:51:14 +03:30
parent 0dcb2cf2ca
commit a7fe04c032
15 changed files with 581 additions and 8 deletions

View File

@@ -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;
}
}