-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathauthClient.ts
More file actions
63 lines (51 loc) · 1.69 KB
/
authClient.ts
File metadata and controls
63 lines (51 loc) · 1.69 KB
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
import { PostHogAPIClient } from "@renderer/api/posthogClient";
import { trpcClient } from "@renderer/trpc/client";
import { getCloudUrlFromRegion } from "@shared/utils/urls";
import { useMemo } from "react";
import {
type AuthState,
fetchAuthState,
useAuthStateValue,
} from "./authQueries";
async function getValidAccessToken(): Promise<string> {
const { accessToken } = await trpcClient.auth.getValidAccessToken.query();
return accessToken;
}
async function refreshAccessToken(): Promise<string> {
const { accessToken } = await trpcClient.auth.refreshAccessToken.mutate();
return accessToken;
}
export function createAuthenticatedClient(
authState: AuthState | null | undefined,
): PostHogAPIClient | null {
if (authState?.status !== "authenticated" || !authState.cloudRegion) {
return null;
}
const client = new PostHogAPIClient(
getCloudUrlFromRegion(authState.cloudRegion),
getValidAccessToken,
refreshAccessToken,
authState.projectId ?? undefined,
);
if (authState.projectId) {
client.setTeamId(authState.projectId);
}
return client;
}
export async function getAuthenticatedClient(): Promise<PostHogAPIClient | null> {
return createAuthenticatedClient(await fetchAuthState());
}
export function useOptionalAuthenticatedClient(): PostHogAPIClient | null {
const authState = useAuthStateValue((state) => state);
return useMemo(
() => createAuthenticatedClient(authState),
[authState.cloudRegion, authState.projectId, authState.status, authState],
);
}
export function useAuthenticatedClient(): PostHogAPIClient {
const client = useOptionalAuthenticatedClient();
if (!client) {
throw new Error("Not authenticated");
}
return client;
}