-
Notifications
You must be signed in to change notification settings - Fork 1
/
session.server.ts
90 lines (78 loc) · 2.25 KB
/
session.server.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
import { createCookieSessionStorage, redirect } from '@remix-run/node';
import type { Session, User } from '@supabase/supabase-js';
import { SESSION_SECRET } from './variables.server';
export const sessionStorage = createCookieSessionStorage({
cookie: {
name: '__session',
httpOnly: true,
maxAge: 0,
path: '/',
sameSite: 'lax',
secrets: [SESSION_SECRET],
secure: process.env.NODE_ENV ? process.env.NODE_ENV === 'production' : true
}
});
export async function getSession(request: Request) {
const cookie = request.headers.get('Cookie');
return sessionStorage.getSession(cookie);
}
export async function getSbSession(
request: Request
): Promise<Session | undefined> {
const session = await getSession(request);
const sbSession = session.get('session');
return sbSession;
}
export async function getUser(request: Request): Promise<null | User> {
const session = await getSbSession(request);
if (session === undefined) return null;
if (session.user) return session.user;
throw await logout(request);
}
export async function requireSession(
request: Request,
redirectTo: string = new URL(request.url).pathname
): Promise<Session> {
const session = await getSbSession(request);
if (!session) {
const searchParams = new URLSearchParams([['redirectTo', redirectTo]]);
throw redirect(`/login?${searchParams}`);
}
return session;
}
export async function requireUser(request: Request) {
const session = await requireSession(request);
if (session.user) return session.user;
throw await logout(request);
}
export async function createUserSession({
request,
session,
remember,
redirectTo
}: {
request: Request;
session: Session;
remember: boolean;
redirectTo: string;
}) {
const sessionCookie = await getSession(request);
sessionCookie.set('session', session);
return redirect(redirectTo, {
headers: {
'Set-Cookie': await sessionStorage.commitSession(sessionCookie, {
maxAge: remember
? 60 * 60 * 24 * 7 // 7 days
: undefined
})
}
});
}
export async function logout(request: Request) {
const session = await getSession(request);
return redirect('/', {
headers: {
'Set-Cookie': await sessionStorage.destroySession(session)
}
});
}