-
Notifications
You must be signed in to change notification settings - Fork 158
Expand file tree
/
Copy pathroute.ts
More file actions
57 lines (47 loc) · 1.71 KB
/
route.ts
File metadata and controls
57 lines (47 loc) · 1.71 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
import { WorkOS } from '@workos-inc/node';
import { NextResponse } from 'next/server';
import { SignJWT } from 'jose';
import { getJwtSecretKey } from '../auth';
import { consumeInvitationToken } from '@/lib/invitation-token';
// This is a Next.js Route Handler.
//
// If your application is a single page app (SPA) with a separate backend you will need to:
// - create a backend endpoint to handle the request
// - adapt the code below in your endpoint
const workos = new WorkOS(process.env.WORKOS_API_KEY);
export async function GET(request: Request) {
const url = new URL(request.url);
const code = url.searchParams.get('code') || '';
// Check for a stored invitation token (persisted across auth flows like password reset)
const invitationToken = await consumeInvitationToken();
try {
const { user } = await workos.userManagement.authenticateWithCode({
clientId: process.env.WORKOS_CLIENT_ID || '',
code,
invitationToken,
});
// Create a JWT with the user's information
// Here you might lookup and retrieve user details from your database
const token = await new SignJWT({ user })
.setProtectedHeader({ alg: 'HS256', typ: 'JWT' })
.setIssuedAt()
.setExpirationTime('1h')
.sign(getJwtSecretKey());
// Cleanup params
url.searchParams.delete('code');
// Store the session and redirect to the application
url.pathname = '/using-hosted-authkit/with-session';
const response = NextResponse.redirect(url);
response.cookies.set({
name: 'token',
value: token,
httpOnly: true,
path: '/',
secure: true,
sameSite: 'lax',
});
return response;
} catch (error) {
return NextResponse.json(error);
}
}