Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/pr-web.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ jobs:
- name: Install dependencies
run: bun install --frozen-lockfile

- name: Generate API clients
run: bun run openapi-ts

- name: Lint
run: bun run lint

Expand Down
39 changes: 39 additions & 0 deletions apps/web/src/lib/api-interceptors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/**
* Request/response interceptors for the generated HeyAPI clients.
*
* Attaches the `Vellum-Organization-Id` header and `X-CSRFToken` header
* to all outbound requests. Import this module for its side effects in
* the app entrypoint (`main.tsx`) so interceptors are installed before
* any API call fires.
*
* Reference: https://heyapi.dev/openapi-ts/clients/fetch#interceptors
*/
import { client as authClient } from "@/generated/auth/client.gen.js";
import { client as platformClient } from "@/generated/api/client.gen.js";
Comment on lines +11 to +12
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Add generation before importing gitignored HeyAPI clients

These imports make a fresh checkout depend on apps/web/src/generated/**, but that directory is gitignored (apps/web/.gitignore) and there are no tracked generated files (git ls-files apps/web/src/generated/** returns 0). I also checked the web PR workflow: after install it runs only lint, bun run typecheck, and build, with no bun run openapi-ts step, so CI and local bun run typecheck/bun run build will fail with missing @/generated/... modules unless the clients are generated as part of install/build/CI or committed despite the ignore.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 8a79627a4b — added bun run openapi-ts codegen step to pr-web.yaml before lint/typecheck/build. The OpenAPI specs are committed at apps/web/openapi-schemas/, so CI can regenerate the clients from them.

import { ensureCsrfCookie, getCsrfToken } from "@/lib/auth/csrf.js";
import { getActiveOrganizationIdForRequests } from "@/lib/organization/organization-state.js";

const MUTATING_METHODS = new Set(["POST", "PUT", "PATCH", "DELETE"]);

async function requestInterceptor(request: Request) {
const newRequest = new Request(request);
const organizationId = getActiveOrganizationIdForRequests();

if (organizationId) {
newRequest.headers.set("Vellum-Organization-Id", organizationId);
}

if (MUTATING_METHODS.has(request.method)) {
await ensureCsrfCookie();
const csrfToken = getCsrfToken();
if (csrfToken) {
newRequest.headers.set("X-CSRFToken", csrfToken);
}
}

return newRequest;
}

for (const apiClient of [authClient, platformClient]) {
apiClient.interceptors.request.use(requestInterceptor);
}
118 changes: 118 additions & 0 deletions apps/web/src/lib/auth/allauth-client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
/**
* Thin adapter around the generated allauth HeyAPI SDK.
*
* Normalizes responses into a discriminated union so callers
* don't have to scatter null-checks across every call site.
*
* Reference: https://docs.allauth.org/en/latest/headless/openapi-specification/
*/
import type {
Authenticated,
EmailAddress,
Flow,
ProviderAccount,
} from "@/generated/auth/types.gen.js";
import {
deleteAllauthByClientV1AuthSession,
getAllauthByClientV1AuthSession,
getAllauthByClientV1AuthProviderSignup,
postAllauthByClientV1AuthProviderSignup,
} from "@/generated/auth/sdk.gen.js";

export type AllauthResult<T = unknown> =
| { ok: true; data: T }
| {
ok: false;
status?: number;
errors: Array<{ code: string; message: string; param?: string }>;
flows?: Array<Flow>;
};

export function isConflict(result: AllauthResult): boolean {
return !result.ok && result.status === 409;
}

function errorResult(
error: unknown,
status?: number,
): AllauthResult<never> {
const err = error as Record<string, unknown> | undefined;
if (err && Array.isArray(err.errors)) {
return { ok: false, status, errors: err.errors };
}
const data = err?.data as Record<string, unknown> | undefined;
if (data && Array.isArray(data.flows)) {
return { ok: false, status, errors: [], flows: data.flows as Array<Flow> };
}
return { ok: false, status, errors: [] };
}

export async function getSession(): Promise<AllauthResult<Authenticated>> {
const { data, error, response } = await getAllauthByClientV1AuthSession({
path: { client: "browser" },
});

if (data) {
return { ok: true, data: data.data };
}

return errorResult(error, response?.status);
}

export async function logout(): Promise<AllauthResult> {
const { data, error, response } =
await deleteAllauthByClientV1AuthSession({
path: { client: "browser" },
});

if (data) {
return { ok: true, data };
}

if (response?.status === 401) {
return { ok: true, data: {} };
}

return errorResult(error, response?.status);
}

export interface ProviderSignupContext {
account: ProviderAccount;
user: Authenticated["user"];
email: Array<EmailAddress>;
}

export async function getProviderSignup(): Promise<
AllauthResult<ProviderSignupContext>
> {
const { data, error, response } =
await getAllauthByClientV1AuthProviderSignup({
path: { client: "browser" },
});

if (data) {
return { ok: true, data: data.data as unknown as ProviderSignupContext };
}

return errorResult(error, response?.status);
}

