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