Finish changing XDate.now() to env.now, new XDate() to new XDate(env.now)
[ndcode_site.git] / api / account / verify_email.json.jst
1 let crypto = require('crypto')
2 let jst_server = (await import('@ndcode/jst_server')).default
3
4 return async env => {
5   let post_request = await _require('/_lib/post_request.jst')
6
7   await post_request(
8     // env
9     env,
10     // handler
11     async (email, link_code) => {
12       // coerce and/or validate
13       email = email.slice(0, 256).toLowerCase()
14       link_code = link_code.slice(0, 256).toLowerCase()
15       if (email.length === 0 || link_code.length < 32)
16         throw new jst_server.Problem(
17           'Bad request',
18           'Minimum length check failed',
19           400
20         )
21
22       let transaction = await env.site.database.Transaction()
23       try {
24         let root = await transaction.get({})
25         let accounts = await root.get('accounts', {})
26         let account = await accounts.get(email)
27         if (account === undefined)
28           throw new jst_server.Problem(
29             'Account does not exist',
30             `Please create the account for "${email}" before attempting to verify the email verification link.`
31             421
32           )
33
34         if (await account.get_json('email_verified'))
35           throw new jst_server.Problem(
36             'Email already verified',
37             `Your email "${email}" is already verified. You can now sign in.`
38             422
39           )
40
41         let verify_email = await account.get('verify_email')
42         if (
43           verify_email === undefined ||
44             env.now >= await verify_email.get_json('expires')
45         )
46           throw new jst_server.Problem(
47             'Link code missing',
48             `Email verification link code for account "${email}" does not exist or has expired.`,
49             423
50           )
51         if (link_code !== await verify_email.get_json('link_code'))
52           throw new jst_server.Problem(
53             'Link code mismatch',
54             `Provided email verification link code "${link_code}" does not match expected value.`,
55             423
56           )
57
58         await account.delete('verify_email')
59         await account.set('email_verified', true)
60         await transaction.commit()
61       }
62       catch (error) {
63         transaction.rollback()
64         throw error
65       }
66     }
67   )
68 }