File size: 3,093 Bytes
af1bee9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import { createContext, useCallback, useContext, useMemo, type ReactNode } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { api, ApiError, setCsrfToken, unwrap, type Schemas } from '../api/client';

export type Role = 'viewer' | 'consultant' | 'qa_approver' | 'admin';
export type User = Schemas['UserOut'];

interface AuthState {
  user: User | null;
  loading: boolean;
  login: (username: string, password: string, remember?: boolean) => Promise<User>;
  /** Creates an account. 'confirm_email' = the address must be confirmed before the first sign-in. */
  register: (email: string, password: string) => Promise<'signed_in' | 'confirm_email'>;
  logout: () => Promise<void>;
  can: (perm: string) => boolean;
}

const Ctx = createContext<AuthState | null>(null);

export function AuthProvider({ children }: { children: ReactNode }) {
  const qc = useQueryClient();
  const me = useQuery({
    queryKey: ['me'],
    queryFn: async () => {
      try {
        return await unwrap(api.GET('/api/auth/me'));
      } catch (e) {
        if (e instanceof ApiError && e.status === 401) return null;
        throw e;
      }
    },
    staleTime: 60_000,
    retry: false,
  });

  const login = useCallback(async (username: string, password: string, remember = false) => {
    const out = await unwrap(api.POST('/api/auth/login', { body: { username, password, remember } }));
    setCsrfToken(out.csrf_token);
    qc.setQueryData(['me'], out.user);
    return out.user;
  }, [qc]);

  const register = useCallback(async (email: string, password: string) => {
    const out = (await unwrap(api.POST('/api/auth/register', { body: { email, password } }))) as { status: 'signed_in' | 'confirm_email'; user?: User; csrf_token?: string };
    if (out.status === 'signed_in' && out.user) {
      setCsrfToken(out.csrf_token ?? null);
      qc.setQueryData(['me'], out.user);
    }
    return out.status;
  }, [qc]);

  const logout = useCallback(async () => {
    try {
      await unwrap(api.POST('/api/auth/logout'));
    } finally {
      setCsrfToken(null);
      // Tell the signed-in check first (clearing the whole cache would leave it showing the old user), then drop the rest.
      qc.setQueryData(['me'], null);
      qc.removeQueries({ predicate: (q) => q.queryKey[0] !== 'me' });
    }
  }, [qc]);

  const value = useMemo<AuthState>(() => {
    const user = (me.data ?? null) as User | null;
    return { user, loading: me.isLoading, login, register, logout, can: (perm) => !!user?.permissions?.includes(perm) };
  }, [me.data, me.isLoading, login, register, logout]);

  return <Ctx.Provider value={value}>{children}</Ctx.Provider>;
}

/** The auth state, or null outside an AuthProvider (shared helpers that also render in isolated tests). */
export function useAuthOptional(): AuthState | null {
  return useContext(Ctx);
}

export function useAuth(): AuthState {
  const v = useContext(Ctx);
  if (!v) throw new Error('useAuth outside AuthProvider');
  return v;
}