-
Notifications
You must be signed in to change notification settings - Fork 0
/
session.server.ts
109 lines (91 loc) · 2.59 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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import { createCookieSessionStorage, redirect } from "@remix-run/node";
import type { LoaderContext, SessionServer } from "./types";
if (!process.env.SESSION_SECRET) {
throw new Error("SESSION_SECRET must be set");
}
export const sessionStorage = createCookieSessionStorage({
cookie: {
name: "__session",
httpOnly: true,
maxAge: 0,
path: "/",
sameSite: "lax",
secrets: [process.env.SESSION_SECRET],
secure: process.env.NODE_ENV === "production",
},
});
const USER_SESSION_KEY = "userId";
export const SessionServerFactory = (env: LoaderContext): SessionServer => {
async function getSession(request: Request) {
const cookie = request.headers.get("Cookie");
return sessionStorage.getSession(cookie);
}
async function getUserId(request: Request) {
const session = await getSession(request);
const userId = session.get(USER_SESSION_KEY);
return userId;
}
async function getUser(request: Request) {
const { UserServer } = env;
const userId = await getUserId(request);
if (userId === undefined) return null;
const user = await UserServer.getUserById(userId);
if (user) return user;
throw await logout(request);
}
async function requireUserId(request: Request, redirectTo?: string) {
const userId = await getUserId(request);
if (!userId) {
const searchParams = new URLSearchParams([["redirectTo", redirectTo || "/"]]);
throw redirect(`/login?${searchParams}`);
}
return userId;
}
async function requireUser(request: Request) {
const { UserServer } = env;
const userId = await requireUserId(request);
const user = await UserServer.getUserById(userId);
if (user) return user;
throw await logout(request);
}
async function createUserSession({
request,
userId,
remember,
redirectTo,
}: {
request: Request;
userId: string;
remember: boolean;
redirectTo: string;
}) {
const session = await getSession(request);
session.set(USER_SESSION_KEY, userId);
return redirect(redirectTo, {
headers: {
"Set-Cookie": await sessionStorage.commitSession(session, {
maxAge: remember
? 60 * 60 * 24 * 7 // 7 days
: undefined,
}),
},
});
}
async function logout(request: Request) {
const session = await getSession(request);
return redirect("/", {
headers: {
"Set-Cookie": await sessionStorage.destroySession(session),
},
});
}
return {
getSession,
getUserId,
getUser,
requireUserId,
requireUser,
createUserSession,
logout,
};
};