forked from infonomic/remix.infonomic.io
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsession.server.ts
154 lines (136 loc) · 3.24 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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
/* eslint-disable @typescript-eslint/no-throw-literal */
import { createCookieSessionStorage, redirect } from '@remix-run/node'
import invariant from 'tiny-invariant'
import { getUserById } from '~/models/user.server'
import type { User } from '~/models/user.server'
invariant(process.env.SESSION_SECRET, 'SESSION_SECRET must be set')
const sessionStorage = createCookieSessionStorage({
cookie: {
name: '__session',
path: '/',
sameSite: 'lax',
httpOnly: true,
secrets: [process.env.SESSION_SECRET],
secure: process.env.NODE_ENV === 'production',
},
})
// Export convenience methods
const { commitSession, destroySession } = sessionStorage
export { commitSession, destroySession }
const USER_SESSION_KEY = 'userId'
const USER_IS_ADMIN = 'isAdmin'
// Convenience getSession helper
export async function getSession(request: Request) {
const cookie = request.headers.get('Cookie')
return sessionStorage.getSession(cookie)
}
/**
* Logout
* @param request
* @returns
*/
export async function logout(request: Request) {
const session = await getSession(request)
return redirect('/', {
headers: {
'Set-Cookie': await sessionStorage.destroySession(session),
},
})
}
/**
* getUserId
*
* @param request
* @returns
*/
export async function getUserId(request: Request): Promise<User['id'] | undefined> {
const session = await getSession(request)
const userId = session.get(USER_SESSION_KEY)
return userId
}
/**
* getUser
* @param request
* @returns
*/
export async function getUser(request: Request) {
const userId = await getUserId(request)
if (userId === undefined) return null
const user = await getUserById(userId)
if (user) return user
throw await logout(request)
}
/**
* requireUserId
*
* @param request
* @param redirectTo
* @returns
*/
export async function requireUserId(
request: Request,
redirectTo: string = new URL(request.url).pathname
) {
const userId = await getUserId(request)
if (!userId) {
const searchParams = new URLSearchParams([['redirectTo', redirectTo]])
throw redirect(`/sign-in?${searchParams}`)
}
return userId
}
/**
* requireAdmin
*
* @param request
* @returns
*/
export async function requireAdmin(request: Request) {
const session = await getSession(request)
const isAdmin = session.get(USER_IS_ADMIN)
if (!isAdmin) {
throw new Response('Access Denied', { status: 403 })
}
}
/**
* requireUser
*
* @param request
* @returns
*/
export async function requireUser(request: Request) {
const userId = await requireUserId(request)
const user = await getUserById(userId)
if (user) return user
throw await logout(request)
}
/**
* createUserSession
*
* @param param0
* @returns
*/
export async function createUserSession({
request,
userId,
isAdmin,
remember,
redirectTo,
}: {
request: Request
userId: string
isAdmin: boolean
remember: boolean
redirectTo: string
}) {
const session = await getSession(request)
session.set(USER_SESSION_KEY, userId)
session.set(USER_IS_ADMIN, isAdmin)
return redirect(redirectTo, {
headers: {
'Set-Cookie': await sessionStorage.commitSession(session, {
// 7 days if remember or undefined
maxAge: remember ? 60 * 60 * 24 * 7 : undefined,
}),
},
})
}