/
index.ts
353 lines (288 loc) · 8.27 KB
/
index.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
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
import sql from "@/src/utils/db"
import { RESET_PASSWORD, sendVerifyEmail } from "@/src/utils/emails"
import Context from "@/src/utils/koa"
import { sendTelegramMessage } from "@/src/utils/notifications"
import { sendEmail } from "@/src/utils/sendEmail"
import Router from "koa-router"
import { z } from "zod"
import {
hashPassword,
sanitizeEmail,
signJwt,
verifyJwt,
verifyPassword,
} from "./utils"
import saml, { getLoginUrl } from "./saml"
import { jwtVerify } from "jose"
const auth = new Router({
prefix: "/auth",
})
auth.post("/method", async (ctx: Context) => {
const bodySchema = z.object({
email: z.string().email().transform(sanitizeEmail),
})
const { email } = bodySchema.parse(ctx.request.body)
const [samlOrg] = await sql`
select org.* from org
join account on account.org_id = org.id
where account.email = ${email}
and org.saml_enabled = true
and org.saml_idp_xml is not null
`
if (!samlOrg || !samlOrg.samlIdpXml) {
ctx.body = { method: "password" }
} else {
const url = await getLoginUrl(samlOrg.id)
ctx.body = { method: "saml", redirect: url }
}
})
auth.post("/signup", async (ctx: Context) => {
const bodySchema = z.object({
email: z.string().email().transform(sanitizeEmail),
password: z.string().min(6).optional(), // optional if SAML flow
name: z.string(),
orgName: z.string().optional(),
projectName: z.string().optional(),
employeeCount: z.string().optional(),
orgId: z.string().optional(),
token: z.string().optional(),
redirectUrl: z.string().optional(),
signupMethod: z.enum(["signup", "join"]),
})
const {
email,
password,
name,
orgName,
projectName,
employeeCount,
orgId,
signupMethod,
redirectUrl,
token,
} = bodySchema.parse(ctx.request.body)
// Spamming hotfix
if (orgName?.includes("https://") || name.includes("http://")) {
ctx.throw(403, "Bad request")
}
if (signupMethod === "signup") {
const { user, org } = await sql.begin(async (sql) => {
const plan = process.env.DEFAULT_PLAN || "free"
const [existingUser] = await sql`
select * from account where lower(email) = lower(${email})
`
if (!password) {
ctx.throw(403, "Password is required")
}
if (existingUser) {
ctx.throw(403, "User already exists")
}
const [org] =
await sql`insert into org ${sql({ name: orgName || `${name}'s Org`, plan })} returning *`
const newUser = {
name,
passwordHash: await hashPassword(password!),
email,
orgId: org.id,
role: "owner",
verified: !process.env.RESEND_KEY ? true : false,
lastLoginAt: new Date(),
}
const [user] = await sql`
insert into account ${sql(newUser)}
returning *
`
const newProject = {
name: projectName,
orgId: org.id,
}
const [project] = await sql`
insert into project ${sql(newProject)} returning *
`
await sql`
insert into account_project ${sql({ accountId: user.id, projectId: project.id })}
`
const publicKey = {
type: "public",
projectId: project.id,
apiKey: project.id,
}
await sql`
insert into api_key ${sql(publicKey)}
`
const privateKey = [
{
type: "private",
projectId: project.id,
},
]
await sql`
insert into api_key ${sql(privateKey)}
`
return { user, org }
})
const token = await signJwt({
userId: user.id,
email: user.email,
orgId: org.id,
})
await sendVerifyEmail(email, name)
await sendTelegramMessage(
`<b>🔔 New signup from ${email}</b>
${name} is ${
signupMethod === "signup"
? `building ${projectName} @ ${orgName} (${employeeCount}).`
: "joining an org."
}`,
"users",
)
ctx.body = { token }
return
} else if (signupMethod === "join") {
const { payload } = await verifyJwt(token!)
if (payload.email !== email) {
ctx.throw(403, "Invalid token")
}
const update = {
name,
verified: true,
singleUseToken: null,
}
if (password) {
update.passwordHash = await hashPassword(password)
}
await sql`
update account set ${sql(update)}
where email = ${email} and org_id = ${orgId!}
returning *
`
ctx.body = {}
return
}
})
auth.get("/join-data", async (ctx: Context) => {
const token = z.string().parse(ctx.query.token)
const {
payload: { orgId },
} = await verifyJwt(token)
const [org] = await sql`
select name, plan from org where id = ${orgId}
`
const [orgUserCountResult] = await sql`
select count(*) from account where org_id = ${orgId}
`
const orgUserCount = parseInt(orgUserCountResult.count, 10)
ctx.body = {
orgUserCount,
orgName: org?.name,
orgPlan: org?.plan,
orgId: orgId,
}
})
auth.post("/login", async (ctx: Context) => {
const bodySchema = z.object({
email: z.string().email().transform(sanitizeEmail),
password: z.string(),
})
const body = bodySchema.safeParse(ctx.request.body)
if (!body.success) {
ctx.status = 402
ctx.body = {
error: "Unauthorized",
message: "Email must be of valid format, and password must be a string",
}
return
}
const { email, password } = body.data
const [user] = await sql`
select * from account where email = ${email}
`
if (!user) {
ctx.status = 403
ctx.body = { error: "Unauthorized", message: "Invalid email or password" }
return
}
const passwordCorrect = await verifyPassword(password, user.passwordHash)
if (!passwordCorrect) {
ctx.status = 403
ctx.body = { error: "Unauthorized", message: "Invalid email or password" }
return
}
// update last login
await sql`update account set last_login_at = now() where id = ${user.id}`
const token = await signJwt({
userId: user.id,
email: user.email,
orgId: user.orgId,
})
ctx.body = { token }
})
auth.post("/request-password-reset", async (ctx: Context) => {
const bodySchema = z.object({
email: z.string().email().transform(sanitizeEmail),
})
try {
const body = bodySchema.safeParse(ctx.request.body)
if (!body.success) {
ctx.status = 400
ctx.body = { error: "Invalid email format" }
return
}
const { email } = body.data
const [user] = await sql`select id from account where email = ${email}`
const ONE_HOUR = 60 * 60
const token = await signJwt({ email }, ONE_HOUR)
await sql`update account set recovery_token = ${token} where id = ${user.id}`
const link = `${process.env.APP_URL}/reset-password?token=${token}`
await sendEmail(RESET_PASSWORD(email, link))
ctx.body = { ok: true }
} catch (error) {
console.error(error)
// Do not send error message to client if email is not found
ctx.body = {}
}
})
auth.post("/reset-password", async (ctx: Context) => {
const bodySchema = z.object({
token: z.string(),
password: z.string(),
})
const { token, password } = bodySchema.parse(ctx.request.body)
const {
payload: { email },
} = await verifyJwt<{ email: string }>(token)
const passwordHash = await hashPassword(password)
const [user] = await sql`
update account set password_hash = ${passwordHash}, last_login_at = NOW() where email = ${email} returning *
`
const authToken = await signJwt({
userId: user.id,
email: user.email,
orgId: user.orgId,
})
ctx.body = { token: authToken }
})
// Used after the SAML flow to exchange the onetime token for an auth token
auth.post("/exchange-token", async (ctx: Context) => {
const { onetimeToken } = ctx.request.body as { onetimeToken: string }
await verifyJwt(onetimeToken)
// get account with onetime_token = token
const [account] = await sql`
update account set single_use_token = null where single_use_token = ${onetimeToken} returning *
`
if (!account) {
ctx.throw(401, "Invalid onetime token")
}
const oneDay = 60 * 60 * 24
const authToken = await signJwt(
{
userId: account.id,
email: account.email,
orgId: account.orgId,
},
oneDay,
)
ctx.body = { token: authToken }
})
auth.use(saml.routes())
export default auth