-
Notifications
You must be signed in to change notification settings - Fork 158
Expand file tree
/
Copy pathmagic-auth.ts
More file actions
45 lines (39 loc) · 1.6 KB
/
magic-auth.ts
File metadata and controls
45 lines (39 loc) · 1.6 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
'use server';
// These are Next.js server actions.
//
// If your application is a single page app (SPA) with a separate backend you will need to:
// - create a backend endpoint to handle each request
// - adapt the code below in each of those endpoints
//
// Please also note that for the sake of simplicity, we return all errors here.
// In a real application, you should pay attention to which errors make it
// to the client for security reasons.
import { WorkOS } from '@workos-inc/node';
import { consumeInvitationToken } from '@/lib/invitation-token';
const workos = new WorkOS(process.env.WORKOS_API_KEY);
export async function sendCode(prevState: any, formData: FormData) {
try {
return await workos.userManagement.sendMagicAuthCode({
email: String(formData.get('email')),
});
} catch (error) {
return { error: JSON.parse(JSON.stringify(error)) };
}
}
export async function signIn(prevState: any, formData: FormData) {
try {
// Check for a stored invitation token (persisted across auth flows like password reset)
const invitationToken = await consumeInvitationToken();
// For the sake of simplicity, we directly return the user here.
// In a real application, you would probably store the user in a token (JWT)
// and store that token in your DB or use cookies.
return await workos.userManagement.authenticateWithMagicAuth({
clientId: process.env.WORKOS_CLIENT_ID || '',
code: String(formData.get('code')),
email: String(formData.get('email')),
invitationToken,
});
} catch (error) {
return { error: JSON.parse(JSON.stringify(error)) };
}
}