feat: Azure (Entra ID) login as user login (#16)

Replaces the client-side PIN login with real authentication against Azure
Entra ID via PocketBase's built-in OAuth2 (OIDC) flow. Every Azure user is
auto-provisioned as a team_member on first login.

- pb_migrations: team_members becomes a PocketBase auth collection (OIDC
  provider configured from env); all collections require @request.auth.id
- pb_hooks: provisioning of role (ENTRA_ADMIN_EMAILS allow-list) and
  enrollment_status, with admin-role re-sync on every login
- frontend: "Sign in with Microsoft" login, pb.authStore-based session,
  TeamManager manages roster/roles (no PIN/manual create)
- infra: Entra env wiring + pb_hooks mount for dev (Labs) and prod
- src/lib/azureAuth.js + tests for the canonical role/allow-list logic
- docs/auth-spec.md

Knowledge base, generated tests and micro-learnings are left untouched.
Existing PIN users are dropped (no migration required, per sign-off).

Closes #16

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
RaymondVerhoef
2026-06-23 11:41:08 +02:00
parent 5f34a6f825
commit 3af105bccd
17 changed files with 734 additions and 170 deletions

View File

@@ -1,6 +1,7 @@
import { createContext, useContext, useReducer, useEffect } from 'react';
import * as db from '../lib/db';
import { pb } from '../lib/pb';
import { OIDC_PROVIDER } from '../lib/azureAuth';
import { getPersonalWeekNumber } from '../lib/curriculumService';
const AppContext = createContext();
@@ -50,44 +51,40 @@ export function AppProvider({ children }) {
useEffect(() => {
const loadState = async () => {
let members = await db.getTeamMembers();
if (!members || members.length === 0) {
// Restore the session from PocketBase's persistent auth store. The token
// is kept in localStorage by the SDK; authRefresh verifies it is still
// valid (and that the Entra account hasn't been revoked) and returns the
// up-to-date record.
if (pb.authStore.isValid && pb.authStore.record?.collectionName === 'team_members') {
try {
const created = await db.addTeamMember({ name: 'Admin', role: 'admin', pin: '0000' });
members = [created];
} catch (e) {
console.warn('[AppContext] Could not auto-create admin user:', e.message,
'— Run scripts/setup-pb-collections.mjs to configure the database.');
}
}
const sessionUserId = sessionStorage.getItem('respellion_session');
if (sessionUserId) {
const user = members.find(u => u.id === sessionUserId);
if (user) {
dispatch({ type: 'LOGIN', payload: user });
const { record } = await pb.collection('team_members').authRefresh();
dispatch({ type: 'LOGIN', payload: record });
} catch {
// Token rejected (expired / account revoked) — drop the session.
pb.authStore.clear();
}
}
// The team list (leaderboard, dashboard) requires authentication now, so
// only load it once we have a valid session.
const members = pb.authStore.isValid ? await db.getTeamMembers() : [];
dispatch({ type: 'INIT_APP', payload: { users: members } });
};
loadState().catch(console.error);
}, []);
const login = (userId, pin) => {
const user = state.users.find(u => u.id === userId && u.pin === pin);
if (user) {
sessionStorage.setItem('respellion_session', user.id);
dispatch({ type: 'LOGIN', payload: user });
return true;
}
return false;
// Start the Entra (OIDC) login flow. PocketBase opens the provider popup,
// handles the token exchange server-side, and auto-provisions the record on
// first login (see pb_hooks/team_members.pb.js).
const loginWithAzure = async () => {
const authData = await pb.collection('team_members').authWithOAuth2({ provider: OIDC_PROVIDER });
dispatch({ type: 'LOGIN', payload: authData.record });
return authData.record;
};
const logout = () => {
sessionStorage.removeItem('respellion_session');
pb.authStore.clear();
dispatch({ type: 'LOGOUT' });
};
@@ -107,7 +104,7 @@ export function AppProvider({ children }) {
};
return (
<AppContext.Provider value={{ state, dispatch, login, logout, enrollCurrentUser }}>
<AppContext.Provider value={{ state, dispatch, loginWithAzure, logout, enrollCurrentUser }}>
{children}
</AppContext.Provider>
);