Compare commits

..

2 Commits

Author SHA1 Message Date
RaymondVerhoef
89d3395a62 feat: enhance OIDC configuration for Azure login and improve error handling in API responses
All checks were successful
On Push to Main / test (push) Successful in 56s
On Push to Main / publish (push) Successful in 1m24s
On Push to Main / deploy-dev (push) Successful in 2m58s
2026-07-11 10:19:54 +02:00
RaymondVerhoef
d5191073f0 feat: migrate team_members to OIDC-based auth collection and update docker-compose environment configuration
All checks were successful
On Push to Main / test (push) Successful in 57s
On Push to Main / publish (push) Successful in 1m16s
On Push to Main / deploy-dev (push) Successful in 3m0s
2026-06-25 18:05:39 +02:00
3 changed files with 66 additions and 56 deletions

View File

@@ -46,6 +46,13 @@
} }
handle_errors { handle_errors {
# Don't mask API errors with the SPA shell — return a proper
# JSON error so the frontend can display a meaningful message.
@api path /api/*
respond @api `{"code":{err.status_code},"message":"Backend unavailable"}` {err.status_code} {
Content-Type application/json
}
rewrite * /index.html rewrite * /index.html
file_server file_server
} }

View File

@@ -12,7 +12,11 @@ services:
container_name: pocketbase-learning container_name: pocketbase-learning
restart: unless-stopped restart: unless-stopped
working_dir: /pb working_dir: /pb
env_file:
- .env.local
command: ["serve", "--http=0.0.0.0:8090", "--dir=/pb/pb_data", "--migrationsDir=/pb/pb_migrations"] command: ["serve", "--http=0.0.0.0:8090", "--dir=/pb/pb_data", "--migrationsDir=/pb/pb_migrations"]
ports:
- "8090:8090"
volumes: volumes:
- pb_data:/pb/pb_data - pb_data:/pb/pb_data
- ./pb_migrations:/pb/pb_migrations - ./pb_migrations:/pb/pb_migrations

View File

@@ -19,42 +19,26 @@
// re-configure the provider from the PocketBase admin UI (Settings → Auth // re-configure the provider from the PocketBase admin UI (Settings → Auth
// providers) or ship a follow-up migration. // providers) or ship a follow-up migration.
migrate((app) => { migrate((app) => {
// 1. Detach relation fields that point at team_members. PocketBase refuses to // 1. Drop the old PIN-based collection (takes the PIN records with it).
// delete a collection that other collections relate to, so before we can // Other collections (micro_learning_completions, theme_session_completions)
// drop the old PIN-based team_members we convert those relations into plain // have relation fields pointing to the old team_members — PocketBase refuses
// text fields (the id is stored as text — consistent with how user_id is // to delete a referenced collection. Remove those relation fields first,
// stored in test_results / on_demand_attempts). Per-user progress is reset // delete the old collection, create the new auth collection, then re-add
// anyway, so dropping the FK constraint here is acceptable. // the relation fields pointing to the new collection.
const deps = [ const relDeps = [
{ name: "micro_learning_completions", relId: "rel_team_member_id", textId: "txt_mlc_team_member" }, { collection: "micro_learning_completions", fieldId: "rel_team_member_id", fieldName: "team_member_id" },
{ name: "theme_session_completions", relId: "rel_tsc_team_member", textId: "txt_tsc_team_member" }, { collection: "theme_session_completions", fieldId: "rel_tsc_team_member", fieldName: "team_member_id" },
]; ];
for (const dep of deps) {
let c; // Remove blocking relation fields so the old collection can be deleted.
try { c = app.findCollectionByNameOrId(dep.name); } catch (_) { continue; } for (const dep of relDeps) {
// Drop any index that references the team_member_id column. try {
c.indexes = (c.indexes || []).filter((idx) => idx.indexOf("team_member_id") === -1); const col = app.findCollectionByNameOrId(dep.collection);
// Replace the relation field with a text field of the same name. col.fields.removeById(dep.fieldId);
c.fields.removeById(dep.relId); app.save(col);
c.fields.add(new Field({ } catch (_) { /* collection doesn't exist yet — skip */ }
type: "text",
id: dep.textId,
name: "team_member_id",
required: false,
min: 0,
max: 0,
}));
app.save(c);
} }
// Recreate the unique (team_member_id, session_week) guard on the text column.
try {
const tsc = app.findCollectionByNameOrId("theme_session_completions");
tsc.indexes.push("CREATE UNIQUE INDEX `idx_theme_session_completions_user_week` ON `theme_session_completions` (`team_member_id`, `session_week`)");
app.save(tsc);
} catch (_) { /* collection missing — skip */ }
// 2. Drop the old PIN-based team_members (now unreferenced).
try { try {
const old = app.findCollectionByNameOrId("team_members"); const old = app.findCollectionByNameOrId("team_members");
app.delete(old); app.delete(old);
@@ -62,29 +46,15 @@ migrate((app) => {
// Collection did not exist — nothing to drop. // Collection did not exist — nothing to drop.
} }
const tenant = $os.getenv("ENTRA_TENANT_ID") || "common"; const tenant = $os.getenv("ENTRA_TENANT_ID") || "common";
const clientId = $os.getenv("ENTRA_CLIENT_ID"); const clientId = $os.getenv("ENTRA_CLIENT_ID");
const clientSecret = $os.getenv("ENTRA_CLIENT_SECRET"); const clientSecret = $os.getenv("ENTRA_CLIENT_SECRET");
// Only configure the OIDC provider when credentials are actually present. const hasOidc = !!(clientId && clientSecret);
// PocketBase rejects an enabled OAuth2 provider with an empty clientId / if (!hasOidc) {
// clientSecret, which would abort this migration and prevent PocketBase from console.log("WARN: ENTRA_CLIENT_ID / ENTRA_CLIENT_SECRET not set — OIDC provider will not be configured. " +
// starting at all (502 on every /api call). When the secrets are absent the "Set the env vars and re-apply the migration to enable Azure login.");
// collection is created without a provider; once the ENTRA_* secrets are set, }
// configure the provider via the PocketBase admin UI
// (Settings → Auth providers → OIDC) or re-apply this migration.
const oidcProviders = (clientId && clientSecret) ? [
{
name: "oidc",
clientId: clientId,
clientSecret: clientSecret,
authURL: "https://login.microsoftonline.com/" + tenant + "/oauth2/v2.0/authorize",
tokenURL: "https://login.microsoftonline.com/" + tenant + "/oauth2/v2.0/token",
userInfoURL: "https://graph.microsoft.com/oidc/userinfo",
displayName: "Microsoft",
pkce: true,
},
] : [];
// 2. Recreate `team_members` as an auth collection (same name → all existing // 2. Recreate `team_members` as an auth collection (same name → all existing
// `user_id` references in test_results, on_demand_attempts, // `user_id` references in test_results, on_demand_attempts,
@@ -113,7 +83,7 @@ migrate((app) => {
mfa: { enabled: false, duration: 600, rule: "" }, mfa: { enabled: false, duration: 600, rule: "" },
oauth2: { oauth2: {
enabled: oidcProviders.length > 0, enabled: hasOidc,
// Map the OIDC userinfo claims onto our fields. // Map the OIDC userinfo claims onto our fields.
mappedFields: { mappedFields: {
id: "", id: "",
@@ -121,7 +91,18 @@ migrate((app) => {
username: "", username: "",
avatarURL: "", avatarURL: "",
}, },
providers: oidcProviders, providers: hasOidc ? [
{
name: "oidc",
clientId: clientId,
clientSecret: clientSecret,
authURL: "https://login.microsoftonline.com/" + tenant + "/oauth2/v2.0/authorize",
tokenURL: "https://login.microsoftonline.com/" + tenant + "/oauth2/v2.0/token",
userInfoURL: "https://graph.microsoft.com/oidc/userinfo",
displayName: "Microsoft",
pkce: true,
},
] : [],
}, },
fields: [ fields: [
@@ -277,6 +258,24 @@ migrate((app) => {
}); });
app.save(collection); app.save(collection);
// 3. Re-add the relation fields pointing to the new auth collection.
for (const dep of relDeps) {
try {
const col = app.findCollectionByNameOrId(dep.collection);
const newField = new Field({
id: dep.fieldId,
name: dep.fieldName,
type: "relation",
required: true,
collectionId: collection.id,
cascadeDelete: true,
maxSelect: 1,
});
col.fields.add(newField);
app.save(col);
} catch (_) { /* collection doesn't exist — skip */ }
}
}, (app) => { }, (app) => {
// Down: drop the auth collection and recreate the original PIN-based base // Down: drop the auth collection and recreate the original PIN-based base
// collection (without data — the original records are gone). // collection (without data — the original records are gone).