Finish changing XDate.now() to env.now, new XDate() to new XDate(env.now)
[ndcode_site.git] / api / account / sign_up / create_account.json.jst
1 let jst_server = (await import('@ndcode/jst_server')).default
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
7   await post_request(
8     // env
9     env,
10     // handler
11     async (verification_code, details) => {
12       // coerce and/or validate
13       verification_code = verification_code.slice(0, 6).toLowerCase()
14       details = {
15         email: details.email.slice(0, 256).toLowerCase(),
16         given_names: details.given_names.slice(0, 256),
17         family_name: details.family_name.slice(0, 256),
18         password: details.password.slice(0, 256),
19         contact_me: details.contact_me ? true : false
20       }
21       if (
22         verification_code.length < 6 ||
23           details.given_names.length === 0 ||
24           details.password.length < 8
25       )
26         throw new jst_server.Problem(
27           'Bad request',
28           'Minimum length check failed',
29           400
30         )
31
32       let transaction = await env.site.database.Transaction()
33       try {
34         let root = await transaction.get()
35         let session = await get_session(env, root)
36
37         let captcha = await session.get('captcha')
38         if (
39           captcha === undefined ||
40             env.now >= await captcha.get_json('expires')
41         )
42           throw new jst_server.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/account/sign_up/create_account.json" call and less than one hour prior.`,
45             418
46           )
47
48         let captcha_text = await captcha.get_json('text')
49         if (verification_code !== captcha_text) {
50           console.log(`verification code mismatch, \"${verification_code}\" should be \"${captcha_text}\"`)
51
52           throw new jst_server.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 root.get('accounts', {})
60         if (accounts.has(details.email))
61           throw new jst_server.Problem(
62             'Account already exists',
63             `The email "${details.email}" already has an account registered.`,
64             420
65           )
66
67         accounts.set_json(details.email, details)
68         await transaction.commit()
69       }
70       catch (error) {
71         transaction.rollback()
72         throw error
73       }
74     }
75   )
76 }