feat: manage expert access and merge Parsian expert seeds

Allow role-specific identities and admin account activation, support national-code-only claim experts, and remove required voice from v4/v5. Add a combined, resumable Parsian seed that preserves existing accounts and merges locations and product codes.
This commit is contained in:
SepehrYahyaee
2026-11-18 17:16:26 +03:30
parent 2cdbc35d2e
commit 83376df4ad
38 changed files with 3608 additions and 136 deletions
+41 -1
View File
@@ -183,7 +183,9 @@ export class ActorAuthService {
dbService: { findOne: (filter: any) => Promise<any> },
identifier: string,
) {
const id = identifier.trim();
const id = identifier.includes("@")
? identifier.trim().toLowerCase()
: identifier.trim();
const or: Record<string, string>[] = [{ email: id }, { username: id }];
if (/^\d{10}$/.test(id)) {
or.push({ nationalCode: id });
@@ -234,9 +236,47 @@ export class ActorAuthService {
if (!(await this.hashService.compare(pass, user.password))) {
throw new UnauthorizedException("نام کاربری یا رمز عبور اشتباه است");
}
this.assertActive(user);
return user;
}
private assertActive(actor: { isActive?: boolean }) {
// Legacy accounts have no flag and remain active.
if (actor.isActive === false)
throw new UnauthorizedException(
"حساب کاری شما غیرفعال شده است. با مدیر سامانه تماس بگیرید.",
);
}
/** Recheck persisted status so a disabled account cannot reuse an old JWT. */
async assertActorActive(payload: { role?: string; sub?: string }) {
if (
![
RoleEnum.EXPERT,
RoleEnum.DAMAGE_EXPERT,
RoleEnum.FIELD_EXPERT,
RoleEnum.FILE_MAKER,
RoleEnum.FILE_REVIEWER,
RoleEnum.CALL_CENTER,
].includes(payload?.role as RoleEnum)
)
return;
if (!payload.sub || !Types.ObjectId.isValid(payload.sub))
throw new UnauthorizedException(
"حساب کاربری معتبر نیست. دوباره وارد شوید.",
);
const actor = await this.dynamicDbController(
payload.role,
null,
payload.sub,
);
if (!actor)
throw new UnauthorizedException(
"حساب کاربری یافت نشد. دوباره وارد شوید.",
);
this.assertActive(actor);
}
/**
* Authenticates an actor from a login request body (role, username/email, password).
*/
@@ -0,0 +1,226 @@
import { ExecutionContext, UnauthorizedException } from "@nestjs/common";
import { Types } from "mongoose";
import { ActorAuthService } from "./actor.auth.service";
import { RoleEnum } from "src/Types&Enums/role.enum";
import { GlobalGuard } from "../guards/global.guard";
import { LocalActorAuthGuard } from "../guards/actor-local.guard";
import { SettingsJwtGuard } from "../guards/settings-jwt.guard";
import { AuthGuard } from "src/common/auth/guards/auth.guard";
import { ClaimAccessGuard } from "../guards/claim-access.guard";
import { ExpertInsurerService } from "src/expert-insurer/expert-insurer.service";
const roles = [
RoleEnum.EXPERT,
RoleEnum.DAMAGE_EXPERT,
RoleEnum.FIELD_EXPERT,
RoleEnum.FILE_MAKER,
RoleEnum.FILE_REVIEWER,
RoleEnum.CALL_CENTER,
];
const dbNames = [
"expertDbService",
"damageExpertDbService",
"fieldExpertDbService",
"fileMakerDbService",
"fileReviewerDbService",
"callCenterAgentDbService",
];
function setup() {
const service = new (ActorAuthService as any)() as ActorAuthService;
const actors = roles.map((role) => ({
_id: new Types.ObjectId(),
role,
email: "person@example.test",
nationalCode: "0012345678",
password: "hash:shared-password",
}));
const dbs = actors.map((actor, index) => {
const db = {
findOne: jest.fn().mockResolvedValue(actor),
findByLoginIdentifier: jest.fn().mockResolvedValue(actor),
};
(service as any)[dbNames[index]] = db;
return db;
});
(service as any).hashService = {
compare: jest.fn(async (plain, hashed) => `hash:${plain}` === hashed),
};
return { service, actors, dbs };
}
describe("expert role identities and activation", () => {
it.each(["person@example.test", "0012345678"])(
"authenticates the same %s and password in every assigned role",
async (identifier) => {
const { service, actors, dbs } = setup();
for (const [index, role] of roles.entries()) {
expect(
await service.validateActor(identifier, "shared-password", role),
).toBe(actors[index]);
expect(
dbs[index].findOne.mock.calls.length +
dbs[index].findByLoginIdentifier.mock.calls.length,
).toBe(1);
}
for (const db of dbs)
expect(
db.findOne.mock.calls.length +
db.findByLoginIdentifier.mock.calls.length,
).toBe(1);
},
);
it.each(roles)(
"blocks inactive %s login and tokens, with legacy-active and reactivation support",
async (role) => {
const { service, actors } = setup();
const actor: any = actors[roles.indexOf(role)];
const token = { role, sub: String(actor._id) };
await expect(
service.validateActor(actor.email, "shared-password", role),
).resolves.toBe(actor);
await expect(service.assertActorActive(token)).resolves.toBeUndefined();
actor.isActive = false;
await expect(
service.validateActor(actor.email, "shared-password", role),
).rejects.toThrow("غیرفعال");
await expect(service.assertActorActive(token)).rejects.toThrow("غیرفعال");
actor.isActive = true;
await expect(
service.validateActor(actor.nationalCode, "shared-password", role),
).resolves.toBe(actor);
},
);
it("disabling the maker leaves the reviewer's credentials and access intact", async () => {
const { service, actors } = setup();
(actors[3] as any).isActive = false;
await expect(
service.validateActor(
"0012345678",
"shared-password",
RoleEnum.FILE_MAKER,
),
).rejects.toThrow("غیرفعال");
await expect(
service.validateActor(
"0012345678",
"shared-password",
RoleEnum.FILE_REVIEWER,
),
).resolves.toBe(actors[4]);
await expect(
service.validateActor(
"0012345678",
"wrong-password",
RoleEnum.FILE_REVIEWER,
),
).rejects.toBeInstanceOf(UnauthorizedException);
});
it("does not resolve ordinary user, insurer or super-admin JWTs through expert storage", async () => {
const { service, dbs } = setup();
for (const role of [RoleEnum.USER, RoleEnum.COMPANY, RoleEnum.SUPER_ADMIN])
await service.assertActorActive({ role, sub: "existing-subject" });
for (const db of dbs) expect(db.findOne).not.toHaveBeenCalled();
});
it("rejects missing/deleted expert subjects", async () => {
const { service, dbs } = setup();
await expect(
service.assertActorActive({ role: RoleEnum.EXPERT, sub: "bad-id" }),
).rejects.toBeInstanceOf(UnauthorizedException);
dbs[0].findOne.mockResolvedValue(null);
await expect(
service.assertActorActive({
role: RoleEnum.EXPERT,
sub: String(new Types.ObjectId()),
}),
).rejects.toBeInstanceOf(UnauthorizedException);
});
});
describe("expert access status at every JWT entry point", () => {
it.each(["actor", "user-panel", "settings", "common", "claim"])(
"checks current account state in %s guard",
async (entry) => {
const auth = { assertActorActive: jest.fn() };
const payload = {
role: entry === "claim" ? RoleEnum.DAMAGE_EXPERT : RoleEnum.FILE_MAKER,
sub: String(new Types.ObjectId()),
};
const jwt = { verifyAsync: jest.fn().mockResolvedValue(payload) };
const guard =
entry === "actor"
? new LocalActorAuthGuard(auth as any, jwt as any)
: entry === "user-panel"
? new GlobalGuard(jwt as any, auth as any)
: entry === "settings"
? new SettingsJwtGuard(jwt as any, auth as any)
: entry === "claim"
? new ClaimAccessGuard(jwt as any, {} as any, auth as any)
: new AuthGuard(jwt as any, auth as any);
const request = {
headers: { authorization: "Bearer existing-token" },
url: "/protected",
};
const context = {
switchToHttp: () => ({ getRequest: () => request }),
} as ExecutionContext;
await expect(guard.canActivate(context)).resolves.toBe(true);
expect(auth.assertActorActive).toHaveBeenCalledWith(payload);
auth.assertActorActive.mockRejectedValue(
new UnauthorizedException("حساب کاری غیرفعال است."),
);
await expect(guard.canActivate(context)).rejects.toThrow("غیرفعال");
},
);
});
describe("older insurer expert-creation endpoints", () => {
it.each([RoleEnum.EXPERT, RoleEnum.DAMAGE_EXPERT])(
"limits duplicate checks to the selected %s role",
async (role) => {
const service = new (ExpertInsurerService as any)() as any;
const key = new Types.ObjectId();
service.getClientId = () => key;
service.assertBranchBelongsToClient = async () => ({
_id: new Types.ObjectId(),
name: "شعبه",
});
service.hashService = { hash: async () => "hash:password" };
service.sanitizeExpertResponse = (value) => ({ role: value.role });
const makeDb = () => ({
findOne: jest.fn().mockResolvedValue(null),
create: jest.fn(async (body) => body),
});
service.expertDbService = makeDb();
service.damageExpertDbService = makeDb();
const selected =
role === RoleEnum.EXPERT
? service.expertDbService
: service.damageExpertDbService;
const other =
role === RoleEnum.EXPERT
? service.damageExpertDbService
: service.expertDbService;
other.findOne.mockResolvedValue({
nationalCode: "0012345678",
email: "person@example.test",
});
await service.createExpertForInsurer(
String(key),
{
email: "person@example.test",
nationalCode: "0012345678",
password: "password",
branchId: String(new Types.ObjectId()),
firstName: "علی",
lastName: "احمدی",
},
role,
);
expect(selected.create).toHaveBeenCalledWith(
expect.objectContaining({ role, email: "person@example.test" }),
);
expect(other.findOne).not.toHaveBeenCalled();
},
);
});
+45 -14
View File
@@ -4,15 +4,17 @@ import { LocalActorAuthGuard } from "./actor-local.guard";
describe("LocalActorAuthGuard", () => {
const credentials = { username: "new-account", password: "test-password" };
let auth: { loginFromCredentials: jest.Mock };
let auth: { loginFromCredentials: jest.Mock; assertActorActive: jest.Mock };
let jwt: { verifyAsync: jest.Mock };
let guard: LocalActorAuthGuard;
const context = (request: Record<string, unknown>) =>
({ switchToHttp: () => ({ getRequest: () => request }) }) as ExecutionContext;
({
switchToHttp: () => ({ getRequest: () => request }),
}) as ExecutionContext;
beforeEach(() => {
auth = { loginFromCredentials: jest.fn() };
auth = { loginFromCredentials: jest.fn(), assertActorActive: jest.fn() };
jwt = { verifyAsync: jest.fn() };
guard = new LocalActorAuthGuard(auth as any, jwt as any);
});
@@ -38,14 +40,19 @@ describe("LocalActorAuthGuard", () => {
it("does not let a previous token bypass failed credentials or captcha", async () => {
auth.loginFromCredentials.mockRejectedValue(new UnauthorizedException());
jwt.verifyAsync.mockResolvedValue({ sub: "old-account", role: RoleEnum.EXPERT });
jwt.verifyAsync.mockResolvedValue({
sub: "old-account",
role: RoleEnum.EXPERT,
});
await expect(
guard.canActivate(context({
route: { path: "/actor/login" },
headers: { authorization: "Bearer previous-session" },
body: credentials,
})),
guard.canActivate(
context({
route: { path: "/actor/login" },
headers: { authorization: "Bearer previous-session" },
body: credentials,
}),
),
).rejects.toBeInstanceOf(UnauthorizedException);
expect(jwt.verifyAsync).not.toHaveBeenCalled();
});
@@ -58,9 +65,31 @@ describe("LocalActorAuthGuard", () => {
headers: { authorization: "Bearer current-session" },
};
await expect(guard.canActivate(context(request))).resolves.toBe(true);
expect(jwt.verifyAsync).toHaveBeenCalledWith("current-session", expect.any(Object));
expect(jwt.verifyAsync).toHaveBeenCalledWith(
"current-session",
expect.any(Object),
);
expect(auth.loginFromCredentials).not.toHaveBeenCalled();
expect(request["user"]).toBe(payload);
expect(auth.assertActorActive).toHaveBeenCalledWith(payload);
});
it("rejects a previously issued token after the account is disabled", async () => {
jwt.verifyAsync.mockResolvedValue({
sub: "expert-id",
role: RoleEnum.EXPERT,
});
auth.assertActorActive.mockRejectedValue(
new UnauthorizedException("حساب کاری شما غیرفعال شده است."),
);
const request = {
url: "/actor/profile",
headers: { authorization: "Bearer old-session" },
};
await expect(guard.canActivate(context(request))).rejects.toThrow(
"غیرفعال",
);
expect(request).not.toHaveProperty("user");
});
it("rejects protected actor routes without a token", async () => {
@@ -73,10 +102,12 @@ describe("LocalActorAuthGuard", () => {
it("rejects expired tokens on protected routes", async () => {
jwt.verifyAsync.mockRejectedValue(new Error("expired"));
await expect(
guard.canActivate(context({
url: "/actor/profile",
headers: { authorization: "Bearer expired-session" },
})),
guard.canActivate(
context({
url: "/actor/profile",
headers: { authorization: "Bearer expired-session" },
}),
),
).rejects.toBeInstanceOf(UnauthorizedException);
});
});
+3 -1
View File
@@ -55,9 +55,11 @@ export class LocalActorAuthGuard implements CanActivate {
throw new UnauthorizedException("User role is not authorized");
}
await this.actorAuthService.assertActorActive(payload);
request.user = payload;
request.identity = request.user;
} catch {
} catch (error) {
if (error instanceof UnauthorizedException) throw error;
throw new UnauthorizedException("Invalid token");
}
+3
View File
@@ -9,6 +9,7 @@ import { JwtService } from "@nestjs/jwt";
import { RoleEnum } from "src/Types&Enums/role.enum";
import { ClaimRequestManagementDbService } from "src/claim-request-management/entites/db-service/claim-request-management.db.service";
import { Types } from "mongoose";
import { ActorAuthService } from "src/auth/auth-services/actor.auth.service";
/**
* Guard that allows:
@@ -20,6 +21,7 @@ export class ClaimAccessGuard implements CanActivate {
constructor(
private readonly jwtService: JwtService,
private readonly claimDbService: ClaimRequestManagementDbService,
private readonly actorAuthService: ActorAuthService,
) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
@@ -33,6 +35,7 @@ export class ClaimAccessGuard implements CanActivate {
const payload = await this.jwtService.verifyAsync(token, {
secret: `${process.env.JWT_SECRET}`,
});
await this.actorAuthService.assertActorActive(payload);
// Allow users to pass through (they will be checked by service methods)
if (payload.role === RoleEnum.USER) {
+7 -2
View File
@@ -7,18 +7,22 @@ import {
import { JwtService } from "@nestjs/jwt";
import { Request } from "express";
import { RoleEnum } from "src/Types&Enums/role.enum";
import { ActorAuthService } from "src/auth/auth-services/actor.auth.service";
const GLOBAL_GUARD_ROLES = new Set<string>([
RoleEnum.USER,
RoleEnum.FIELD_EXPERT,
RoleEnum.REGISTRAR,
RoleEnum.FILE_MAKER,
RoleEnum.FILE_REVIEWER
RoleEnum.FILE_REVIEWER,
]);
@Injectable()
export class GlobalGuard implements CanActivate {
constructor(private readonly jwtService: JwtService) {}
constructor(
private readonly jwtService: JwtService,
private readonly actorAuthService: ActorAuthService,
) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest();
@@ -39,6 +43,7 @@ export class GlobalGuard implements CanActivate {
);
}
await this.actorAuthService.assertActorActive(payload);
request.user = payload;
request.identity = request.user;
} catch (error) {
+8 -2
View File
@@ -6,6 +6,7 @@ import {
} from "@nestjs/common";
import { JwtService } from "@nestjs/jwt";
import { Request } from "express";
import { ActorAuthService } from "src/auth/auth-services/actor.auth.service";
/**
* Verifies Bearer JWT for platform settings routes. Does not restrict by role;
@@ -13,7 +14,10 @@ import { Request } from "express";
*/
@Injectable()
export class SettingsJwtGuard implements CanActivate {
constructor(private readonly jwtService: JwtService) {}
constructor(
private readonly jwtService: JwtService,
private readonly actorAuthService: ActorAuthService,
) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest<Request>();
@@ -26,10 +30,12 @@ export class SettingsJwtGuard implements CanActivate {
const payload = await this.jwtService.verifyAsync(token, {
secret: `${process.env.JWT_SECRET}`,
});
await this.actorAuthService.assertActorActive(payload);
(request as any).user = payload;
(request as any).identity = payload;
return true;
} catch {
} catch (error) {
if (error instanceof UnauthorizedException) throw error;
throw new UnauthorizedException("Invalid token");
}
}