patchwise-agent-studio / web /src /auth /AuthContext.tsx
EnergyVenom's picture
Patchwise Agent Studio: Oracle AI Agent Studio cycles
af1bee9 verified
Raw History Blame Contribute Delete
3.09 kB
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;
}