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