acc_invoices: роль admin и переключатель роли CFO/accountant/employee; Keycloak: фирменный стиль KH Build
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
19
packages/acc_invoices/src/auth.test.ts
Normal file
19
packages/acc_invoices/src/auth.test.ts
Normal 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" });
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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) => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import * as Ariakit from "@ariakit/react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { ApiError, api, getToken, type Detail, type Line, type Lookups, type Me, type Row } from "./api.js";
|
||||
import { ApiError, api, getActing, getToken, setActing, type Detail, type Line, type Lookups, type Me, type Row } from "./api.js";
|
||||
import { FormDialog } from "./FormDialog.js";
|
||||
import { Login } from "./Login.js";
|
||||
import { finishLogin, logout, relogin } from "./oidc.js";
|
||||
@@ -105,7 +105,15 @@ function Main({ me, onLogout }: { me: Me; onLogout: () => void }) {
|
||||
</Ariakit.TabList>
|
||||
<input className="search" type="search" placeholder="Поиск: вендор, номер, проект, сумма" value={q} onChange={(e) => setQ(e.target.value)} aria-label="Поиск" />
|
||||
<span className="spacer" />
|
||||
<span className="who" title={me.roles.join(", ") || "сотрудник"}>{me.name}</span>
|
||||
<span className="who" title={"роли: " + (me.real_roles.join(", ") || "сотрудник")}>{me.name}</span>
|
||||
{me.can_switch && (
|
||||
<select className="role-switch" aria-label="Роль для отладки и тестирования" title="Роль (отладка и тестирование)" value={me.acting_role}
|
||||
onChange={(e) => { setActing(e.target.value); location.reload(); }}>
|
||||
<option value="cfo">CFO</option>
|
||||
<option value="accountant">accountant</option>
|
||||
<option value="employee">employee</option>
|
||||
</select>
|
||||
)}
|
||||
<button className="btn" onClick={onLogout}>Выйти</button>
|
||||
<button className="btn primary" disabled={!lookups} onClick={() => openForm(null, [])}>Create</button>
|
||||
</Ariakit.Toolbar>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
export interface Me { person_id: string; name: string; roles: string[]; is_staff: boolean; filters: { key: string; label: string }[] }
|
||||
export interface Me { person_id: string; name: string; roles: string[]; real_roles: string[]; can_switch: boolean; acting_role: string; is_staff: boolean; filters: { key: string; label: string }[] }
|
||||
export interface Row {
|
||||
id: string; invoice_number: string | null; vendor_name: string; vendor_qbo_id: string | null; invoice_date: string | null; amount: number;
|
||||
project_customer_id: string | null; project_name: string | null; contract_id: string | null; pay_method: string | null;
|
||||
@@ -20,6 +20,9 @@ export interface Lookups { projects: Named[]; vendors: Named[]; people: Named[];
|
||||
|
||||
import { freshToken, hasSession } from "./oidc.js";
|
||||
export const getToken = (): string => (hasSession() ? "1" : "");
|
||||
const AK = "acc_invoices_acting_role";
|
||||
export const getActing = (): string => { try { return sessionStorage.getItem(AK) ?? ""; } catch { return ""; } };
|
||||
export const setActing = (r: string): void => { try { sessionStorage.setItem(AK, r); } catch { /* ignore */ } };
|
||||
|
||||
export class ApiError extends Error {
|
||||
constructor(message: string, readonly status: number, readonly problems?: string[]) { super(message); }
|
||||
@@ -29,7 +32,7 @@ export class ApiError extends Error {
|
||||
export async function api<T = unknown>(path: string, init: { method?: string; body?: unknown } = {}): Promise<T> {
|
||||
const r = await fetch(`api/${path}`, {
|
||||
method: init.method ?? "GET",
|
||||
headers: { Authorization: `Bearer ${await freshToken()}`, ...(init.body !== undefined ? { "content-type": "application/json" } : {}) },
|
||||
headers: { Authorization: `Bearer ${await freshToken()}`, ...(getActing() ? { "x-acting-role": getActing() } : {}), ...(init.body !== undefined ? { "content-type": "application/json" } : {}) },
|
||||
body: init.body !== undefined ? JSON.stringify(init.body) : undefined,
|
||||
});
|
||||
const text = await r.text();
|
||||
|
||||
@@ -23,6 +23,7 @@ body { margin: 0; background: var(--bg); color: var(--text); font: 14px/1.4 syst
|
||||
.search { min-width: 240px; padding: 6px 10px; border: 1px solid var(--line); border-radius: 8px; background: var(--panel); color: var(--text); }
|
||||
.spacer { flex: 1; }
|
||||
.who { color: var(--muted); }
|
||||
.role-switch { padding: 5px 8px; border: 1px solid var(--accent); border-radius: 8px; background: var(--panel); color: var(--text); font: inherit; }
|
||||
|
||||
.btn { border: 1px solid var(--line); background: var(--panel); color: var(--text); padding: 6px 14px; border-radius: 8px; cursor: pointer; font: inherit; text-decoration: none; display: inline-block; }
|
||||
.btn:hover:not(:disabled) { border-color: var(--accent); }
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
-- acc_invoices: роль admin (отладка и тестирование: может переключаться между CFO, accountant и employee)
|
||||
alter table user_roles drop constraint if exists user_roles_role_check;
|
||||
alter table user_roles add constraint user_roles_role_check check (role in ('accountant', 'cfo', 'admin'));
|
||||
insert into user_roles (person_id, role)
|
||||
select id, 'admin' from person where lower(email) in ('yuri@khbuild.pro', 'dmitry@khbuild.pro')
|
||||
on conflict do nothing;
|
||||
Reference in New Issue
Block a user