Change /_lib/session_cookie.jst to /_lib/get_session.jst
[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         // initialize env.session_key, set cookie in env.response
24         let session = await get_session(env, transaction)
25
26         let account = await (
27           await (
28             await transaction.get({})
29           ).get('accounts', {})
30         ).get(email)
31         if (
32           account === undefined ||
33             password !== await account.get_json('password')
34         )
35           throw new Problem(
36             'Unauthorized',
37             'Email and password combination was incorrect.'
38             401
39           )
40
41         if (!await account.get_json('email_verified'))
42           throw new Problem(
43             'Email not yet verified',
44             'Please verify your email address via email link before trying to sign in.',
45             425
46           )
47
48         session.set_json('signed_in_as', email)
49         await transaction.commit()
50       }
51       catch (error) {
52         transaction.rollback()
53         throw error
54       }
55     }
56   )
57 }