forked from get-convex/convex-auth
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.tsx
266 lines (258 loc) · 7.49 KB
/
index.tsx
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
/**
* React bindings for Convex Auth.
*
* @module
*/
"use client";
import { ConvexHttpClient } from "convex/browser";
import { ConvexProviderWithAuth, ConvexReactClient } from "convex/react";
import { Value } from "convex/values";
import { ReactNode, useContext, useMemo } from "react";
import {
AuthProvider,
ConvexAuthActionsContext,
ConvexAuthTokenContext,
useAuth,
} from "./client.js";
import { AuthClient } from "./clientType.js";
/**
* Use this hook to access the `signIn` and `signOut` methods:
*
* ```ts
* import { useAuthActions } from "@convex-dev/auth/react";
*
* function SomeComponent() {
* const { signIn, signOut } = useAuthActions();
* // ...
* }
* ```
*/
export function useAuthActions() {
return useContext(ConvexAuthActionsContext);
}
/**
* Replace your `ConvexProvider` with this component to enable authentication.
*
* ```tsx
* import { ConvexAuthProvider } from "@convex-dev/auth/react";
* import { ConvexReactClient } from "convex/react";
* import { ReactNode } from "react";
*
* const convex = new ConvexReactClient(/* ... *\/);
*
* function RootComponent({ children }: { children: ReactNode }) {
* return <ConvexAuthProvider client={convex}>{children}</ConvexAuthProvider>;
* }
* ```
*/
export function ConvexAuthProvider(props: {
/**
* Your [`ConvexReactClient`](https://docs.convex.dev/api/classes/react.ConvexReactClient).
*/
client: ConvexReactClient;
/**
* Optional custom storage object that implements
* the {@link TokenStorage} interface, otherwise
* [`localStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage)
* is used.
*
* You must set this for React Native.
*/
storage?: TokenStorage;
/**
* Optional namespace for keys used to store tokens. The keys
* determine whether the tokens are shared or not.
*
* Any non-alphanumeric characters will be ignored (for RN compatibility).
*
* Defaults to the deployment URL, as configured in the given `client`.
*/
storageNamespace?: string;
/**
* Provide this function if you're using a JS router (Expo router etc.)
* and after OAuth or magic link sign-in the `code` param is not being
* erased from the URL.
*
* The implementation will depend on your chosen router.
*/
replaceURL?: (
/**
* The URL, always starting with '/' and include the path, query and
* fragment components, that the window location should be set to.
*/
relativeUrl: string,
) => void | Promise<void>;
/**
* Children components can call Convex hooks
* and {@link useAuthActions}.
*/
children: ReactNode;
}) {
const { client, storage, storageNamespace, replaceURL, children } = props;
const authClient = useMemo(
() =>
({
authenticatedCall(action, args) {
return client.action(action, args);
},
unauthenticatedCall(action, args) {
return new ConvexHttpClient((client as any).address, {
logger: client.logger,
}).action(action, args);
},
verbose: (client as any).options?.verbose,
logger: client.logger,
}) satisfies AuthClient,
[client],
);
return (
<AuthProvider
client={authClient}
storage={
storage ??
// Handle SSR, RN, Web, etc.
// Pretend we always have storage, the component checks
// it in first useEffect.
(typeof window === "undefined" ? undefined : window?.localStorage)!
}
storageNamespace={storageNamespace ?? (client as any).address}
replaceURL={
replaceURL ??
((url) => {
window.history.replaceState({}, "", url);
})
}
>
<ConvexProviderWithAuth client={client} useAuth={useAuth}>
{children}
</ConvexProviderWithAuth>
</AuthProvider>
);
}
/**
* A storage interface for storing and retrieving tokens and other secrets.
*
* In browsers `localStorage` and `sessionStorage` implement this interface.
*
* `sessionStorage` can be used for creating separate sessions for each
* browser tab.
*
* In React Native we recommend wrapping `expo-secure-store`.
*/
export interface TokenStorage {
/**
* Read a value.
* @param key Unique key.
*/
getItem: (
key: string,
) => string | undefined | null | Promise<string | undefined | null>;
/**
* Write a value.
* @param key Unique key.
* @param value The value to store.
*/
setItem: (key: string, value: string) => void | Promise<void>;
/**
* Remove a value.
* @param key Unique key.
*/
removeItem: (key: string) => void | Promise<void>;
}
/**
* The result of calling {@link useAuthActions}.
*/
export type ConvexAuthActionsContext = {
/**
* Sign in via one of your configured authentication providers.
*
* @returns Whether the user was immediately signed in (ie. the sign-in
* didn't trigger an additional step like email verification
* or OAuth signin).
*/
signIn(
this: void,
/**
* The ID of the provider (lowercase version of the
* provider name or a configured `id` option value).
*/
provider: string,
/**
* Either a `FormData` object containing the sign-in
* parameters or a plain object containing them.
* The shape required depends on the chosen provider's
* implementation.
*
* Special fields:
* - `redirectTo`: If provided, customizes the destination the user is
* redirected to at the end of an OAuth flow or the magic link URL.
* See [redirect callback](https://labs.convex.dev/auth/api_reference/server#callbacksredirect).
* - `code`: OTP code for email or phone verification, or
* (used only in RN) the code from an OAuth flow or magic link URL.
*/
params?:
| FormData
| (Record<string, Value> & {
/**
* If provided, customizes the destination the user is
* redirected to at the end of an OAuth flow or the magic link URL.
*/
redirectTo?: string;
/**
* OTP code for email or phone verification, or
* (used only in RN) the code from an OAuth flow or magic link URL.
*/
code?: string;
}),
): Promise<{
/**
* Whether the call led to an immediate successful sign-in.
*
* Note that there's a delay between the `signIn` function
* returning and the client performing the handshake with
* the server to confirm the sign-in.
*/
signingIn: boolean;
/**
* If the sign-in started an OAuth flow, this is the URL
* the browser should be redirected to.
*
* Useful in RN for opening the in-app browser to
* this URL.
*/
redirect?: URL;
}>;
/**
* Sign out the current user.
*
* Calls the server to invalidate the server session
* and deletes the locally stored JWT and refresh token.
*/
signOut(this: void): Promise<void>;
};
/**
* Use this hook to access the JWT token on the client, for authenticating
* your Convex HTTP actions.
*
* You should not pass this token to other servers (think of it
* as an "ID token").
*
* ```ts
* import { useAuthToken } from "@convex-dev/auth/react";
*
* function SomeComponent() {
* const token = useAuthToken();
* const onClick = async () => {
* await fetch(`${CONVEX_SITE_URL}/someEndpoint`, {
* headers: {
* Authorization: `Bearer ${token}`,
* },
* });
* };
* // ...
* }
* ```
*/
export function useAuthToken() {
return useContext(ConvexAuthTokenContext);
}