Implement feedback as a JSON API, fix missing await on all post_request() calls
[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 session_cookie = await _require('/_lib/session_cookie.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 session_cookie(env, transaction)
37
38         let captcha = await session.get('captcha')
39         if (captcha === undefined || XDate.now() >= captcha.get('expires'))
40           throw new Problem(
41             'No verification image in session',
42             `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.`,
43             418
44           )
45         
46         let captcha_text = await captcha.get('text')
47         if (verification_code !== captcha_text) {
48           console.log(`verification code mismatch, \"${verification_code}\" should be \"${captcha_text}\"`)
49
50           throw new Problem(
51             'Verification code mismatch',
52             `The provided verification code "${verification_code}" did not match the verification image.`,
53             419
54           )
55         }
56
57         let accounts = await (
58           await transaction.get({})
59         ).get('accounts', {})
60
61         if (accounts.has(details.email))
62           throw new Problem(
63             'Account already exists',
64             `The email "${details.email}" already has an account registered.`,
65             420
66           )
67         accounts.set(details.email, transaction.json_to_logjson(details))
68
69         await transaction.commit()
70       }
71       catch (error) {
72         transaction.rollback()
73         throw error
74       }
75     }
76   )
77 }