forked from Yara724/api
75 lines
2.3 KiB
TypeScript
75 lines
2.3 KiB
TypeScript
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;
|
|
}
|
|
}
|