acc_invoices: роль admin и переключатель роли CFO/accountant/employee; Keycloak: фирменный стиль KH Build
All checks were successful
ci / test (push) Successful in 55s
ci / deploy (push) Successful in 3m13s

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-04 14:36:45 +03:00
parent d79ebfda10
commit b878aa72bb
9 changed files with 126 additions and 15 deletions

View File

@@ -0,0 +1,19 @@
import { describe, expect, it } from "vitest";
import { effectiveRoles } from "./auth.js";
describe("effectiveRoles", () => {
it("CFO по умолчанию CFO и может переключаться", () => {
expect(effectiveRoles(["cfo"])).toEqual({ roles: ["cfo"], canSwitch: true, acting: "cfo" });
expect(effectiveRoles(["cfo"], "employee")).toEqual({ roles: [], canSwitch: true, acting: "employee" });
expect(effectiveRoles(["cfo"], "accountant").roles).toEqual(["accountant"]);
});
it("admin по умолчанию employee и может стать кем угодно", () => {
expect(effectiveRoles(["admin"])).toEqual({ roles: [], canSwitch: true, acting: "employee" });
expect(effectiveRoles(["admin"], "cfo").roles).toEqual(["cfo"]);
expect(effectiveRoles(["admin"], "bogus").acting).toBe("employee");
});
it("бухгалтер и сотрудник переключаться не могут", () => {
expect(effectiveRoles(["accountant"], "cfo")).toEqual({ roles: ["accountant"], canSwitch: false, acting: "accountant" });
expect(effectiveRoles([], "cfo")).toEqual({ roles: [], canSwitch: false, acting: "employee" });
});
});

View File

@@ -10,10 +10,19 @@ export class AuthError extends Error {
}
export type Role = "accountant" | "cfo";
/** Роль для переключателя в интерфейсе (employee - без прав бухгалтерии). */
export type ActingRole = Role | "employee";
export const ACTING_ROLES: ActingRole[] = ["cfo", "accountant", "employee"];
export interface Actor {
personId: string;
displayName: string;
/** Действующие роли (с учётом выбранной роли у admin и CFO). */
roles: Role[];
/** Настоящие роли человека из user_roles (admin, accountant, cfo). */
realRoles: string[];
/** admin и CFO могут переключать роль (отладка и тестирование). */
canSwitch: boolean;
acting: ActingRole;
}
const safeEqual = (a: string, b: string): boolean => {
@@ -38,30 +47,41 @@ export function keycloakVerifier(issuer: string): JwtVerifier {
}
/** Роли человека: таблица user_roles, а если записей нет - person.role_code (accountant, cfo). */
export async function loadRoles(pool: Pool, personId: string): Promise<Role[]> {
export async function loadRoles(pool: Pool, personId: string): Promise<string[]> {
const r = await pool.query("select role from user_roles where person_id = $1", [personId]);
const roles = new Set<Role>(r.rows.map((x) => x.role as Role));
if (!roles.size) {
const roles = new Set<string>(r.rows.map((x) => String(x.role)));
if (![...roles].some((x) => x !== "admin")) {
const p = (await pool.query("select role_code from person where id = $1", [personId])).rows[0];
if (p?.role_code === "accountant" || p?.role_code === "cfo") roles.add(p.role_code);
}
return [...roles];
}
async function actorOf(pool: Pool, personId: string): Promise<Actor> {
/** Действующая роль: admin и CFO выбирают сами (по умолчанию CFO у CFO, employee у admin); остальным выбор недоступен. */
export function effectiveRoles(real: string[], requested?: string): { roles: Role[]; canSwitch: boolean; acting: ActingRole } {
const base = real.filter((x): x is Role => x === "accountant" || x === "cfo");
const canSwitch = real.includes("admin") || real.includes("cfo");
if (!canSwitch) return { roles: base, canSwitch, acting: base[0] ?? "employee" };
const def: ActingRole = real.includes("cfo") ? "cfo" : "employee";
const acting = (ACTING_ROLES as string[]).includes(requested ?? "") ? (requested as ActingRole) : def;
return { roles: acting === "employee" ? [] : [acting], canSwitch, acting };
}
async function actorOf(pool: Pool, personId: string, requested?: string): Promise<Actor> {
const p = (await pool.query("select id, display_name from person where id = $1 and is_active", [personId])).rows[0];
if (!p) throw new AuthError("человек не найден или неактивен", 403);
return { personId: String(p.id), displayName: String(p.display_name), roles: await loadRoles(pool, personId) };
const realRoles = await loadRoles(pool, personId);
return { personId: String(p.id), displayName: String(p.display_name), realRoles, ...effectiveRoles(realRoles, requested) };
}
/** «Заголовок Authorization -> Actor». Статический токен, затем JWT Keycloak (person по email). */
export function createAuth(pool: Pool, settings: Pick<AccInvoicesSettings, "auth">, verifyJwt?: JwtVerifier): (authorization: string | undefined) => Promise<Actor> {
export function createAuth(pool: Pool, settings: Pick<AccInvoicesSettings, "auth">, verifyJwt?: JwtVerifier): (authorization: string | undefined, actingRole?: string) => Promise<Actor> {
const verify = verifyJwt ?? (settings.auth.issuer ? keycloakVerifier(settings.auth.issuer) : undefined);
return async (authorization) => {
return async (authorization, actingRole) => {
const t = bearerToken(authorization);
if (!t) throw new AuthError("нужен заголовок Authorization: Bearer <токен>", 401);
const st = settings.auth.staticTokens.find((x) => safeEqual(t, x.token));
if (st) return actorOf(pool, st.personId);
if (st) return actorOf(pool, st.personId, actingRole);
if (!verify) throw new AuthError("токен не принят", 401);
let email: string | undefined;
try {
@@ -84,6 +104,6 @@ export function createAuth(pool: Pool, settings: Pick<AccInvoicesSettings, "auth
)
).rows[0];
if (!p) throw new AuthError(`для ${email} нет активного person: доступ запрещён`, 403);
return actorOf(pool, String(p.id));
return actorOf(pool, String(p.id), actingRole);
};
}

View File

@@ -90,7 +90,7 @@ export function buildApi(deps: ApiDeps): FastifyInstance {
return reply.code(500).send({ error: "внутренняя ошибка" });
});
const need = async (req: FastifyRequest): Promise<Actor> => authenticate(req.headers.authorization);
const need = async (req: FastifyRequest): Promise<Actor> => authenticate(req.headers.authorization, typeof req.headers["x-acting-role"] === "string" ? req.headers["x-acting-role"] : undefined);
const fail = (reply: FastifyReply, status: number, error: string) => reply.code(status).send({ error });
/** Загружает инвойс и проверяет, что он виден этому человеку (чужой выглядит как несуществующий). */
@@ -106,7 +106,7 @@ export function buildApi(deps: ApiDeps): FastifyInstance {
app.get("/api/me", async (req) => {
const a = await need(req);
return { person_id: a.personId, name: a.displayName, roles: a.roles, is_staff: isStaff(a), filters: QUICK_FILTERS };
return { person_id: a.personId, name: a.displayName, roles: a.roles, real_roles: a.realRoles, can_switch: a.canSwitch, acting_role: a.acting, is_staff: isStaff(a), filters: QUICK_FILTERS };
});
app.get("/api/lookups", async (req) => {