3
4const TOKEN_KEY = "bearer";
5const ANTHROPIC_KEY = "anthropic_api_key";
6
7export function useAuth() {
8 const [token, setToken, removeToken] = useLocalStorage(TOKEN_KEY, "");
9 const [anthropicApiKey, setAnthropicApiKey, removeAnthropicApiKey] = useLocalStorage(ANTHROPIC_KEY, "");
10 const [error, setError] = useState(null);
11
12 const isAuthenticated = !!token;
13
14 const authenticate = async (valTownAPIKey: string, anthropicKey: string) => {
15 // replace all this with oauth when it's ready
16 try {
17 const res = await fetch("/api/user", {
18 headers: {
19 "Authorization": "Bearer " + valTownAPIKey,
20 },
21 });
25 setError(data.error);
26 removeToken();
27 removeAnthropicApiKey();
28 return;
29 }
30 setError(null);
31 setToken(valTownAPIKey);
32 setAnthropicApiKey(anthropicKey);
33 } catch (e) {
34 console.error(e);
35 setError(e.error);
36 removeToken();
37 removeAnthropicApiKey();
38 }
39 };
41 const logOut = () => {
42 removeToken();
43 removeAnthropicApiKey();
44 };
45
50 logOut,
51 token,
52 anthropicApiKey,
53 };
54}