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