-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.ts
104 lines (88 loc) · 2.36 KB
/
auth.ts
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
import { cookies } from 'next/headers';
import NextAuth, { type NextAuthConfig } from 'next-auth';
import CredentialsProvider from 'next-auth/providers/credentials';
import { z } from 'zod';
import { assignCartToCustomer } from './client/mutations/assign-cart-to-customer';
import { login } from './client/mutations/login';
import { unassignCartFromCustomer } from './client/mutations/unassign-cart-from-customer';
export const Credentials = z.object({
email: z.string().email(),
password: z.string().min(1),
});
declare module 'next-auth' {
interface Session {
user?: {
id?: number;
};
}
}
const config = {
session: {
strategy: 'jwt',
},
pages: {
signIn: '/login',
},
callbacks: {
session({ session, token }) {
session.user ||= {};
session.user.id = token.sub ? parseInt(token.sub, 10) : undefined;
return session;
},
},
events: {
async signIn({ user }) {
const cookieCartId = cookies().get('cartId')?.value;
if (cookieCartId) {
try {
await assignCartToCustomer(user.id, cookieCartId);
} catch (error) {
// eslint-disable-next-line no-console
console.error(error);
}
}
},
async signOut() {
const cookieCartId = cookies().get('cartId')?.value;
if (cookieCartId) {
try {
await unassignCartFromCustomer(cookieCartId);
} catch (error) {
// eslint-disable-next-line no-console
console.error(error);
}
}
},
},
providers: [
CredentialsProvider({
credentials: {
email: { label: 'Email', type: 'email' },
password: { label: 'Password', type: 'password' },
},
async authorize(credentials) {
const { email, password } = Credentials.parse(credentials);
const customer = await login(email, password);
if (!customer) {
return null;
}
return {
id: customer.entityId.toString(),
};
},
}),
],
} satisfies NextAuthConfig;
const { handlers, auth, signIn, signOut, update } = NextAuth(config);
const getSessionCustomerId = async () => {
try {
const session = await auth();
if (!session?.user?.id) {
return;
}
return session.user.id;
} catch {
// No empty
}
};
export { handlers, auth, signIn, signOut, update, getSessionCustomerId };