Files
temetro/frontend/components/auth/app-auth-guard.tsx
T
Khalid Abdi 6213da9477 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>
2026-06-08 19:12:07 +03:00

68 lines
2.2 KiB
TypeScript

"use client";
import { usePathname, useRouter } from "next/navigation";
import { type ReactNode, useEffect, useRef } from "react";
import { authClient } from "@/lib/auth-client";
import { canAccessRoute, defaultLandingFor, useActiveRole } from "@/lib/roles";
// Authoritative client-side gate for the app shell. Requires a session and an
// active clinic. If the user is signed in without an active clinic but already
// belongs to one, we select it automatically; onboarding is only for users
// with no clinics at all. The API enforces the same access rules server-side.
export function AppAuthGuard({ children }: { children: ReactNode }) {
const router = useRouter();
const pathname = usePathname();
const role = useActiveRole();
const { data: session, isPending } = authClient.useSession();
const { data: orgs, isPending: orgsPending } =
authClient.useListOrganizations();
const settingActive = useRef(false);
const hasUser = Boolean(session?.user);
const activeOrgId = session?.session?.activeOrganizationId ?? null;
useEffect(() => {
if (isPending) return;
if (!hasUser) {
router.replace("/login");
return;
}
if (activeOrgId) return;
// Signed in but no active clinic selected yet.
if (orgsPending) return;
const first = orgs?.[0];
if (first) {
if (!settingActive.current) {
settingActive.current = true;
void authClient.organization.setActive({ organizationId: first.id });
}
} else {
router.replace("/onboarding");
}
}, [isPending, hasUser, activeOrgId, orgsPending, orgs, router]);
const ready = hasUser && Boolean(activeOrgId);
// Role-based route guard: keep non-clinical roles (reception) out of clinical
// pages — bounce them to their default landing. The backend enforces the same
// via per-route RBAC (403); this just avoids showing an empty/erroring page.
useEffect(() => {
if (!ready || role == null) return;
if (!canAccessRoute(pathname, role)) {
router.replace(defaultLandingFor(role));
}
}, [ready, role, pathname, router]);
if (!ready) {
return (
<div className="flex h-dvh w-full items-center justify-center text-sm text-muted-foreground">
Loading
</div>
);
}
return <>{children}</>;
}