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