mirror of
https://github.com/temetro/temetro.git
synced 2026-08-13 03:56:53 +00:00
feat: admin-provisioned staff, username login & role-based access
Replace the email-invitation flow with admin-provisioned staff accounts and
add role-based access that changes what each member sees.
Backend:
- Enable Better Auth `username` plugin (staff sign in by username); regenerate
auth schema (+ username/displayUsername on user) and migration 0007.
- Add `doctor` and `reception` roles to the access-control RBAC. `reception` is
scoped to scheduling + registration (no `prescription` statement).
- New `/api/staff` route: POST creates a user (auth.api.signUpEmail) and adds
them to the active clinic (auth.api.addMember); GET lists members + usernames.
Gated by requirePermission({ member: ["create"] }).
- Redact clinical PHI for the reception role in the patients service (read,
create and update) so demographics-only is enforced server-side.
Frontend:
- usernameClient + Email|Username tabs on the login form.
- lib/roles.ts: useActiveRole + Better-Auth-permission-driven nav visibility,
default landing, and a route guard (reception -> /appointments, blocked from
clinical routes). Applied to the sidebar, command palette and auth guard.
- Care team page now provisions staff via a two-step Add-team-member dialog
(details -> username/password) hitting /api/staff; removes the email-invite
and pending-invitation UI. New members are contactable from Messages
automatically (they become org members).
- Hide clinical sections of the patient form and the admin-only settings tabs
for non-clinical/non-admin roles.
All permission management stays in Better Auth (per the better-auth skills now
referenced in backend/CLAUDE.md).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
import { betterAuth } from "better-auth";
|
||||
import { drizzleAdapter } from "better-auth/adapters/drizzle";
|
||||
import { organization } from "better-auth/plugins";
|
||||
import { username } from "better-auth/plugins/username";
|
||||
import { eq } from "drizzle-orm";
|
||||
|
||||
import { db } from "./db/index.js";
|
||||
@@ -55,6 +56,13 @@ export const auth = betterAuth({
|
||||
},
|
||||
|
||||
plugins: [
|
||||
// Lets staff sign in with a username (in addition to email). Admin-created
|
||||
// staff accounts (see src/routes/staff.ts) set a username + password the
|
||||
// employee uses to log in. Adds `username` + `displayUsername` to `user`.
|
||||
username({
|
||||
minUsernameLength: 3,
|
||||
maxUsernameLength: 32,
|
||||
}),
|
||||
organization({
|
||||
ac,
|
||||
roles,
|
||||
|
||||
@@ -21,6 +21,8 @@ export const user = pgTable("user", {
|
||||
.defaultNow()
|
||||
.$onUpdate(() => /* @__PURE__ */ new Date())
|
||||
.notNull(),
|
||||
username: text("username").unique(),
|
||||
displayUsername: text("display_username"),
|
||||
});
|
||||
|
||||
export const session = pgTable(
|
||||
|
||||
@@ -16,6 +16,7 @@ import { notesRouter } from "./routes/notes.js";
|
||||
import { notificationsRouter } from "./routes/notifications.js";
|
||||
import { patientsRouter } from "./routes/patients.js";
|
||||
import { prescriptionsRouter } from "./routes/prescriptions.js";
|
||||
import { staffRouter } from "./routes/staff.js";
|
||||
import { tasksRouter } from "./routes/tasks.js";
|
||||
|
||||
const app = express();
|
||||
@@ -58,6 +59,7 @@ app.use("/api/notes", notesRouter);
|
||||
app.use("/api/appointments", appointmentsRouter);
|
||||
app.use("/api/prescriptions", prescriptionsRouter);
|
||||
app.use("/api/tasks", tasksRouter);
|
||||
app.use("/api/staff", staffRouter);
|
||||
app.use("/api/activity", activityRouter);
|
||||
app.use("/api/analytics", analyticsRouter);
|
||||
app.use("/api/conversations", conversationsRouter);
|
||||
@@ -78,6 +80,7 @@ server.listen(env.PORT, () => {
|
||||
console.log(` • appts: /api/appointments`);
|
||||
console.log(` • rx: /api/prescriptions`);
|
||||
console.log(` • tasks: /api/tasks`);
|
||||
console.log(` • staff: /api/staff`);
|
||||
console.log(` • activity: /api/activity`);
|
||||
console.log(` • stats: /api/analytics`);
|
||||
console.log(` • messages: /api/conversations (+ Socket.io)`);
|
||||
|
||||
@@ -51,6 +51,29 @@ export const member = ac.newRole({
|
||||
task: ["read", "write", "delete"],
|
||||
});
|
||||
|
||||
// doctor (clinician): same clinical access as `member` — the role we provision
|
||||
// for physicians. Kept distinct from `member` so the UI can label/treat it as
|
||||
// "Doctor" and so reception can be a sibling role with narrower access.
|
||||
export const doctor = ac.newRole({
|
||||
...memberAc.statements,
|
||||
patient: ["read", "write"],
|
||||
appointment: ["read", "write", "delete"],
|
||||
prescription: ["read", "write", "delete"],
|
||||
task: ["read", "write", "delete"],
|
||||
});
|
||||
|
||||
// reception (front desk): scheduling + patient registration only. Can manage
|
||||
// appointments and register/edit patient demographics, but has NO access to
|
||||
// clinical records (no prescription statement at all) — least-privilege per
|
||||
// EHR RBAC guidance. The patients service additionally redacts clinical fields
|
||||
// for this role so demographics-only is enforced server-side, not just in UI.
|
||||
export const reception = ac.newRole({
|
||||
...memberAc.statements,
|
||||
patient: ["read", "write"],
|
||||
appointment: ["read", "write", "delete"],
|
||||
task: ["read", "write"],
|
||||
});
|
||||
|
||||
// viewer: read-only access to clinical records.
|
||||
export const viewer = ac.newRole({
|
||||
patient: ["read"],
|
||||
@@ -59,4 +82,4 @@ export const viewer = ac.newRole({
|
||||
task: ["read"],
|
||||
});
|
||||
|
||||
export const roles = { owner, admin, member, viewer };
|
||||
export const roles = { owner, admin, doctor, reception, member, viewer };
|
||||
|
||||
@@ -15,6 +15,18 @@ import * as service from "../services/patients.js";
|
||||
|
||||
export const patientsRouter = Router();
|
||||
|
||||
// The `reception` role is scoped to scheduling + registration: it sees and
|
||||
// writes patient demographics only, never clinical PHI. True only when the
|
||||
// caller's role set is reception without any clinical-capable role.
|
||||
function isReceptionOnly(memberRole?: string): boolean {
|
||||
const names = String(memberRole ?? "")
|
||||
.split(",")
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean);
|
||||
if (!names.includes("reception")) return false;
|
||||
return !names.some((r) => ["owner", "admin", "doctor", "member"].includes(r));
|
||||
}
|
||||
|
||||
// Notify the rest of the clinic about a patient record change (best-effort,
|
||||
// pushed live over the socket).
|
||||
async function notifyClinic(
|
||||
@@ -50,7 +62,12 @@ patientsRouter.get(
|
||||
requirePermission({ patient: ["read"] }),
|
||||
async (req, res, next) => {
|
||||
try {
|
||||
res.json(await service.listPatients(req.organizationId!));
|
||||
res.json(
|
||||
await service.listPatients(
|
||||
req.organizationId!,
|
||||
isReceptionOnly(req.memberRole),
|
||||
),
|
||||
);
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
@@ -65,6 +82,7 @@ patientsRouter.get(
|
||||
const patient = await service.getPatient(
|
||||
req.organizationId!,
|
||||
req.params.fileNumber as string,
|
||||
isReceptionOnly(req.memberRole),
|
||||
);
|
||||
if (!patient) throw new HttpError(404, "Patient not found.");
|
||||
res.json(patient);
|
||||
@@ -84,6 +102,7 @@ patientsRouter.post(
|
||||
req.organizationId!,
|
||||
req.user!.id,
|
||||
input,
|
||||
isReceptionOnly(req.memberRole),
|
||||
);
|
||||
await recordActivity({
|
||||
orgId: req.organizationId!,
|
||||
@@ -117,6 +136,7 @@ patientsRouter.put(
|
||||
req.organizationId!,
|
||||
req.params.fileNumber as string,
|
||||
input,
|
||||
isReceptionOnly(req.memberRole),
|
||||
);
|
||||
if (!updated) throw new HttpError(404, "Patient not found.");
|
||||
await recordActivity({
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
import { asc, eq } from "drizzle-orm";
|
||||
import { Router } from "express";
|
||||
import { z } from "zod";
|
||||
|
||||
import { auth } from "../auth.js";
|
||||
import { db } from "../db/index.js";
|
||||
import { member, organization, user } from "../db/schema/auth.js";
|
||||
import { HttpError } from "../lib/http-error.js";
|
||||
import { requireAuth, requireOrg, requirePermission } from "../middleware/auth.js";
|
||||
|
||||
export const staffRouter = Router();
|
||||
|
||||
// Admin-provisioned staff accounts. Instead of emailing an invitation link, an
|
||||
// owner/admin creates the employee's account directly — name, role and a
|
||||
// username + password the employee uses to sign in. Everything is gated by the
|
||||
// Better Auth `member` permission so RBAC stays in one place. The account is
|
||||
// created via `auth.api.signUpEmail` and attached to the active clinic via
|
||||
// `auth.api.addMember`; the new user then shows up everywhere org members do
|
||||
// (e.g. the Messages compose picker) with no extra wiring.
|
||||
|
||||
// Roles an admin may assign — `owner` is intentionally excluded (the clinic
|
||||
// creator is the sole owner; transfer ownership via member-role updates).
|
||||
const PROVISIONABLE_ROLES = ["admin", "doctor", "reception", "viewer"] as const;
|
||||
|
||||
const staffInputSchema = z.object({
|
||||
name: z.string().trim().min(1).max(120),
|
||||
username: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(3)
|
||||
.max(32)
|
||||
.regex(
|
||||
/^[a-zA-Z0-9_.]+$/,
|
||||
"Username may only contain letters, numbers, dots and underscores.",
|
||||
),
|
||||
password: z.string().min(12).max(256),
|
||||
role: z.enum(PROVISIONABLE_ROLES),
|
||||
// Optional real email; staff sign in by username, so when omitted we mint a
|
||||
// placeholder (the email column is required + unique).
|
||||
email: z.preprocess(
|
||||
(v) => (v === "" ? undefined : v),
|
||||
z.string().trim().email().optional(),
|
||||
),
|
||||
});
|
||||
|
||||
staffRouter.use(requireAuth, requireOrg);
|
||||
|
||||
// List the clinic's members with their usernames (the org client's
|
||||
// getFullOrganization doesn't expose username). Owner/admin only.
|
||||
staffRouter.get(
|
||||
"/",
|
||||
requirePermission({ member: ["create"] }),
|
||||
async (req, res, next) => {
|
||||
try {
|
||||
const rows = await db
|
||||
.select({
|
||||
id: member.id,
|
||||
userId: member.userId,
|
||||
role: member.role,
|
||||
name: user.name,
|
||||
email: user.email,
|
||||
username: user.username,
|
||||
})
|
||||
.from(member)
|
||||
.innerJoin(user, eq(user.id, member.userId))
|
||||
.where(eq(member.organizationId, req.organizationId!))
|
||||
.orderBy(asc(user.name));
|
||||
res.json(rows);
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// Provision a new staff account and add them to the active clinic.
|
||||
staffRouter.post(
|
||||
"/",
|
||||
requirePermission({ member: ["create"] }),
|
||||
async (req, res, next) => {
|
||||
try {
|
||||
const input = staffInputSchema.parse(req.body);
|
||||
|
||||
const [org] = await db
|
||||
.select({ slug: organization.slug })
|
||||
.from(organization)
|
||||
.where(eq(organization.id, req.organizationId!));
|
||||
if (!org) throw new HttpError(404, "Clinic not found.");
|
||||
|
||||
const email =
|
||||
input.email ?? `${input.username.toLowerCase()}@${org.slug}.temetro.local`;
|
||||
|
||||
// Create the credential account (user + hashed password + username).
|
||||
let newUserId: string;
|
||||
try {
|
||||
const result = await auth.api.signUpEmail({
|
||||
body: {
|
||||
name: input.name,
|
||||
email,
|
||||
password: input.password,
|
||||
username: input.username,
|
||||
},
|
||||
});
|
||||
newUserId = result.user.id;
|
||||
} catch (err) {
|
||||
// Surface Better Auth's reason (e.g. username/email already taken).
|
||||
const message =
|
||||
(err as { body?: { message?: string } })?.body?.message ??
|
||||
(err as Error)?.message ??
|
||||
"Could not create the account.";
|
||||
throw new HttpError(400, message);
|
||||
}
|
||||
|
||||
// Attach the new user to the clinic with the chosen role (server-side,
|
||||
// no invitation step).
|
||||
await auth.api.addMember({
|
||||
body: {
|
||||
userId: newUserId,
|
||||
organizationId: req.organizationId!,
|
||||
role: input.role,
|
||||
},
|
||||
});
|
||||
|
||||
res.status(201).json({
|
||||
userId: newUserId,
|
||||
name: input.name,
|
||||
email,
|
||||
username: input.username.toLowerCase(),
|
||||
role: input.role,
|
||||
});
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -18,6 +18,7 @@ import type {
|
||||
Medication,
|
||||
Patient,
|
||||
Problem,
|
||||
Trend,
|
||||
} from "../types/patient.js";
|
||||
|
||||
type PatientRow = typeof patients.$inferSelect;
|
||||
@@ -65,6 +66,27 @@ function toPatient(row: PatientRow, children: Children): Patient {
|
||||
};
|
||||
}
|
||||
|
||||
const EMPTY_TREND: Trend = { label: "", unit: "", points: [] };
|
||||
|
||||
// Strip every clinical section, leaving only registration/demographic fields.
|
||||
// Used for the `reception` role, which is scoped to scheduling + registration
|
||||
// and must never receive PHI (labs, meds, problems, vitals, encounters). This
|
||||
// enforces least-privilege server-side rather than relying on the UI to hide it.
|
||||
function redactClinical(patient: Patient): Patient {
|
||||
return {
|
||||
...patient,
|
||||
allergies: [],
|
||||
alerts: [],
|
||||
medications: [],
|
||||
problems: [],
|
||||
vitals: { bp: "", hr: "", temp: "", spo2: "", takenAt: "" },
|
||||
vitalsTrend: EMPTY_TREND,
|
||||
labs: [],
|
||||
labTrend: EMPTY_TREND,
|
||||
encounters: [],
|
||||
};
|
||||
}
|
||||
|
||||
// Input children are already in the canonical Patient sub-shapes.
|
||||
function childrenFromInput(input: PatientInput): Children {
|
||||
return {
|
||||
@@ -98,6 +120,49 @@ function patientColumns(orgId: string, input: PatientInput, createdBy?: string)
|
||||
};
|
||||
}
|
||||
|
||||
// Registration columns only — clinical columns get empty values (they are
|
||||
// NOT NULL). Used when the `reception` role creates a patient so they can never
|
||||
// write PHI even if the request body contains clinical fields.
|
||||
function demographicColumns(
|
||||
orgId: string,
|
||||
input: PatientInput,
|
||||
createdBy?: string,
|
||||
) {
|
||||
return {
|
||||
organizationId: orgId,
|
||||
fileNumber: input.fileNumber,
|
||||
name: input.name,
|
||||
age: input.age,
|
||||
sex: input.sex,
|
||||
pcp: input.pcp,
|
||||
status: input.status,
|
||||
initials: input.initials,
|
||||
alerts: [] as string[],
|
||||
vitalsBp: "",
|
||||
vitalsHr: "",
|
||||
vitalsTemp: "",
|
||||
vitalsSpo2: "",
|
||||
vitalsTakenAt: "",
|
||||
vitalsTrend: EMPTY_TREND,
|
||||
labTrend: EMPTY_TREND,
|
||||
...(createdBy ? { createdBy } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
// The demographic subset for a `reception` update — never touches clinical
|
||||
// columns or child tables, so an existing record's PHI is preserved.
|
||||
function demographicUpdateColumns(input: PatientInput) {
|
||||
return {
|
||||
fileNumber: input.fileNumber,
|
||||
name: input.name,
|
||||
age: input.age,
|
||||
sex: input.sex,
|
||||
pcp: input.pcp,
|
||||
status: input.status,
|
||||
initials: input.initials,
|
||||
};
|
||||
}
|
||||
|
||||
// Loads and groups child rows for a set of patients in one round-trip each.
|
||||
async function loadChildren(
|
||||
patientIds: string[],
|
||||
@@ -212,19 +277,26 @@ function isUniqueViolation(err: unknown): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
export async function listPatients(orgId: string): Promise<Patient[]> {
|
||||
export async function listPatients(
|
||||
orgId: string,
|
||||
demographicsOnly = false,
|
||||
): Promise<Patient[]> {
|
||||
const rows = await db
|
||||
.select()
|
||||
.from(patients)
|
||||
.where(eq(patients.organizationId, orgId))
|
||||
.orderBy(asc(patients.name));
|
||||
const children = await loadChildren(rows.map((r) => r.id));
|
||||
return rows.map((r) => toPatient(r, children.get(r.id) ?? emptyChildren()));
|
||||
return rows.map((r) => {
|
||||
const patient = toPatient(r, children.get(r.id) ?? emptyChildren());
|
||||
return demographicsOnly ? redactClinical(patient) : patient;
|
||||
});
|
||||
}
|
||||
|
||||
export async function getPatient(
|
||||
orgId: string,
|
||||
fileNumber: string,
|
||||
demographicsOnly = false,
|
||||
): Promise<Patient | null> {
|
||||
const [row] = await db
|
||||
.select()
|
||||
@@ -237,16 +309,27 @@ export async function getPatient(
|
||||
);
|
||||
if (!row) return null;
|
||||
const children = await loadChildren([row.id]);
|
||||
return toPatient(row, children.get(row.id) ?? emptyChildren());
|
||||
const patient = toPatient(row, children.get(row.id) ?? emptyChildren());
|
||||
return demographicsOnly ? redactClinical(patient) : patient;
|
||||
}
|
||||
|
||||
export async function createPatient(
|
||||
orgId: string,
|
||||
userId: string,
|
||||
input: PatientInput,
|
||||
demographicsOnly = false,
|
||||
): Promise<Patient> {
|
||||
try {
|
||||
return await db.transaction(async (tx) => {
|
||||
// Reception registers demographics only — clinical input is ignored and
|
||||
// no child (clinical) rows are written.
|
||||
if (demographicsOnly) {
|
||||
const [row] = await tx
|
||||
.insert(patients)
|
||||
.values(demographicColumns(orgId, input, userId))
|
||||
.returning();
|
||||
return toPatient(row!, emptyChildren());
|
||||
}
|
||||
const [row] = await tx
|
||||
.insert(patients)
|
||||
.values(patientColumns(orgId, input, userId))
|
||||
@@ -269,6 +352,7 @@ export async function updatePatient(
|
||||
orgId: string,
|
||||
fileNumber: string,
|
||||
input: PatientInput,
|
||||
demographicsOnly = false,
|
||||
): Promise<Patient | null> {
|
||||
try {
|
||||
return await db.transaction(async (tx) => {
|
||||
@@ -283,6 +367,21 @@ export async function updatePatient(
|
||||
);
|
||||
if (!existing) return null;
|
||||
|
||||
// Reception edits demographics only: update the registration columns and
|
||||
// leave clinical columns + child tables (existing PHI) untouched, then
|
||||
// return a redacted record.
|
||||
if (demographicsOnly) {
|
||||
const [row] = await tx
|
||||
.update(patients)
|
||||
.set(demographicUpdateColumns(input))
|
||||
.where(eq(patients.id, existing.id))
|
||||
.returning();
|
||||
const children = await loadChildren([existing.id]);
|
||||
return redactClinical(
|
||||
toPatient(row!, children.get(existing.id) ?? emptyChildren()),
|
||||
);
|
||||
}
|
||||
|
||||
const [row] = await tx
|
||||
.update(patients)
|
||||
.set(patientColumns(orgId, input))
|
||||
|
||||
Reference in New Issue
Block a user