| | | 1 | | import { UserManager, WebStorageStateStore } from "oidc-client-ts"; |
| | | 2 | | |
| | | 3 | | // oidc-client-ts v3 defaults userStore to localStorage; we override to sessionStorage so |
| | | 4 | | // tokens are not shared across tabs and are cleared when the browser session ends. |
| | 0 | 5 | | const sessionStore = () => new WebStorageStateStore({ store: window.sessionStorage }); |
| | | 6 | | |
| | 0 | 7 | | export const AUTH_COOKIE = "clutterstock_auth"; |
| | | 8 | | |
| | 0 | 9 | | function setAuthCookie(token: string, expiresAt: number): void { |
| | 0 | 10 | | const expires = new Date(expiresAt * 1000).toUTCString(); |
| | 0 | 11 | | document.cookie = `${AUTH_COOKIE}=${encodeURIComponent(token)}; expires=${expires}; path=/; SameSite=Lax`; |
| | | 12 | | } |
| | | 13 | | |
| | 0 | 14 | | function clearAuthCookie(): void { |
| | 0 | 15 | | document.cookie = `${AUTH_COOKIE}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; SameSite=Lax`; |
| | | 16 | | } |
| | | 17 | | |
| | | 18 | | let _manager: UserManager | undefined; |
| | | 19 | | |
| | 0 | 20 | | export function getUserManager(): UserManager { |
| | 0 | 21 | | if (!_manager) { |
| | 0 | 22 | | _manager = new UserManager({ |
| | | 23 | | authority: import.meta.env.VITE_OIDC_AUTHORITY ?? "", |
| | | 24 | | client_id: import.meta.env.VITE_OIDC_CLIENT_ID ?? "", |
| | | 25 | | redirect_uri: `${window.location.origin}/auth/callback`, |
| | | 26 | | scope: "openid profile email groups offline_access", |
| | | 27 | | response_type: "code", |
| | | 28 | | automaticSilentRenew: true, |
| | | 29 | | loadUserInfo: true, |
| | | 30 | | userStore: sessionStore(), |
| | | 31 | | }); |
| | | 32 | | |
| | 0 | 33 | | _manager.events.addUserLoaded((user) => { |
| | 0 | 34 | | if (user.expires_at) setAuthCookie(user.access_token, user.expires_at); |
| | | 35 | | }); |
| | | 36 | | |
| | 0 | 37 | | _manager.events.addUserUnloaded(clearAuthCookie); |
| | 0 | 38 | | _manager.events.addUserSignedOut(clearAuthCookie); |
| | | 39 | | } |
| | 0 | 40 | | return _manager; |
| | | 41 | | } |
| | | 42 | | |
| | 0 | 43 | | export async function initAuth(): Promise<void> { |
| | 0 | 44 | | const mgr = getUserManager(); |
| | 0 | 45 | | const user = await mgr.getUser(); |
| | 0 | 46 | | if (user && !user.expired && user.expires_at) { |
| | 0 | 47 | | setAuthCookie(user.access_token, user.expires_at); |
| | | 48 | | } |
| | | 49 | | } |