-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathput.ts
More file actions
88 lines (81 loc) · 2.34 KB
/
put.ts
File metadata and controls
88 lines (81 loc) · 2.34 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
import { usersMeAuthEmailPut } from '@rctf/api-types/routes'
import { makeFastifyRoute } from '../../../helpers'
import { v4 as uuidv4 } from 'uuid'
import emailValidator from 'email-validator'
import config from '../../../../config/server'
import { makeLogin } from '../../../../cache/login'
import { normalizeEmail } from '../../../../util/normalize'
import { divisionAllowed } from '../../../../util/restrict'
import { getToken, tokenKinds } from '../../../../auth/token'
import { getUserByEmail, updateUser } from '../../../../database/users'
import { sendVerification } from '../../../../email'
import {
checkProtectedAction,
RecaptchaProtectedActions,
verifyRecaptchaCode,
} from '../../../../util/recaptcha'
const recaptchaEnabled = checkProtectedAction(
RecaptchaProtectedActions.setEmail
)
export default makeFastifyRoute(
usersMeAuthEmailPut,
async ({ req, user, res }) => {
if (
recaptchaEnabled &&
(!req.body.recaptchaCode ||
!(await verifyRecaptchaCode(req.body.recaptchaCode)))
) {
return res.badRecaptchaCode()
}
const email = normalizeEmail(req.body.email)
if (!emailValidator.validate(email)) {
return res.badEmail()
}
if (config.email) {
const checkUser = await getUserByEmail({
email,
})
if (checkUser !== undefined) {
return res.badKnownEmail()
}
if (config.divisionACLs && !divisionAllowed(email, user.division)) {
return res.badEmailChangeDivision()
}
} else {
let result
try {
result = await updateUser({
id: user.id,
email,
})
} catch (e) {
if (e instanceof Object) {
const { constraint } = e as { constraint?: string }
if (constraint === 'users_email_key') {
return res.badKnownEmail()
}
}
throw e
}
if (result === undefined) {
return res.badUnknownUser()
}
return res.goodEmailSet()
}
const verifyUuid = uuidv4()
await makeLogin({ id: verifyUuid })
const verifyToken = await getToken(tokenKinds.verify, {
verifyId: verifyUuid,
kind: 'update',
userId: user.id,
email,
division: user.division,
})
await sendVerification({
email,
kind: 'update',
token: verifyToken,
})
return res.goodVerifySent()
}
)