Implement feedback as a JSON API, fix missing await on all post_request() calls
[ndcode_site.git] / api / account / sign_in.json.jst
1 let logjson = (await import('@ndcode/logjson')).default
2
3 return async env => {
4   let globals = await env.site.get_json('/_config/globals.json')
5   let nodemailer_noreply = await env.site.get_nodemailer(
6     '/_config/nodemailer_noreply.json'
7   )
8   let post_request = await _require('/_lib/post_request.jst')
9   let session_cookie = await _require('/_lib/session_cookie.jst')
10   let Problem = await _require('/_lib/Problem.jst')
11
12   await post_request(
13     // env
14     env,
15     // handler
16     async (email, password) => {
17       // coerce and/or validate
18       email = email.slice(0, 256).toLowerCase()
19       password = password.slice(0, 256)
20       if (email.length === 0 || password.length < 8)
21         throw new Problem(
22           'Bad request',
23           'Minimum length check failed',
24           400
25         )
26
27       let transaction = await env.site.database.Transaction()
28       try {
29         // initialize env.session_key, set cookie in env.response
30         let session = await session_cookie(env, transaction)
31
32         let account = await (
33           await (
34             await transaction.get({})
35           ).get('accounts', {})
36         ).get(email)
37         if (
38           account === undefined ||
39             password !== await logjson.logjson_to_json(
40               await account.get('password')
41             )
42         )
43           throw new Problem(
44             'Unauthorized',
45             'Email and password combination was incorrect.'
46             401
47           )
48
49         if (
50           !await logjson.logjson_to_json(
51             await account.get('email_verified')
52           )
53         )
54           throw new Problem(
55             'Email not yet verified',
56             'Please verify your email address via email link before trying to sign in.',
57             425
58           )
59
60         session.set('signed_in_as', transaction.json_to_logjson(email))
61
62         await transaction.commit()
63       }
64       catch (error) {
65         transaction.rollback()
66         throw error
67       }
68     }
69   )
70 }