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