AuthContext.tsx 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. import React, { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
  2. import { api, getAuthToken, setAuthToken } from '../api/client';
  3. import type { LoginResponse, Permission, UserResponse } from '../api/client';
  4. interface AuthContextType {
  5. user: UserResponse | null;
  6. authEnabled: boolean;
  7. requiresSetup: boolean;
  8. loading: boolean;
  9. isAdmin: boolean;
  10. /** Login with username/password. Returns LoginResponse (may include requires_2fa). */
  11. login: (username: string, password: string) => Promise<LoginResponse>;
  12. /** Finalise login after 2FA or OIDC — store token and set user directly. */
  13. loginWithToken: (token: string, user: UserResponse) => void;
  14. logout: () => void;
  15. refreshUser: () => Promise<void>;
  16. refreshAuth: () => Promise<void>;
  17. hasPermission: (permission: Permission) => boolean;
  18. hasAnyPermission: (...permissions: Permission[]) => boolean;
  19. hasAllPermissions: (...permissions: Permission[]) => boolean;
  20. canModify: (resource: 'queue' | 'archives' | 'library', action: 'update' | 'delete' | 'reprint', createdById: number | null | undefined) => boolean;
  21. }
  22. const AuthContext = createContext<AuthContextType | undefined>(undefined);
  23. export function AuthProvider({ children }: { children: React.ReactNode }) {
  24. const [user, setUser] = useState<UserResponse | null>(null);
  25. const [authEnabled, setAuthEnabled] = useState(false);
  26. const [requiresSetup, setRequiresSetup] = useState(false);
  27. const [loading, setLoading] = useState(true);
  28. const hasRedirectedRef = useRef(false);
  29. const mountedRef = useRef(true);
  30. const checkAuthStatus = async () => {
  31. try {
  32. // Bootstrap: if URL has ?token= param, store it session-only first and
  33. // strip it from the URL. Allows SpoolBuddy kiosk to pass an API key via
  34. // URL on first load. Persistence to localStorage is deferred until the
  35. // token has been verified by the server (L-4: prevents session fixation
  36. // where an attacker-crafted URL immediately persists a forged/stolen token).
  37. const urlParams = new URLSearchParams(window.location.search);
  38. const urlToken = urlParams.get('token');
  39. if (urlToken) {
  40. setAuthToken(urlToken, false); // session-only until server confirms it's valid
  41. urlParams.delete('token');
  42. const cleanSearch = urlParams.toString();
  43. const cleanUrl = window.location.pathname
  44. + (cleanSearch ? `?${cleanSearch}` : '')
  45. + window.location.hash;
  46. window.history.replaceState({}, '', cleanUrl);
  47. }
  48. const status = await api.getAuthStatus();
  49. if (!mountedRef.current) return;
  50. setAuthEnabled(status.auth_enabled);
  51. setRequiresSetup(status.requires_setup);
  52. if (status.auth_enabled) {
  53. const token = getAuthToken();
  54. if (token) {
  55. try {
  56. const currentUser = await api.getCurrentUser();
  57. if (!mountedRef.current) return;
  58. setUser(currentUser);
  59. // Persist kiosk token only after the server confirms it is valid.
  60. if (urlToken && token === urlToken) {
  61. setAuthToken(urlToken, true);
  62. }
  63. } catch {
  64. // Token invalid, clear it (removes from both sessionStorage and localStorage)
  65. setAuthToken(null);
  66. if (!mountedRef.current) return;
  67. setUser(null);
  68. }
  69. } else {
  70. setUser(null);
  71. }
  72. } else {
  73. // Auth not enabled, allow access
  74. setUser(null);
  75. }
  76. } catch {
  77. if (!mountedRef.current) return;
  78. setAuthEnabled(false);
  79. setUser(null);
  80. } finally {
  81. if (mountedRef.current) {
  82. setLoading(false);
  83. }
  84. }
  85. };
  86. useEffect(() => {
  87. mountedRef.current = true;
  88. // Check auth status on mount
  89. checkAuthStatus();
  90. return () => {
  91. mountedRef.current = false;
  92. };
  93. }, []);
  94. // Separate effect to handle redirect only when setup is required
  95. useEffect(() => {
  96. // Only redirect if setup is truly required (first time setup)
  97. // Don't redirect if user manually navigated to /setup or is on camera page
  98. if (!loading && requiresSetup && !authEnabled) {
  99. const currentPath = window.location.pathname;
  100. // Only redirect if not already on setup page or camera page, and haven't redirected yet
  101. if (currentPath !== '/setup' && !currentPath.startsWith('/camera/') && !hasRedirectedRef.current) {
  102. hasRedirectedRef.current = true;
  103. window.location.href = '/setup';
  104. }
  105. } else if (!requiresSetup) {
  106. // Reset redirect flag when setup is no longer required
  107. hasRedirectedRef.current = false;
  108. }
  109. }, [loading, requiresSetup, authEnabled]);
  110. const login = async (username: string, password: string): Promise<LoginResponse> => {
  111. const response = await api.login({ username, password });
  112. if (!response.requires_2fa && response.access_token) {
  113. setAuthToken(response.access_token);
  114. await checkAuthStatus();
  115. }
  116. return response;
  117. };
  118. const loginWithToken = (token: string, userObj: UserResponse) => {
  119. setAuthToken(token);
  120. setUser(userObj);
  121. setAuthEnabled(true);
  122. };
  123. const logout = () => {
  124. setAuthToken(null);
  125. setUser(null);
  126. api.logout().catch(() => {
  127. // Ignore logout errors
  128. });
  129. window.location.href = '/login';
  130. };
  131. const refreshUser = async () => {
  132. if (authEnabled && getAuthToken()) {
  133. try {
  134. const currentUser = await api.getCurrentUser();
  135. if (mountedRef.current) {
  136. setUser(currentUser);
  137. }
  138. } catch {
  139. setAuthToken(null);
  140. if (mountedRef.current) {
  141. setUser(null);
  142. }
  143. }
  144. }
  145. };
  146. const refreshAuth = async () => {
  147. await checkAuthStatus();
  148. };
  149. // Memoize permission set for efficient lookups
  150. const permissionSet = useMemo(() => {
  151. return new Set(user?.permissions ?? []);
  152. }, [user?.permissions]);
  153. // Computed admin status
  154. const isAdmin = useMemo(() => {
  155. if (!authEnabled) return true; // Auth disabled = admin access
  156. return user?.is_admin ?? false;
  157. }, [authEnabled, user?.is_admin]);
  158. // Permission check functions
  159. const hasPermission = useCallback((permission: Permission): boolean => {
  160. if (!authEnabled) return true; // Auth disabled = allow all
  161. if (isAdmin) return true; // Admins have all permissions
  162. return permissionSet.has(permission);
  163. }, [authEnabled, isAdmin, permissionSet]);
  164. const hasAnyPermission = useCallback((...permissions: Permission[]): boolean => {
  165. if (!authEnabled) return true;
  166. if (isAdmin) return true;
  167. return permissions.some(p => permissionSet.has(p));
  168. }, [authEnabled, isAdmin, permissionSet]);
  169. const hasAllPermissions = useCallback((...permissions: Permission[]): boolean => {
  170. if (!authEnabled) return true;
  171. if (isAdmin) return true;
  172. return permissions.every(p => permissionSet.has(p));
  173. }, [authEnabled, isAdmin, permissionSet]);
  174. // Ownership-based permission check
  175. const canModify = useCallback((
  176. resource: 'queue' | 'archives' | 'library',
  177. action: 'update' | 'delete' | 'reprint',
  178. createdById: number | null | undefined,
  179. ): boolean => {
  180. if (!authEnabled) return true; // Auth disabled, allow all
  181. if (isAdmin) return true; // Admins can modify anything
  182. const allPerm = `${resource}:${action}_all` as Permission;
  183. const ownPerm = `${resource}:${action}_own` as Permission;
  184. // User has *_all permission - can modify any item
  185. if (permissionSet.has(allPerm)) return true;
  186. // User has *_own permission - can only modify their own items
  187. if (permissionSet.has(ownPerm)) {
  188. // Ownerless items (null created_by_id) require *_all permission
  189. if (createdById == null) return false;
  190. return createdById === user?.id;
  191. }
  192. return false;
  193. }, [authEnabled, isAdmin, permissionSet, user?.id]);
  194. return (
  195. <AuthContext.Provider
  196. value={{
  197. user,
  198. authEnabled,
  199. requiresSetup,
  200. loading,
  201. isAdmin,
  202. login,
  203. loginWithToken,
  204. logout,
  205. refreshUser,
  206. refreshAuth,
  207. hasPermission,
  208. hasAnyPermission,
  209. hasAllPermissions,
  210. canModify,
  211. }}
  212. >
  213. {children}
  214. </AuthContext.Provider>
  215. );
  216. }
  217. export function useAuth() {
  218. const context = useContext(AuthContext);
  219. if (context === undefined) {
  220. throw new Error('useAuth must be used within an AuthProvider');
  221. }
  222. return context;
  223. }