Use jst_server.Problem everywhere, make /_lib/post_request.jst use jst_server's new...
[ndcode_site.git] / api / account / sign_up / create_account.json.jst
1 let jst_server = (await import('@ndcode/jst_server')).default
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
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 jst_server.Problem(
28           'Bad request',
29           'Minimum length check failed',
30           400
31         )
32
33       let transaction = await env.site.database.Transaction()
34       try {
35         let root = await transaction.get({})
36         let session = await get_session(env, root)
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 jst_server.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 jst_server.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 root.get('accounts', {})
61         if (accounts.has(details.email))
62           throw new jst_server.Problem(
63             'Account already exists',
64             `The email "${details.email}" already has an account registered.`,
65             420
66           )
67
68         accounts.set_json(details.email, details)
69         await transaction.commit()
70       }
71       catch (error) {
72         transaction.rollback()
73         throw error
74       }
75     }
76   )
77 }