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