-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathindex.tsx
337 lines (321 loc) · 10.2 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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
import "server-only";
import { fetchQuery } from "convex/nextjs";
import { NextMiddlewareResult } from "next/dist/server/web/types";
import {
NextFetchEvent,
NextMiddleware,
NextRequest,
NextResponse,
} from "next/server";
import { ReactNode } from "react";
import {
ConvexAuthNextjsClientProvider,
ConvexAuthServerState,
} from "../client.js";
import { getRequestCookies, getRequestCookiesInMiddleware } from "./cookies.js";
import { proxyAuthActionToConvex, shouldProxyAuthAction } from "./proxy.js";
import { handleAuthenticationInRequest } from "./request.js";
import {
logVerbose,
setAuthCookies,
setAuthCookiesInMiddleware,
} from "./utils.js";
import { IsAuthenticatedQuery } from "../../server/implementation/index.js";
import { jwtVerify, createLocalJWKSet } from "jose"
/**
* Wrap your app with this provider in your root `layout.tsx`.
*/
export async function ConvexAuthNextjsServerProvider(props: {
/**
* You can customize the route path that handles authentication
* actions via this prop and the `apiRoute` option to `convexAuthNextjsMiddleWare`.
*
* Defaults to `/api/auth`.
*/
apiRoute?: string;
/**
* Choose how the auth information will be stored on the client.
*
* Defaults to `"localStorage"`.
*
* If you choose `"inMemory"`, different browser tabs will not
* have a synchronized authentication state.
*/
storage?: "localStorage" | "inMemory";
/**
* 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.
*
* Defaults to `process.env.NEXT_PUBLIC_CONVEX_URL`.
*/
storageNamespace?: string;
/**
* Turn on debugging logs.
*/
verbose?: boolean;
/**
* Children components can call Convex hooks
* and [useAuthActions](https://labs.convex.dev/auth/api_reference/react#useauthactions).
*/
children: ReactNode;
}) {
const { apiRoute, storage, storageNamespace, verbose, children } = props;
const serverState = await convexAuthNextjsServerState();
return (
<ConvexAuthNextjsClientProvider
serverState={serverState}
apiRoute={apiRoute}
storage={storage}
storageNamespace={storageNamespace}
verbose={verbose}
>
{children}
</ConvexAuthNextjsClientProvider>
);
}
/**
* Retrieve the token for authenticating calls to your
* Convex backend from Server Components, Server Actions and Route Handlers.
* @returns The token if the client is authenticated, otherwise `undefined`.
*/
export async function convexAuthNextjsToken() {
return (await getRequestCookies()).token ?? undefined;
}
/**
* Whether the client is authenticated, which you can check
* in Server Actions, Route Handlers and Middleware.
*
* Avoid the pitfall of checking authentication state in layouts,
* since they won't stop nested pages from rendering.
*/
export async function isAuthenticatedNextjs() {
const cookies = await getRequestCookies();
return isAuthenticated(cookies.token);
}
/**
* In `convexAuthNextjsMiddleware`, you can use this context
* to get the token and check if the client is authenticated in place of
* `convexAuthNextjsToken` and `isAuthenticatedNextjs`.
*
* ```ts
* export function convexAuthNextjsMiddleware(handler, options) {
* return async (request, event, convexAuth) => {
* if (!(await convexAuth.isAuthenticated())) {
* return nextjsMiddlewareRedirect(request, "/login");
* }
* };
* }
* ```
*/
export type ConvexAuthNextjsMiddlewareContext = {
getToken: () => Promise<string | undefined>;
isAuthenticated: () => Promise<boolean>;
};
/**
* Use in your `middleware.ts` to enable your Next.js app to use
* Convex Auth for authentication on the server.
*
* @returns A Next.js middleware.
*/
export function convexAuthNextjsMiddleware(
/**
* A custom handler, which you can use to decide
* which routes should be accessible based on the client's authentication.
*/
handler?: (
request: NextRequest,
ctx: {
event: NextFetchEvent;
convexAuth: ConvexAuthNextjsMiddlewareContext;
},
) => NextMiddlewareResult | Promise<NextMiddlewareResult>,
options: {
/**
* The URL of the Convex deployment to use for authentication.
*
* Defaults to `process.env.NEXT_PUBLIC_CONVEX_URL`.
*/
convexUrl?: string;
/**
* You can customize the route path that handles authentication
* actions via this option and the `apiRoute` prop of `ConvexAuthNextjsProvider`.
*
* Defaults to `/api/auth`.
*/
apiRoute?: string;
/**
* The cookie config to use for the auth cookies.
*
* `maxAge` is the number of seconds the cookie will be valid for. If this is not set, the cookie will be a session cookie.
*
* See [MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#defining_the_lifetime_of_a_cookie)
* for more information.
*/
cookieConfig?: { maxAge: number | null };
/**
* Turn on debugging logs.
*/
verbose?: boolean;
} = {},
): NextMiddleware {
return async (request, event) => {
const verbose = options.verbose ?? false;
const cookieConfig = options.cookieConfig ?? { maxAge: null };
if (cookieConfig.maxAge !== null && cookieConfig.maxAge <= 0) {
throw new Error(
"cookieConfig.maxAge must be null or a positive number of seconds",
);
}
logVerbose(`Begin middleware for request with URL ${request.url}`, verbose);
const requestUrl = new URL(request.url);
// Proxy signIn and signOut actions to Convex backend
const apiRoute = options?.apiRoute ?? "/api/auth";
if (shouldProxyAuthAction(request, apiRoute)) {
logVerbose(
`Proxying auth action to Convex, path matches ${apiRoute} with or without trailing slash`,
verbose,
);
return await proxyAuthActionToConvex(request, options);
}
logVerbose(
`Not proxying auth action to Convex, path ${requestUrl.pathname} does not match ${apiRoute}`,
verbose,
);
// Refresh tokens, handle code query param
const authResult = await handleAuthenticationInRequest(
request,
verbose,
cookieConfig,
);
// If redirecting, proceed, the middleware will run again on next request
if (authResult.kind === "redirect") {
logVerbose(
`Redirecting to ${authResult.response.headers.get("Location")}`,
verbose,
);
return authResult.response;
}
let response: Response | null = null;
// Forward cookies to request for custom handler
if (
authResult.kind === "refreshTokens" &&
authResult.refreshTokens !== undefined
) {
logVerbose(`Forwarding cookies to request`, verbose);
await setAuthCookiesInMiddleware(request, authResult.refreshTokens);
}
if (handler === undefined) {
logVerbose(`No custom handler`, verbose);
response = NextResponse.next({
request: {
headers: request.headers,
},
});
} else {
// Call the custom handler
logVerbose(`Calling custom handler`, verbose);
response =
(await handler(request, {
event,
convexAuth: {
getToken: async () => {
const cookies = await getRequestCookiesInMiddleware(request);
return cookies.token ?? undefined;
},
isAuthenticated: async () => {
const cookies = await getRequestCookiesInMiddleware(request);
return isAuthenticated(cookies.token);
},
},
})) ??
NextResponse.next({
request: {
headers: request.headers,
},
});
}
// Port the cookies from the auth middleware to the response
if (
authResult.kind === "refreshTokens" &&
authResult.refreshTokens !== undefined
) {
const nextResponse = NextResponse.next(response);
await setAuthCookies(
nextResponse,
authResult.refreshTokens,
cookieConfig,
);
return nextResponse;
}
return response;
};
}
export { createRouteMatcher, RouteMatcherParam } from "./routeMatcher.js";
/**
* Helper for redirecting to a different route from
* a Next.js middleware.
*
* ```ts
* return nextjsMiddlewareRedirect(request, "/login");
* ```
*/
export function nextjsMiddlewareRedirect(
/**
* The incoming request handled by the middleware.
*/
request: NextRequest,
/**
* The route path to redirect to.
*/
pathname: string,
) {
const url = request.nextUrl.clone();
url.pathname = pathname;
return NextResponse.redirect(url);
}
async function convexAuthNextjsServerState(): Promise<ConvexAuthServerState> {
const { token } = await getRequestCookies();
return {
// The server doesn't share the refresh token with the client
// for added security - the client has to use the server
// to refresh the access token via cookies.
_state: { token, refreshToken: "dummy" },
_timeFetched: Date.now(),
};
}
async function isAuthenticated(token: string | null): Promise<boolean> {
if (!token) {
return false;
}
// First, try using the JWKS from the environment variable to do token
// verification locally (networkless mode).
try {
const envJwks = process.env.CONVEX_AUTH_JWKS
if (envJwks) {
const jwkSet = createLocalJWKSet(JSON.parse(envJwks))
const verifiedToken = await jwtVerify(token, jwkSet);
return !!verifiedToken.payload.sub;
}
} catch (error: any) {
console.error("Error verifying token", error);
}
// Fallback to asking the server to do verification.
try {
return await fetchQuery(
"auth:isAuthenticated" as any as IsAuthenticatedQuery,
{},
{ token: token },
);
} catch (e: any) {
if (e.message.includes("Could not find public function")) {
throw new Error(
"Server Error: could not find api.auth.isAuthenticated. convex-auth 0.0.76 introduced a new export in convex/auth.ts. Add `isAuthenticated` to the list of functions returned from convexAuth(). See convex-auth changelog for more https://github.com/get-convex/convex-auth/blob/main/CHANGELOG.md",
);
} else {
console.log("Returning false from isAuthenticated because", e);
}
return false;
}
}