Change /_lib/session_cookie.jst to /_lib/get_session.jst
[ndcode_site.git] / api / account / sign_up / create_account.json.jst
1 let XDate = require('xdate')
2
3 return async env => {
4   let post_request = await _require('/_lib/post_request.jst')
5   let get_session = await _require('/_lib/get_session.jst')
6   let Problem = await _require('/_lib/Problem.jst')
7
8   await post_request(
9     // env
10     env,
11     // handler
12     async (verification_code, details) => {
13       // coerce and/or validate
14       verification_code = verification_code.slice(0, 6).toLowerCase()
15       details = {
16         email: details.email.slice(0, 256).toLowerCase(),
17         given_names: details.given_names.slice(0, 256),
18         family_name: details.family_name.slice(0, 256),
19         password: details.password.slice(0, 256),
20         contact_me: details.contact_me ? true : false
21       }
22       if (
23         verification_code.length < 6 ||
24           details.given_names.length === 0 ||
25           details.password.length < 8
26       )
27         throw new Problem(
28           'Bad request',
29           'Minimum length check failed',
30           400
31         )
32
33       let transaction = await env.site.database.Transaction()
34       try {
35         // initialize env.session_key, set cookie in env.response
36         let session = await get_session(env, transaction)
37
38         let captcha = await session.get('captcha')
39         if (
40           captcha === undefined ||
41             XDate.now() >= await captcha.get_json('expires')
42         )
43           throw new Problem(
44             'No verification image in session',
45             `Please call the "/api/verification_image.png" endpoint to create a verification image, in same session as the "/api/account/sign_up/create_account.json" call and less than one hour prior.`,
46             418
47           )
48         
49         let captcha_text = await captcha.get_json('text')
50         if (verification_code !== captcha_text) {
51           console.log(`verification code mismatch, \"${verification_code}\" should be \"${captcha_text}\"`)
52
53           throw new Problem(
54             'Verification code mismatch',
55             `The provided verification code "${verification_code}" did not match the verification image.`,
56             419
57           )
58         }
59
60         let accounts = await (
61           await transaction.get({})
62         ).get('accounts', {})
63
64         if (accounts.has(details.email))
65           throw new Problem(
66             'Account already exists',
67             `The email "${details.email}" already has an account registered.`,
68             420
69           )
70
71         accounts.set_json(details.email, details)
72         await transaction.commit()
73       }
74       catch (error) {
75         transaction.rollback()
76         throw error
77       }
78     }
79   )
80 }