Compare commits
37 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| d9ba6045ad | |||
| b83a793de4 | |||
| a610ef9d39 | |||
| cf3d30f19e | |||
| 0625961adf | |||
| b61d899f81 | |||
| 38047d5ea3 | |||
| fbcaedf155 | |||
| 7cfb24d542 | |||
| b0d9e5816f | |||
| 7a0662541d | |||
| 5e78df85f1 | |||
| 0a2259b67f | |||
| cc09a8e1e8 | |||
| 74da042d13 | |||
| ad1b210de1 | |||
| a03771f7e7 | |||
| 040ff4a253 | |||
| a1466b44c9 | |||
| b486c44a82 | |||
| b5a08a2c7e | |||
| 06d72b5baf | |||
| 33aa63b10f | |||
| e26d960046 | |||
| 4e8c66f3ca | |||
| ea28095434 | |||
| 3b9c72c2c4 | |||
| 49f70eb74b | |||
| 62dfc7776b | |||
| 68df697cf3 | |||
| 174d1c667b | |||
| 9fe6e15012 | |||
| 002e6575ba | |||
| f9c679b392 | |||
| 7b2b533c16 | |||
| 55894c6ff2 | |||
| 9f2809e89b |
@@ -0,0 +1 @@
|
|||||||
|
GRO-1757 direct push CI trigger - 2026-05-26T00:15:41Z
|
||||||
@@ -78,6 +78,8 @@ jobs:
|
|||||||
|
|
||||||
- name: Set up Docker Buildx
|
- name: Set up Docker Buildx
|
||||||
uses: docker/setup-buildx-action@v3
|
uses: docker/setup-buildx-action@v3
|
||||||
|
with:
|
||||||
|
driver-opts: network=host
|
||||||
|
|
||||||
- name: Log in to Gitea Container Registry
|
- name: Log in to Gitea Container Registry
|
||||||
uses: docker/login-action@v3
|
uses: docker/login-action@v3
|
||||||
@@ -89,10 +91,12 @@ jobs:
|
|||||||
- name: Build and push API image
|
- name: Build and push API image
|
||||||
uses: docker/build-push-action@v6
|
uses: docker/build-push-action@v6
|
||||||
with:
|
with:
|
||||||
|
provenance: false
|
||||||
context: .
|
context: .
|
||||||
file: Dockerfile
|
file: Dockerfile
|
||||||
target: runner
|
target: runner
|
||||||
push: true
|
push: true
|
||||||
|
provenance: false
|
||||||
tags: |
|
tags: |
|
||||||
git.farh.net/groombook/api:${{ steps.version.outputs.tag }}
|
git.farh.net/groombook/api:${{ steps.version.outputs.tag }}
|
||||||
${{ github.ref == 'refs/heads/main' && 'git.farh.net/groombook/api:latest' || '' }}
|
${{ github.ref == 'refs/heads/main' && 'git.farh.net/groombook/api:latest' || '' }}
|
||||||
@@ -102,10 +106,12 @@ jobs:
|
|||||||
- name: Build and push Migrate image
|
- name: Build and push Migrate image
|
||||||
uses: docker/build-push-action@v6
|
uses: docker/build-push-action@v6
|
||||||
with:
|
with:
|
||||||
|
provenance: false
|
||||||
context: .
|
context: .
|
||||||
file: Dockerfile
|
file: Dockerfile
|
||||||
target: migrate
|
target: migrate
|
||||||
push: true
|
push: true
|
||||||
|
provenance: false
|
||||||
tags: |
|
tags: |
|
||||||
git.farh.net/groombook/migrate:${{ steps.version.outputs.tag }}
|
git.farh.net/groombook/migrate:${{ steps.version.outputs.tag }}
|
||||||
${{ github.ref == 'refs/heads/main' && 'git.farh.net/groombook/migrate:latest' || '' }}
|
${{ github.ref == 'refs/heads/main' && 'git.farh.net/groombook/migrate:latest' || '' }}
|
||||||
@@ -115,10 +121,12 @@ jobs:
|
|||||||
- name: Build and push Seed image
|
- name: Build and push Seed image
|
||||||
uses: docker/build-push-action@v6
|
uses: docker/build-push-action@v6
|
||||||
with:
|
with:
|
||||||
|
provenance: false
|
||||||
context: .
|
context: .
|
||||||
file: Dockerfile
|
file: Dockerfile
|
||||||
target: seed
|
target: seed
|
||||||
push: true
|
push: true
|
||||||
|
provenance: false
|
||||||
tags: |
|
tags: |
|
||||||
git.farh.net/groombook/seed:${{ steps.version.outputs.tag }}
|
git.farh.net/groombook/seed:${{ steps.version.outputs.tag }}
|
||||||
${{ github.ref == 'refs/heads/main' && 'git.farh.net/groombook/seed:latest' || '' }}
|
${{ github.ref == 'refs/heads/main' && 'git.farh.net/groombook/seed:latest' || '' }}
|
||||||
@@ -128,10 +136,12 @@ jobs:
|
|||||||
- name: Build and push Reset image
|
- name: Build and push Reset image
|
||||||
uses: docker/build-push-action@v6
|
uses: docker/build-push-action@v6
|
||||||
with:
|
with:
|
||||||
|
provenance: false
|
||||||
context: .
|
context: .
|
||||||
file: Dockerfile
|
file: Dockerfile
|
||||||
target: reset
|
target: reset
|
||||||
push: true
|
push: true
|
||||||
|
provenance: false
|
||||||
tags: |
|
tags: |
|
||||||
git.farh.net/groombook/reset:${{ steps.version.outputs.tag }}
|
git.farh.net/groombook/reset:${{ steps.version.outputs.tag }}
|
||||||
${{ github.ref == 'refs/heads/main' && 'git.farh.net/groombook/reset:latest' || '' }}
|
${{ github.ref == 'refs/heads/main' && 'git.farh.net/groombook/reset:latest' || '' }}
|
||||||
|
|||||||
@@ -21,6 +21,14 @@ GroomBook API is a Hono-based REST service (TypeScript/Node.js) powering the pet
|
|||||||
|
|
||||||
## Test Cases
|
## Test Cases
|
||||||
|
|
||||||
|
### 4.0 Health Check
|
||||||
|
|
||||||
|
| # | Scenario | Steps | Expected |
|
||||||
|
|---|----------|-------|----------|
|
||||||
|
| TC-API-0.1 | Unauthenticated health check | GET /api/health | 200 OK, `{"status":"ok"}` |
|
||||||
|
|
||||||
|
> **Note (GRO-1544):** Health endpoint registered on `api` basePath before auth middleware at `/api/health`. The old path `/health` was incorrect (routed to web pod via HTTPRoute `/*` rule).
|
||||||
|
|
||||||
### 4.1 Authentication
|
### 4.1 Authentication
|
||||||
|
|
||||||
| # | Scenario | Steps | Expected |
|
| # | Scenario | Steps | Expected |
|
||||||
@@ -40,6 +48,26 @@ GroomBook API is a Hono-based REST service (TypeScript/Node.js) powering the pet
|
|||||||
| TC-API-1.15 | Name fallback — no name, no email | Auto-provision where Better-Auth user has name = null, email = null | Staff name = "Unknown" |
|
| TC-API-1.15 | Name fallback — no name, no email | Auto-provision where Better-Auth user has name = null, email = null | Staff name = "Unknown" |
|
||||||
| TC-API-1.16 | OIDC login — Terraform-provisioned user | Initiate OIDC login as any UAT persona (uat-super, uat-groomer, uat-customer, uat-tester), complete authentik callback | 200 OK, session created — no account_not_linked error |
|
| TC-API-1.16 | OIDC login — Terraform-provisioned user | Initiate OIDC login as any UAT persona (uat-super, uat-groomer, uat-customer, uat-tester), complete authentik callback | 200 OK, session created — no account_not_linked error |
|
||||||
|
|
||||||
|
#### SSO Login Journey (Authentik OIDC end-to-end)
|
||||||
|
|
||||||
|
| # | Scenario | Steps | Pass Criteria | Fail Criteria |
|
||||||
|
|---|----------|-------|---------------|---------------|
|
||||||
|
| TC-API-1.17 | SSO redirect to Authentik | Navigate to app → sign-in page shown → click "Sign in with SSO" | Redirected to Authentik at auth.farh.net | 403 error, redirect loop, no SSO button |
|
||||||
|
| TC-API-1.18 | Authenticate with valid OIDC credentials | At Authentik login page, enter valid credentials and authenticate | Redirected back to app with valid session | Redirect loop, 403, missing session cookie |
|
||||||
|
| TC-API-1.19 | SSO user auto-provisioned as groomer | Complete SSO login as a user with no pre-existing staff record | 200 response; groomer staff record auto-created; session active | 403 Forbidden, staff record not created |
|
||||||
|
| TC-API-1.20 | Existing staff record resolves correctly | Complete SSO login as uat-groomer (pre-existing staff) | 200 OK, correct staff identity resolved, no duplicate record created | 403, duplicate record, wrong staff data |
|
||||||
|
| TC-API-1.21 | SSO session grants dashboard access | After TC-API-1.18 SSO login, GET /api/staff/me | 200 OK, valid staff record returned, correct role displayed | 401/403, missing session, wrong identity |
|
||||||
|
|
||||||
|
#### OOBE Flow Post-Login
|
||||||
|
|
||||||
|
| # | Scenario | Steps | Pass Criteria | Fail Criteria |
|
||||||
|
|---|----------|-------|---------------|---------------|
|
||||||
|
| TC-API-1.22 | Fresh DB reports needsSetup | On a fresh DB (no super user), GET /api/setup/status | needsSetup: true returned | needsSetup: false when it should be true |
|
||||||
|
| TC-API-1.23 | Configure OIDC via auth-provider endpoint | POST /api/setup/auth-provider with valid OIDC config | 200 OK, auth provider configured, no 403 | 403, setup blocked, invalid config rejected |
|
||||||
|
| TC-API-1.24 | Complete setup creates super user | POST /api/setup with business name (after TC-API-1.23) | First user becomes super user, setup completes | Setup errors, 403 on admin endpoints |
|
||||||
|
| TC-API-1.25 | Super user accesses admin features | After TC-API-1.24, GET /api/staff/me and verify isSuperUser: true | isSuperUser: true, admin endpoints accessible | 403 on admin, isSuperUser: false |
|
||||||
|
| TC-API-1.26 | Auto-provision skipped during OOBE | During fresh setup (needsSetup: true), complete OIDC login — verify no duplicate staff record created before setup completes | No duplicate staff, OOBE completes successfully | Duplicate staff record, 403 before setup, auto-provision interferes with OOBE |
|
||||||
|
|
||||||
### 4.2 Client Management
|
### 4.2 Client Management
|
||||||
|
|
||||||
| # | Scenario | Steps | Expected |
|
| # | Scenario | Steps | Expected |
|
||||||
|
|||||||
@@ -36,6 +36,19 @@ const DEMO_PET = {
|
|||||||
weightKg: "30.00",
|
weightKg: "30.00",
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const UAT_CLIENT = {
|
||||||
|
name: "UAT Customer",
|
||||||
|
email: "uat-customer@groombook.dev",
|
||||||
|
phone: "555-0100",
|
||||||
|
address: "1 UAT Lane, Test City, CA 90210",
|
||||||
|
status: "active" as const,
|
||||||
|
};
|
||||||
|
|
||||||
|
const UAT_PETS = [
|
||||||
|
{ name: "Bella", species: "Dog", breed: "Poodle", coatType: "curly" as const, weightKg: "20.00" },
|
||||||
|
{ name: "Max", species: "Dog", breed: "Labrador Retriever", coatType: "smooth" as const, weightKg: "30.00" },
|
||||||
|
];
|
||||||
|
|
||||||
const DEMO_SERVICES = [
|
const DEMO_SERVICES = [
|
||||||
{ id: "b0000001-0000-0000-0000-000000000001", name: "Bath & Brush", description: "Full bath, blow-dry, brush out, and ear cleaning", basePriceCents: 4500, durationMinutes: 45 },
|
{ id: "b0000001-0000-0000-0000-000000000001", name: "Bath & Brush", description: "Full bath, blow-dry, brush out, and ear cleaning", basePriceCents: 4500, durationMinutes: 45 },
|
||||||
{ id: "b0000001-0000-0000-0000-000000000002", name: "Full Groom — Small", description: "Complete grooming for dogs under 25 lbs", basePriceCents: 6500, durationMinutes: 60 },
|
{ id: "b0000001-0000-0000-0000-000000000002", name: "Full Groom — Small", description: "Complete grooming for dogs under 25 lbs", basePriceCents: 6500, durationMinutes: 60 },
|
||||||
@@ -43,7 +56,7 @@ const DEMO_SERVICES = [
|
|||||||
{ id: "b0000001-0000-0000-0000-000000000004", name: "Nail Trim", description: "Nail clipping and filing", basePriceCents: 1500, durationMinutes: 15 },
|
{ id: "b0000001-0000-0000-0000-000000000004", name: "Nail Trim", description: "Nail clipping and filing", basePriceCents: 1500, durationMinutes: 15 },
|
||||||
];
|
];
|
||||||
|
|
||||||
adminSeedRouter.post("/seed", async (c) => {
|
adminSeedRouter.post("/", async (c) => {
|
||||||
// Refuse to run when AUTH_DISABLED — dev environments use direct-DB seeding
|
// Refuse to run when AUTH_DISABLED — dev environments use direct-DB seeding
|
||||||
if (process.env.AUTH_DISABLED === "true") {
|
if (process.env.AUTH_DISABLED === "true") {
|
||||||
return c.json(
|
return c.json(
|
||||||
@@ -128,6 +141,51 @@ adminSeedRouter.post("/seed", async (c) => {
|
|||||||
results.push(`Created pet '${DEMO_PET.name}' for Demo Client (id: ${created!.id})`);
|
results.push(`Created pet '${DEMO_PET.name}' for Demo Client (id: ${created!.id})`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Client: UAT Customer ──────────────────────────────────────────────────
|
||||||
|
const [existingUatClient] = await db
|
||||||
|
.select()
|
||||||
|
.from(clients)
|
||||||
|
.where(eq(clients.email, UAT_CLIENT.email));
|
||||||
|
|
||||||
|
let uatClientId: string;
|
||||||
|
if (existingUatClient) {
|
||||||
|
uatClientId = existingUatClient.id;
|
||||||
|
results.push(`Client '${UAT_CLIENT.name}' already exists (id: ${uatClientId})`);
|
||||||
|
} else {
|
||||||
|
const [created] = await db.insert(clients).values(UAT_CLIENT).returning();
|
||||||
|
uatClientId = created!.id;
|
||||||
|
results.push(`Created client '${UAT_CLIENT.name}' (id: ${uatClientId})`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Pets: UAT Customer's Pets ─────────────────────────────────────────────
|
||||||
|
const existingUatPets = await db
|
||||||
|
.select()
|
||||||
|
.from(pets)
|
||||||
|
.where(eq(pets.clientId, uatClientId));
|
||||||
|
|
||||||
|
for (const uatPet of UAT_PETS) {
|
||||||
|
const existingPet = existingUatPets.find(
|
||||||
|
(p) => p.name === uatPet.name && p.species === uatPet.species
|
||||||
|
);
|
||||||
|
if (existingPet) {
|
||||||
|
results.push(`Pet '${uatPet.name}' already exists for UAT Customer (id: ${existingPet.id})`);
|
||||||
|
} else {
|
||||||
|
const [created] = await db
|
||||||
|
.insert(pets)
|
||||||
|
.values({
|
||||||
|
clientId: uatClientId,
|
||||||
|
name: uatPet.name,
|
||||||
|
species: uatPet.species,
|
||||||
|
breed: uatPet.breed,
|
||||||
|
coatType: uatPet.coatType,
|
||||||
|
weightKg: uatPet.weightKg,
|
||||||
|
dateOfBirth: new Date("2019-01-01T00:00:00Z"),
|
||||||
|
})
|
||||||
|
.returning();
|
||||||
|
results.push(`Created pet '${uatPet.name}' for UAT Customer (id: ${created!.id})`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return c.json({
|
return c.json({
|
||||||
message: "Seed complete",
|
message: "Seed complete",
|
||||||
details: results,
|
details: results,
|
||||||
|
|||||||
@@ -6,8 +6,10 @@
|
|||||||
CREATE TYPE "pet_size_category" AS ENUM ('small', 'medium', 'large', 'xlarge');
|
CREATE TYPE "pet_size_category" AS ENUM ('small', 'medium', 'large', 'xlarge');
|
||||||
CREATE TYPE "coat_type" AS ENUM ('smooth', 'double', 'wire', 'curly', 'long', 'hairless');
|
CREATE TYPE "coat_type" AS ENUM ('smooth', 'double', 'wire', 'curly', 'long', 'hairless');
|
||||||
|
|
||||||
-- ─── Alter pets columns to use new enums ─────────────────────────────────────
|
-- ─── Add columns to pets if missing, then cast to enums ──────────────────────
|
||||||
|
|
||||||
|
ALTER TABLE "pets" ADD COLUMN IF NOT EXISTS "coat_type" text;
|
||||||
|
ALTER TABLE "pets" ADD COLUMN IF NOT EXISTS "pet_size_category" text;
|
||||||
ALTER TABLE "pets" ALTER COLUMN "coat_type" TYPE "coat_type" USING "coat_type"::text::"coat_type";
|
ALTER TABLE "pets" ALTER COLUMN "coat_type" TYPE "coat_type" USING "coat_type"::text::"coat_type";
|
||||||
ALTER TABLE "pets" ALTER COLUMN "pet_size_category" TYPE "pet_size_category" USING "pet_size_category"::text::"pet_size_category";
|
ALTER TABLE "pets" ALTER COLUMN "pet_size_category" TYPE "pet_size_category" USING "pet_size_category"::text::"pet_size_category";
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
-- no-op: journal entry exists but no schema change was needed
|
||||||
@@ -105,6 +105,10 @@ export function buildPet(overrides: Partial<PetRow> & { clientId: string }): Pet
|
|||||||
photoKey: null,
|
photoKey: null,
|
||||||
photoUploadedAt: null,
|
photoUploadedAt: null,
|
||||||
image: null,
|
image: null,
|
||||||
|
temperamentScore: null,
|
||||||
|
temperamentFlags: [],
|
||||||
|
medicalAlerts: [],
|
||||||
|
preferredCuts: [],
|
||||||
createdAt: new Date("2025-01-01T00:00:00Z"),
|
createdAt: new Date("2025-01-01T00:00:00Z"),
|
||||||
updatedAt: new Date("2025-01-01T00:00:00Z"),
|
updatedAt: new Date("2025-01-01T00:00:00Z"),
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ export function getDb() {
|
|||||||
if (_db) return _db;
|
if (_db) return _db;
|
||||||
const url = process.env.DATABASE_URL;
|
const url = process.env.DATABASE_URL;
|
||||||
if (!url) throw new Error("DATABASE_URL is not set");
|
if (!url) throw new Error("DATABASE_URL is not set");
|
||||||
const client = postgres(url, { max: 10 });
|
const client = postgres(url, { max: 10, connect_timeout: 5 });
|
||||||
_db = drizzle(client, { schema });
|
_db = drizzle(client, { schema });
|
||||||
return _db;
|
return _db;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import {
|
|||||||
unique,
|
unique,
|
||||||
uuid,
|
uuid,
|
||||||
} from "drizzle-orm/pg-core";
|
} from "drizzle-orm/pg-core";
|
||||||
|
import type { MedicalAlert } from "@groombook/types";
|
||||||
|
|
||||||
// ─── Enums ────────────────────────────────────────────────────────────────────
|
// ─── Enums ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@@ -164,6 +165,10 @@ export const pets = pgTable(
|
|||||||
specialCareNotes: text("special_care_notes"),
|
specialCareNotes: text("special_care_notes"),
|
||||||
coatType: coatTypeEnum("coat_type"),
|
coatType: coatTypeEnum("coat_type"),
|
||||||
petSizeCategory: petSizeCategoryEnum("pet_size_category"),
|
petSizeCategory: petSizeCategoryEnum("pet_size_category"),
|
||||||
|
temperamentScore: integer("temperament_score"),
|
||||||
|
temperamentFlags: jsonb("temperament_flags").$type<string[]>().default([]),
|
||||||
|
medicalAlerts: jsonb("medical_alerts").$type<MedicalAlert[]>().default([]),
|
||||||
|
preferredCuts: jsonb("preferred_cuts").$type<string[]>().default([]),
|
||||||
customFields: jsonb("custom_fields").$type<Record<string, string>>().notNull().default({}),
|
customFields: jsonb("custom_fields").$type<Record<string, string>>().notNull().default({}),
|
||||||
photoKey: text("photo_key"),
|
photoKey: text("photo_key"),
|
||||||
photoUploadedAt: timestamp("photo_uploaded_at"),
|
photoUploadedAt: timestamp("photo_uploaded_at"),
|
||||||
|
|||||||
+10
-5
@@ -58,8 +58,11 @@ app.use(
|
|||||||
})
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
// Health check (no auth required)
|
// Health check — no auth required, registered on app at full path before auth middleware
|
||||||
|
// /health: used by Dockerfile HEALTHCHECK and K8s readinessProbe/livenessProbe (port 3000 direct)
|
||||||
app.get("/health", (c) => c.json({ status: "ok" }));
|
app.get("/health", (c) => c.json({ status: "ok" }));
|
||||||
|
// /api/health: used by Gateway HTTPRoute (/api/* → API pod)
|
||||||
|
app.get("/api/health", (c) => c.json({ status: "ok" }));
|
||||||
|
|
||||||
// Public booking routes — no auth required, must be registered before auth middleware
|
// Public booking routes — no auth required, must be registered before auth middleware
|
||||||
app.route("/api/book", bookRouter);
|
app.route("/api/book", bookRouter);
|
||||||
@@ -282,14 +285,16 @@ startReminderScheduler();
|
|||||||
|
|
||||||
function shutdown() {
|
function shutdown() {
|
||||||
console.log("Shutting down gracefully...");
|
console.log("Shutting down gracefully...");
|
||||||
|
// SIGTERM/SIGINT → server.close() → callback → process.exit(0)
|
||||||
|
// If graceful close takes >8s, force-exit to avoid being killed undrained
|
||||||
|
setTimeout(() => {
|
||||||
|
console.error("Graceful close timeout — forcing exit");
|
||||||
|
process.exit(1);
|
||||||
|
}, 8_000);
|
||||||
server.close(() => {
|
server.close(() => {
|
||||||
console.log("HTTP server closed");
|
console.log("HTTP server closed");
|
||||||
process.exit(0);
|
process.exit(0);
|
||||||
});
|
});
|
||||||
setTimeout(() => {
|
|
||||||
console.error("Forced shutdown after timeout");
|
|
||||||
process.exit(1);
|
|
||||||
}, 10_000);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
process.on("SIGTERM", shutdown);
|
process.on("SIGTERM", shutdown);
|
||||||
|
|||||||
+3
-1
@@ -186,7 +186,9 @@ export async function initAuth(): Promise<void> {
|
|||||||
const discoveryUrlStr = `${providerConfig.issuerUrl}/.well-known/openid-configuration`;
|
const discoveryUrlStr = `${providerConfig.issuerUrl}/.well-known/openid-configuration`;
|
||||||
let oidcConfig: Record<string, string> = {};
|
let oidcConfig: Record<string, string> = {};
|
||||||
try {
|
try {
|
||||||
const discoveryRes = await fetch(discoveryUrlStr);
|
const discoveryRes = await fetch(discoveryUrlStr, {
|
||||||
|
signal: AbortSignal.timeout(5000),
|
||||||
|
});
|
||||||
if (discoveryRes.ok) {
|
if (discoveryRes.ok) {
|
||||||
const discovery = await discoveryRes.json() as {
|
const discovery = await discoveryRes.json() as {
|
||||||
authorization_endpoint?: string;
|
authorization_endpoint?: string;
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ if (process.env.AUTH_DISABLED === "true") {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const authMiddleware: MiddlewareHandler = async (c, next) => {
|
export const authMiddleware: MiddlewareHandler = async (c, next) => {
|
||||||
if (c.req.path.startsWith("/api/auth/")) {
|
if (c.req.path.startsWith("/api/auth/") || c.req.path === "/api/health") {
|
||||||
await next();
|
await next();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|||||||
+43
-1
@@ -1,5 +1,5 @@
|
|||||||
import type { MiddlewareHandler } from "hono";
|
import type { MiddlewareHandler } from "hono";
|
||||||
import { and, eq, getDb, sql, staff } from "@groombook/db";
|
import { and, eq, getDb, sql, staff, account } from "@groombook/db";
|
||||||
|
|
||||||
export type StaffRole = "groomer" | "receptionist" | "manager";
|
export type StaffRole = "groomer" | "receptionist" | "manager";
|
||||||
export type StaffRow = typeof staff.$inferSelect;
|
export type StaffRow = typeof staff.$inferSelect;
|
||||||
@@ -110,6 +110,48 @@ export const resolveStaffMiddleware: MiddlewareHandler<AppEnv> = async (
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Auto-provision for OIDC users: check if jwt.sub has an OAuth/OIDC account
|
||||||
|
// (e.g. authentik). If so, create a groomer staff record on the fly.
|
||||||
|
if (jwt.email) {
|
||||||
|
const [oidcAccount] = await db
|
||||||
|
.select({ id: account.id })
|
||||||
|
.from(account)
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq(account.userId, jwt.sub),
|
||||||
|
sql`${account.providerId} IN ('authentik', 'google', 'github')`
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.limit(1);
|
||||||
|
|
||||||
|
if (oidcAccount) {
|
||||||
|
// Derive name: prefer jwt.name, fall back to email prefix, then "Unknown"
|
||||||
|
const name =
|
||||||
|
jwt.name?.trim() ||
|
||||||
|
(jwt.email ? jwt.email.split("@")[0] : "Unknown");
|
||||||
|
|
||||||
|
const [newStaff] = await db
|
||||||
|
.insert(staff)
|
||||||
|
.values({
|
||||||
|
userId: jwt.sub,
|
||||||
|
email: jwt.email ?? "",
|
||||||
|
name,
|
||||||
|
role: "groomer",
|
||||||
|
isSuperUser: false,
|
||||||
|
active: true,
|
||||||
|
})
|
||||||
|
.returning();
|
||||||
|
|
||||||
|
console.log(
|
||||||
|
`[rbac] auto-provisioned staff record for OIDC user: ${jwt.sub} -> staff:${newStaff.id} (${name})`
|
||||||
|
);
|
||||||
|
c.set("staff", newStaff);
|
||||||
|
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
|
||||||
|
|||||||
@@ -36,6 +36,19 @@ const DEMO_PET = {
|
|||||||
weightKg: "30.00",
|
weightKg: "30.00",
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const UAT_CLIENT = {
|
||||||
|
name: "UAT Customer",
|
||||||
|
email: "uat-customer@groombook.dev",
|
||||||
|
phone: "555-0100",
|
||||||
|
address: "1 UAT Lane, Test City, CA 90210",
|
||||||
|
status: "active" as const,
|
||||||
|
};
|
||||||
|
|
||||||
|
const UAT_PETS = [
|
||||||
|
{ name: "Bella", species: "Dog", breed: "Poodle", coatType: "curly", weightKg: "20.00" },
|
||||||
|
{ name: "Max", species: "Dog", breed: "Labrador Retriever", coatType: "smooth", weightKg: "30.00" },
|
||||||
|
];
|
||||||
|
|
||||||
const DEMO_SERVICES = [
|
const DEMO_SERVICES = [
|
||||||
{ id: "b0000001-0000-0000-0000-000000000001", name: "Bath & Brush", description: "Full bath, blow-dry, brush out, and ear cleaning", basePriceCents: 4500, durationMinutes: 45 },
|
{ id: "b0000001-0000-0000-0000-000000000001", name: "Bath & Brush", description: "Full bath, blow-dry, brush out, and ear cleaning", basePriceCents: 4500, durationMinutes: 45 },
|
||||||
{ id: "b0000001-0000-0000-0000-000000000002", name: "Full Groom — Small", description: "Complete grooming for dogs under 25 lbs", basePriceCents: 6500, durationMinutes: 60 },
|
{ id: "b0000001-0000-0000-0000-000000000002", name: "Full Groom — Small", description: "Complete grooming for dogs under 25 lbs", basePriceCents: 6500, durationMinutes: 60 },
|
||||||
@@ -43,7 +56,7 @@ const DEMO_SERVICES = [
|
|||||||
{ id: "b0000001-0000-0000-0000-000000000004", name: "Nail Trim", description: "Nail clipping and filing", basePriceCents: 1500, durationMinutes: 15 },
|
{ id: "b0000001-0000-0000-0000-000000000004", name: "Nail Trim", description: "Nail clipping and filing", basePriceCents: 1500, durationMinutes: 15 },
|
||||||
];
|
];
|
||||||
|
|
||||||
adminSeedRouter.post("/seed", async (c) => {
|
adminSeedRouter.post("/", async (c) => {
|
||||||
// Refuse to run when AUTH_DISABLED — dev environments use direct-DB seeding
|
// Refuse to run when AUTH_DISABLED — dev environments use direct-DB seeding
|
||||||
if (process.env.AUTH_DISABLED === "true") {
|
if (process.env.AUTH_DISABLED === "true") {
|
||||||
return c.json(
|
return c.json(
|
||||||
@@ -128,6 +141,51 @@ adminSeedRouter.post("/seed", async (c) => {
|
|||||||
results.push(`Created pet '${DEMO_PET.name}' for Demo Client (id: ${created!.id})`);
|
results.push(`Created pet '${DEMO_PET.name}' for Demo Client (id: ${created!.id})`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Client: UAT Customer ──────────────────────────────────────────────────
|
||||||
|
const [existingUatClient] = await db
|
||||||
|
.select()
|
||||||
|
.from(clients)
|
||||||
|
.where(eq(clients.email, UAT_CLIENT.email));
|
||||||
|
|
||||||
|
let uatClientId: string;
|
||||||
|
if (existingUatClient) {
|
||||||
|
uatClientId = existingUatClient.id;
|
||||||
|
results.push(`Client '${UAT_CLIENT.name}' already exists (id: ${uatClientId})`);
|
||||||
|
} else {
|
||||||
|
const [created] = await db.insert(clients).values(UAT_CLIENT).returning();
|
||||||
|
uatClientId = created!.id;
|
||||||
|
results.push(`Created client '${UAT_CLIENT.name}' (id: ${uatClientId})`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Pets: UAT Customer's Pets ─────────────────────────────────────────────
|
||||||
|
const existingUatPets = await db
|
||||||
|
.select()
|
||||||
|
.from(pets)
|
||||||
|
.where(eq(pets.clientId, uatClientId));
|
||||||
|
|
||||||
|
for (const uatPet of UAT_PETS) {
|
||||||
|
const existing = existingUatPets.find(
|
||||||
|
(p) => p.name === uatPet.name && p.species === uatPet.species
|
||||||
|
);
|
||||||
|
if (existing) {
|
||||||
|
results.push(`Pet '${uatPet.name}' already exists for UAT Customer (id: ${existing.id})`);
|
||||||
|
} else {
|
||||||
|
const [created] = await db
|
||||||
|
.insert(pets)
|
||||||
|
.values({
|
||||||
|
clientId: uatClientId,
|
||||||
|
name: uatPet.name,
|
||||||
|
species: uatPet.species,
|
||||||
|
breed: uatPet.breed,
|
||||||
|
coatType: uatPet.coatType as any,
|
||||||
|
weightKg: uatPet.weightKg,
|
||||||
|
dateOfBirth: new Date("2019-01-01T00:00:00Z"),
|
||||||
|
})
|
||||||
|
.returning();
|
||||||
|
results.push(`Created pet '${uatPet.name}' for UAT Customer (id: ${created!.id})`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return c.json({
|
return c.json({
|
||||||
message: "Seed complete",
|
message: "Seed complete",
|
||||||
details: results,
|
details: results,
|
||||||
|
|||||||
Reference in New Issue
Block a user