-
Notifications
You must be signed in to change notification settings - Fork 88
feat(web): port provider stack (Auth, Organization, Feature Flags) from platform repo #31099
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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"; | ||
| 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); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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 nobun run openapi-tsstep, so CI and localbun run typecheck/bun run buildwill fail with missing@/generated/...modules unless the clients are generated as part of install/build/CI or committed despite the ignore.Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fixed in
8a79627a4b— addedbun run openapi-tscodegen step topr-web.yamlbefore lint/typecheck/build. The OpenAPI specs are committed atapps/web/openapi-schemas/, so CI can regenerate the clients from them.