-
Notifications
You must be signed in to change notification settings - Fork 463
Expand file tree
/
Copy pathauth.server.ts
More file actions
298 lines (269 loc) · 7.01 KB
/
auth.server.ts
File metadata and controls
298 lines (269 loc) · 7.01 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
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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
import crypto from 'node:crypto'
import {
type Connection,
type Password,
type User,
} from '#prisma/generated/client.ts'
import bcrypt from 'bcryptjs'
import { redirect } from 'react-router'
import { Authenticator } from 'remix-auth'
import { safeRedirect } from 'remix-utils/safe-redirect'
import { providers } from './connections.server.ts'
import { prisma } from './db.server.ts'
import { combineHeaders, downloadFile } from './misc.tsx'
import { type ProviderUser } from './providers/provider.ts'
import { authSessionStorage } from './session.server.ts'
import { uploadProfileImage } from './storage.server.ts'
export const SESSION_EXPIRATION_TIME = 1000 * 60 * 60 * 24 * 30
export const getSessionExpirationDate = () =>
new Date(Date.now() + SESSION_EXPIRATION_TIME)
export const sessionKey = 'sessionId'
export const authenticator = new Authenticator<ProviderUser>()
for (const [providerName, provider] of Object.entries(providers)) {
const strategy = provider.getAuthStrategy()
if (strategy) {
authenticator.use(strategy, providerName)
}
}
export async function getUserId(request: Request) {
const authSession = await authSessionStorage.getSession(
request.headers.get('cookie'),
)
const sessionId = authSession.get(sessionKey)
if (!sessionId) return null
const session = await prisma.session.findUnique({
select: { userId: true },
where: { id: sessionId, expirationDate: { gt: new Date() } },
})
if (!session?.userId) {
throw redirect('/', {
headers: {
'set-cookie': await authSessionStorage.destroySession(authSession),
},
})
}
return session.userId
}
export async function requireUserId(
request: Request,
{ redirectTo }: { redirectTo?: string | null } = {},
) {
const userId = await getUserId(request)
if (!userId) {
const requestUrl = new URL(request.url)
redirectTo =
redirectTo === null
? null
: (redirectTo ?? `${requestUrl.pathname}${requestUrl.search}`)
const loginParams = redirectTo ? new URLSearchParams({ redirectTo }) : null
const loginRedirect = ['/login', loginParams?.toString()]
.filter(Boolean)
.join('?')
throw redirect(loginRedirect)
}
return userId
}
export async function requireAnonymous(request: Request) {
const userId = await getUserId(request)
if (userId) {
throw redirect('/')
}
}
export async function login({
username,
password,
}: {
username: User['username']
password: string
}) {
const user = await verifyUserPassword({ username }, password)
if (!user) return null
const session = await prisma.session.create({
select: { id: true, expirationDate: true, userId: true },
data: {
expirationDate: getSessionExpirationDate(),
userId: user.id,
},
})
return session
}
export async function resetUserPassword({
username,
password,
}: {
username: User['username']
password: string
}) {
const hashedPassword = await getPasswordHash(password)
return prisma.user.update({
where: { username },
data: {
password: {
update: {
hash: hashedPassword,
},
},
},
})
}
export async function signup({
email,
username,
password,
name,
}: {
email: User['email']
username: User['username']
name: User['name']
password: string
}) {
const hashedPassword = await getPasswordHash(password)
const session = await prisma.session.create({
data: {
expirationDate: getSessionExpirationDate(),
user: {
create: {
email: email.toLowerCase(),
username: username.toLowerCase(),
name,
roles: { connect: { name: 'user' } },
password: {
create: {
hash: hashedPassword,
},
},
},
},
},
select: { id: true, expirationDate: true },
})
return session
}
export async function signupWithConnection({
email,
username,
name,
providerId,
providerName,
imageUrl,
}: {
email: User['email']
username: User['username']
name: User['name']
providerId: Connection['providerId']
providerName: Connection['providerName']
imageUrl?: string
}) {
const user = await prisma.user.create({
data: {
email: email.toLowerCase(),
username: username.toLowerCase(),
name,
roles: { connect: { name: 'user' } },
connections: { create: { providerId, providerName } },
},
select: { id: true },
})
if (imageUrl) {
const imageFile = await downloadFile(imageUrl)
await prisma.user.update({
where: { id: user.id },
data: {
image: {
create: {
objectKey: await uploadProfileImage(user.id, imageFile),
},
},
},
})
}
// Create and return the session
const session = await prisma.session.create({
data: {
expirationDate: getSessionExpirationDate(),
userId: user.id,
},
select: { id: true, expirationDate: true },
})
return session
}
export async function logout(
{
request,
redirectTo = '/',
}: {
request: Request
redirectTo?: string
},
responseInit?: ResponseInit,
) {
const authSession = await authSessionStorage.getSession(
request.headers.get('cookie'),
)
const sessionId = authSession.get(sessionKey)
// if this fails, we still need to delete the session from the user's browser
// and it doesn't do any harm staying in the db anyway.
if (sessionId) {
// the .catch is important because that's what triggers the query.
// learn more about PrismaPromise: https://www.prisma.io/docs/orm/reference/prisma-client-reference#prismapromise-behavior
void prisma.session.deleteMany({ where: { id: sessionId } }).catch(() => {})
}
throw redirect(safeRedirect(redirectTo), {
...responseInit,
headers: combineHeaders(
{ 'set-cookie': await authSessionStorage.destroySession(authSession) },
responseInit?.headers,
),
})
}
export async function getPasswordHash(password: string) {
const hash = await bcrypt.hash(password, 10)
return hash
}
export async function verifyUserPassword(
where: Pick<User, 'username'> | Pick<User, 'id'>,
password: Password['hash'],
) {
const userWithPassword = await prisma.user.findUnique({
where,
select: { id: true, password: { select: { hash: true } } },
})
if (!userWithPassword || !userWithPassword.password) {
return null
}
const isValid = await bcrypt.compare(password, userWithPassword.password.hash)
if (!isValid) {
return null
}
return { id: userWithPassword.id }
}
export function getPasswordHashParts(password: string) {
const hash = crypto
.createHash('sha1')
.update(password, 'utf8')
.digest('hex')
.toUpperCase()
return [hash.slice(0, 5), hash.slice(5)] as const
}
export async function checkIsCommonPassword(password: string) {
const [prefix, suffix] = getPasswordHashParts(password)
try {
const response = await fetch(
`https://api.pwnedpasswords.com/range/${prefix}`,
{ signal: AbortSignal.timeout(1000) },
)
if (!response.ok) return false
const data = await response.text()
return data.split(/\r?\n/).some((line) => {
const [hashSuffix, ignoredPrevalenceCount] = line.split(':')
return hashSuffix === suffix
})
} catch (error) {
if (error instanceof DOMException && error.name === 'TimeoutError') {
console.warn('Password check timed out')
return false
}
console.warn('Unknown error during password check', error)
return false
}
}