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