export async function submitProviderSignup({
email,
username,
}: {
email: string;
username: string;
}): Promise<AllauthResult<Authenticated>> {
const { data, error, response } =
await postAllauthByClientV1AuthProviderSignup({
path: { client: "browser" },
body: { email, username },
});

if (data) {
return { ok: true, data: data.data };
}

return errorResult(error, response?.status);
}
202 changes: 202 additions & 0 deletions apps/web/src/lib/auth/auth-provider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,202 @@
/**
* Authentication context for the web SPA.
*
* Probes the Django/allauth session on mount, re-validates on window focus
* and visibility changes, and synchronizes logout across tabs via
* BroadcastChannel.
*
* Reference: https://docs.allauth.org/en/latest/headless/openapi-specification/
*/
import {
createContext,
useCallback,
useContext,
useEffect,
useRef,
useState,
type ReactNode,
} from "react";

import {
getSession,
logout as allauthLogout,
} from "@/lib/auth/allauth-client.js";
import { setActiveOrganizationIdForRequests } from "@/lib/organization/organization-state.js";

export interface AuthSessionUser {
id?: string;
username?: string;
email?: string;
is_staff?: boolean;
first_name?: string;
last_name?: string;
}

function getAuthSessionUserId(user: AuthSessionUser | null): string | null {
return user?.id ?? user?.email ?? user?.username ?? null;
}

function syncOrganizationStateForUser(
previousUser: AuthSessionUser | null,
nextUser: AuthSessionUser | null,
): void {
const previousUserId = getAuthSessionUserId(previousUser);
const nextUserId = getAuthSessionUserId(nextUser);

if (!nextUserId || (previousUserId && previousUserId !== nextUserId)) {
setActiveOrganizationIdForRequests(null);
}
}

interface AuthContextType {
isLoggedIn: boolean;
isLoading: boolean;
isAdmin: boolean;
userId: string | null;
username: string | null;
email: string | null;
firstName: string;
lastName: string;
logout: () => Promise<void>;
refreshSession: () => Promise<boolean>;
}

const AuthContext = createContext<AuthContextType | null>(null);

interface AuthProviderProps {
children: ReactNode;
}

export function AuthProvider({ children }: AuthProviderProps) {
const [isLoggedIn, setIsLoggedIn] = useState(false);
const [isLoading, setIsLoading] = useState(true);
const [userId, setUserId] = useState<string | null>(null);
const [username, setUsername] = useState<string | null>(null);
const [email, setEmail] = useState<string | null>(null);
const [isAdmin, setIsAdmin] = useState(false);
const [firstName, setFirstName] = useState("");
const [lastName, setLastName] = useState("");
const previousUserRef = useRef<AuthSessionUser | null>(null);

const setUser = useCallback(
(user: AuthSessionUser | null) => {
syncOrganizationStateForUser(previousUserRef.current, user);
previousUserRef.current = user;

setIsLoggedIn(!!user);
setUserId(getAuthSessionUserId(user));
setUsername(user?.username ?? null);
setEmail(user?.email ?? null);
setIsAdmin(user?.is_staff ?? false);
setFirstName(user?.first_name ?? "");
setLastName(user?.last_name ?? "");
},
[],
);

const refreshSession = useCallback(async (): Promise<boolean> => {
const result = await getSession();
if (result.ok && result.data.user) {
setUser(result.data.user);
return true;
}

setUser(null);
return false;
}, [setUser]);

useEffect(() => {
let cancelled = false;
async function initSession() {
const result = await getSession();
if (cancelled) return;
if (result.ok && result.data.user) {
setUser(result.data.user);
setIsLoading(false);
return;
}

setUser(null);
setIsLoading(false);
}
initSession().catch((err) => {
if (cancelled) return;
console.error("auth.initSession failed", err);
setIsLoading(false);
});
return () => {
cancelled = true;
};
}, [setUser]);

useEffect(() => {
const safeRefresh = () =>
refreshSession().catch((err) =>
console.warn("auth.refreshSession failed", err),
);
const onFocus = () => safeRefresh();
const onVisibilityChange = () => {
if (document.visibilityState === "visible") safeRefresh();
};
window.addEventListener("focus", onFocus);
document.addEventListener("visibilitychange", onVisibilityChange);
return () => {
window.removeEventListener("focus", onFocus);
document.removeEventListener("visibilitychange", onVisibilityChange);
};
}, [refreshSession]);

const channelRef = useRef<BroadcastChannel | null>(null);
useEffect(() => {
if (typeof BroadcastChannel === "undefined") return;
const channel = new BroadcastChannel("auth");
channelRef.current = channel;
channel.onmessage = () => {
refreshSession();
};
return () => {
channel.close();
channelRef.current = null;
};
}, [refreshSession]);

const broadcastAuthChange = useCallback(() => {
channelRef.current?.postMessage("auth-changed");
}, []);

const logout = useCallback(async () => {
try {
await allauthLogout();
} finally {
setUser(null);
broadcastAuthChange();
}
}, [setUser, broadcastAuthChange]);

return (
<AuthContext
value={{
isLoggedIn,
isLoading,
isAdmin,
userId,
username,
email,
firstName,
lastName,
logout,
refreshSession,
}}
>
{children}
</AuthContext>
);
}

export function useAuth(): AuthContextType {
const context = useContext(AuthContext);
if (!context) {
throw new Error("useAuth must be used within an AuthProvider");
}
return context;
}
Loading