-
Notifications
You must be signed in to change notification settings - Fork 37
/
auth.ts
100 lines (91 loc) · 2.87 KB
/
auth.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
import type { BaseServer } from '@logux/server'
import {
setPassword,
signInEndpoint,
signOutEndpoint,
signUpEndpoint
} from '@slowreader/api'
import { verify } from 'argon2'
import cookieJs from 'cookie'
import { and, eq, sql } from 'drizzle-orm'
import { nanoid } from 'nanoid'
import type { ServerResponse } from 'node:http'
import { db, sessions, users } from '../db/index.ts'
import { jsonApi } from '../lib/http.ts'
async function setNewSession(
res: ServerResponse,
userId: string
): Promise<string> {
let token = nanoid()
await db.insert(sessions).values({ token, usedAt: sql`now()`, userId })
res.setHeader('Set-Cookie', `session=${token}; HttpOnly; Path=/; Secure`)
return token
}
export default (server: BaseServer): void => {
server.auth(async ({ client, cookie, token, userId }) => {
let sessionToken = token || cookie.session
if (!sessionToken) return false
let session = await db.query.sessions.findFirst({
columns: { id: true },
where: and(eq(sessions.token, sessionToken), eq(sessions.userId, userId))
})
if (session) {
await db
.update(sessions)
.set({ clientId: client.clientId, usedAt: sql`now()` })
.where(eq(sessions.id, session.id))
.catch(error => {
/* c8 ignore next */
server.logger.error(error)
})
return true
} else {
return false
}
})
jsonApi(server, signInEndpoint, async (params, res) => {
let user = await db.query.users.findFirst({
where: eq(users.id, params.userId)
})
if (user?.passwordHash) {
if (await verify(user.passwordHash, params.password)) {
let token = await setNewSession(res, params.userId)
return { session: token }
}
}
return false
})
jsonApi(server, signOutEndpoint, async (params, res, req) => {
let token = params.session
if (!token) {
token = cookieJs.parse(req.headers.cookie ?? '').session
res.setHeader(
'Set-Cookie',
'session=; Max-Age=0; HttpOnly; Path=/; Secure'
)
}
if (!token) return false
let session = await db.query.sessions.findFirst({
where: eq(sessions.token, token)
})
if (session) {
for (let client of server.connected.values()) {
if (client.clientId === session.clientId) client.destroy()
}
await db.delete(sessions).where(eq(sessions.token, token))
}
return {}
})
jsonApi(server, signUpEndpoint, async (params, res) => {
let id = params.id
let already: object | undefined
await db.transaction(async tx => {
already = await tx.query.users.findFirst({ where: eq(users.id, id) })
if (!already) await tx.insert(users).values({ id })
})
if (already) return false
await server.process(setPassword({ password: params.password, userId: id }))
let session = await setNewSession(res, id)
return { id, session }
})
}