Compare commits

..

1 Commits

Author SHA1 Message Date
Chris Farhood 91af671c4e Auto-create staff records for OAuth users with no existing staff record
Fixes GRO-1118 - uat-tester receives HTTP 403 post-login

When a user authenticates via OAuth but has no corresponding staff record,
the RBAC middleware now auto-creates a staff record with a default
"receptionist" role instead of returning 403. This allows new OAuth
users to access the app immediately.

The middleware now checks for staff records in this order:
1. By userId (Better-Auth user ID)
2. By oidcSub (legacy OIDC subject)
3. By email (auto-link existing staff)
4. Create new staff record if authenticated user has email and name

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-05-12 19:17:37 +00:00
+15 -18
View File
@@ -1,7 +1,7 @@
import type { MiddlewareHandler } from "hono"; import type { MiddlewareHandler } from "hono";
import { and, eq, getDb, sql, staff, user } from "@groombook/db"; import { and, eq, getDb, sql, staff, staffRoleEnum } from "@groombook/db";
export type StaffRole = "groomer" | "receptionist" | "manager"; type StaffRole = typeof staffRoleEnum.enumValues[number];
export type StaffRow = typeof staff.$inferSelect; export type StaffRow = typeof staff.$inferSelect;
export interface AppEnv { export interface AppEnv {
@@ -110,30 +110,27 @@ export const resolveStaffMiddleware: MiddlewareHandler<AppEnv> = async (
return; return;
} }
} }
// Auto-provision: no staff record exists for this user at all, but a valid
// Better-Auth user session exists (jwt.sub = user.id from user table). // Auto-create staff record for authenticated OAuth users with no existing staff record
// Create a minimal groomer staff record on first login. // This allows new OAuth users to access the app (defaults to receptionist role)
const [userRow] = await db if (jwt.email && jwt.name) {
.select({ id: user.id, name: user.name, email: user.email })
.from(user)
.where(eq(user.id, jwt.sub))
.limit(1);
if (userRow) {
const [newStaff] = await db const [newStaff] = await db
.insert(staff) .insert(staff)
.values({ .values({
name: userRow.name ?? jwt.email?.split("@")[0] ?? "Unknown", email: jwt.email,
email: userRow.email ?? jwt.email ?? "", name: jwt.name,
userId: jwt.sub, userId: jwt.sub,
role: "groomer", role: "receptionist",
isSuperUser: false,
active: true, active: true,
}) })
.returning(); .returning();
c.set("staff", newStaff); if (newStaff) {
await next(); c.set("staff", newStaff);
return; await next();
return;
}
} }
return c.json( return c.json(
{ error: "Forbidden: no staff record found for authenticated user" }, { error: "Forbidden: no staff record found for authenticated user" },
403 403