-
Notifications
You must be signed in to change notification settings - Fork 355
Expand file tree
/
Copy pathanonymous-session.ts
More file actions
94 lines (75 loc) · 2.46 KB
/
Copy pathanonymous-session.ts
File metadata and controls
94 lines (75 loc) · 2.46 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
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
import { cookies, headers } from 'next/headers';
import { AnonymousUser } from 'next-auth';
import { decode, encode } from 'next-auth/jwt';
const anonymousCookieName = 'authjs.anonymous-session-token';
const shouldUseSecureCookie = async () => {
const headersList = await headers();
return headersList.get('x-forwarded-proto') === 'https';
};
export const anonymousSignIn = async (user: Partial<AnonymousUser> = { cartId: null }) => {
const secret = process.env.AUTH_SECRET ?? process.env.NEXTAUTH_SECRET;
const useSecureCookies = await shouldUseSecureCookie();
const cookiePrefix = useSecureCookies ? '__Secure-' : '';
if (!secret) {
throw new Error('AUTH_SECRET is not set');
}
const cookieJar = await cookies();
const jwt = await encode({
salt: `${cookiePrefix}${anonymousCookieName}`,
secret,
token: {
user,
},
});
cookieJar.set(`${cookiePrefix}${anonymousCookieName}`, jwt, {
secure: useSecureCookies,
sameSite: 'lax',
// We set the maxAge to 7 days as a good default for anonymous sessions.
// This can be adjusted based on your application's needs.
maxAge: 60 * 60 * 24 * 7, // 7 days
httpOnly: true,
});
};
export const getAnonymousSession = async () => {
const cookieJar = await cookies();
const useSecureCookies = await shouldUseSecureCookie();
const cookiePrefix = useSecureCookies ? '__Secure-' : '';
const jwt = cookieJar.get(`${cookiePrefix}${anonymousCookieName}`);
if (!jwt) {
return null;
}
const secret = process.env.AUTH_SECRET ?? process.env.NEXTAUTH_SECRET;
if (!secret) {
throw new Error('AUTH_SECRET is not set');
}
try {
const session = await decode({
secret,
salt: `${cookiePrefix}${anonymousCookieName}`,
token: jwt.value,
});
return session;
} catch (err) {
// eslint-disable-next-line no-console
console.error('Failed to decode anonymous session cookie', err);
return null;
}
};
export const clearAnonymousSession = async () => {
const cookieJar = await cookies();
const useSecureCookies = await shouldUseSecureCookie();
const cookiePrefix = useSecureCookies ? '__Secure-' : '';
cookieJar.delete({
name: `${cookiePrefix}${anonymousCookieName}`,
secure: useSecureCookies,
sameSite: 'lax',
httpOnly: true,
});
};
export const updateAnonymousSession = async (user: AnonymousUser) => {
const session = await getAnonymousSession();
if (!session) {
return null;
}
await anonymousSignIn(user);
};