-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathcontext.ts
More file actions
232 lines (219 loc) · 8.52 KB
/
context.ts
File metadata and controls
232 lines (219 loc) · 8.52 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
import type { AnyTable, Column } from 'drizzle-orm'
import { and, asc, desc, eq, like } from 'drizzle-orm'
import type { UndefinedToOptional } from 'type-fest/source/internal'
import type { AnyAccountTable, AnySessionTable, AnyUserTable, AuthConfig } from '.'
import { AccountProvider } from './constant'
import { getSessionCookie } from './utils'
import type { MinimalContext } from '../config'
type InferTableType<T extends AnyTable<{}>> = UndefinedToOptional<{
[K in keyof T['_']['columns']]: T['_']['columns'][K]['_']['notNull'] extends true
? T['_']['columns'][K]['_']['data']
: T['_']['columns'][K]['_']['data'] | null | undefined
}>
type Pagination<TField extends string = string> = {
page?: number // default 1
pageSize?: number // default 10
sort?: {
field: TField
order: 'asc' | 'desc'
}[]
}
export type AuthContext<TConfig extends AuthConfig = AuthConfig> = {
authConfig: TConfig
internalHandlers: InternalHandlers
requiredAuthenticated: (headers?: Record<string, string>) => Promise<InferTableType<AnyUserTable>>
}
export function createAuthContext<TAuthConfig extends AuthConfig, TContext extends MinimalContext>(
authConfig: TAuthConfig,
context: TContext
): AuthContext<TAuthConfig> {
const internalHandlers = createInternalHandlers(authConfig, context)
return {
authConfig: authConfig,
internalHandlers: internalHandlers,
requiredAuthenticated: async (headers?: Record<string, string>) => {
const sessionToken = getSessionCookie(headers)
if (!sessionToken) throw new Error('Unauthorized')
const session = await internalHandlers.session.findUserBySessionToken(sessionToken)
if (!session) throw new Error('Unauthorized')
if (session.expiresAt < new Date()) {
await internalHandlers.session.deleteById(session.id)
throw new Error('Session expired')
}
return {
id: session.user.id,
name: session.user.name,
email: session.user.email,
image: session.user.image,
emailVerified: session.user.emailVerified,
}
},
}
}
function createInternalHandlers<TAuthConfig extends AuthConfig>(
config: TAuthConfig,
context: MinimalContext
) {
const user = {
findById: async (id: string) => {
const table = config.user.model
const users = await context.db.select().from(table).where(eq(table.id, id))
if (users.length === 0) throw new Error('User not found')
if (users.length > 1) throw new Error('Multiple users found')
const user = users[0]
return user
},
findByEmail: async (email: string) => {
const table = config.user.model
const users = await context.db.select().from(table).where(eq(table.email, email))
if (users.length === 0) throw new Error('User not found')
if (users.length > 1) throw new Error('Multiple users found')
const user = users[0]
return user
},
list: async (pagination: Pagination<keyof AnyUserTable['_']['columns']>) => {
const { page = 1, pageSize = 10, sort } = pagination
const table = config.user.model
const users = await context.db
.select()
.from(table)
.limit(pageSize)
.offset((page - 1) * pageSize)
.orderBy(
...(sort?.map((s) => {
const column = table[s.field as keyof typeof table] as Column
return s.order === 'asc' ? asc(column) : desc(column)
}) ?? [])
)
return users
},
create: async (data: Omit<InferTableType<AnyUserTable>, 'id' | 'emailVerified'>) => {
const table = config.user.model
const user = await context.db.insert(table).values(data).returning()
return user[0]
},
}
const account = {
link: async (data: Omit<InferTableType<AnyAccountTable>, 'id' | 'emailVerified'>) => {
const table = config.account.model
const user = await context.db.insert(table).values(data).returning()
return user[0]
},
updatePassword: async (userId: string, password: string) => {
const table = config.account.model
const account = await context.db
.update(table)
.set({ password })
.where(and(eq(table.userId, userId), eq(table.providerId, AccountProvider.CREDENTIAL)))
.returning()
if (account.length === 0) throw new Error('Account not found')
if (account.length > 1) throw new Error('Multiple accounts found')
return account[0]
},
findByUserEmailAndProvider: async (email: string, providerId: AccountProvider) => {
const accounts = await context.db
.select({
user: config.user.model,
password: config.account.model.password,
})
.from(config.account.model)
.leftJoin(config.user.model, eq(config.account.model.userId, config.user.model.id))
.where(
and(eq(config.user.model.email, email), eq(config.account.model.providerId, providerId))
)
if (accounts.length === 0) throw new Error('Account not found')
if (accounts.length > 1) throw new Error('Multiple accounts found')
return accounts[0] as unknown as {
password: InferTableType<AnyAccountTable>['password']
user: InferTableType<AnyUserTable>
}
},
}
const session = {
create: async (data: { userId: string; expiresAt: Date }) => {
const table = config.session.model
const token = crypto.randomUUID()
const session = await context.db
.insert(table)
.values({ ...data, token })
.returning()
return session[0]
},
update: async (id: string, data: any) => {
const table = config.session.model
const session = await context.db.update(table).set(data).where(eq(table.id, id)).returning()
return session[0]
},
findUserBySessionToken: async (token: string) => {
const sessions = await context.db
.select({
id: config.session.model.id,
user: config.user.model,
expiresAt: config.session.model.expiresAt,
})
.from(config.session.model)
.leftJoin(config.user.model, eq(config.session.model.userId, config.user.model.id))
.where(eq(config.session.model.token, token))
if (sessions.length === 0) throw new Error('Session not found')
if (sessions.length > 1) throw new Error('Multiple sessions found')
const session = sessions[0]
return session as unknown as {
id: InferTableType<AnySessionTable>['id']
user: InferTableType<AnyUserTable>
expiresAt: InferTableType<AnySessionTable>['expiresAt']
}
},
deleteById: async (id: string) => {
const table = config.session.model
const session = await context.db.delete(table).where(eq(table.id, id)).returning()
return session[0]
},
deleteByToken: async (token: string) => {
const table = config.session.model
const session = await context.db.delete(table).where(eq(table.token, token)).returning()
return session[0]
},
deleteByUserId: async (userId: string) => {
const table = config.session.model
const session = await context.db.delete(table).where(eq(table.userId, userId)).returning()
return session[0]
},
}
const verification = {
create: async (data: { identifier: string; value: string; expiresAt: Date }) => {
const table = config.verification.model
const verification = await context.db.insert(table).values(data).returning()
return verification[0]
},
findByIdentifier: async (identifier: string) => {
const table = config.verification.model
const verifications = await context.db
.select()
.from(table)
.where(eq(table.identifier, identifier))
if (verifications.length === 0) throw new Error('Verification not found')
if (verifications.length > 1) throw new Error('Multiple verifications found')
return verifications[0]
},
delete: async (id: string) => {
const table = config.verification.model
const verification = await context.db.delete(table).where(eq(table.id, id)).returning()
if (verification.length === 0) throw new Error('Verification not found')
return verification[0]
},
deleteByUserIdAndIdentifierPrefix: async (userId: string, identifierPrefix: string) => {
const table = config.verification.model
return await context.db
.delete(table)
.where(and(eq(table.value, userId), like(table.identifier, `${identifierPrefix}%`)))
.returning()
},
}
return {
user,
account,
session,
verification,
}
}
type InternalHandlers = ReturnType<typeof createInternalHandlers>