Use jst_server.Problem everywhere, make /_lib/post_request.jst use jst_server's new...
[ndcode_site.git] / api / account / change_password.json.jst
1 let crypto = require('crypto')
2 let jst_server = (await import('@ndcode/jst_server')).default
3 let XDate = require('xdate')
4
5 return async env => {
6   let get_account = await _require('/_lib/get_account.jst')
7   let get_session = await _require('/_lib/get_session.jst')
8   let post_request = await _require('/_lib/post_request.jst')
9
10   await post_request(
11     // env
12     env,
13     // handler
14     async (old_password, new_password) => {
15       // coerce and/or validate
16       old_password = old_password.slice(0, 256)
17       new_password = new_password.slice(0, 256)
18       if (old_password.length < 8 || new_password.length < 8)
19         throw new jst_server.Problem(
20           'Bad request',
21           'Minimum length check failed',
22           400
23         )
24
25       let transaction = await env.site.database.Transaction()
26       try {
27         let root = await transaction.get({})
28         let session = await get_session(env, root)
29
30         let account = await get_account(root, session)
31         if (account === undefined)
32           throw new jst_server.Problem(
33             'Unauthorized',
34             'Please sign in first.',
35             401
36           )
37
38         if (old_password !== await account.get_json('password'))
39           throw new jst_server.Problem(
40             'Incorrect password',
41             `Provided old password did not match the expected value.`,
42             426
43           )
44
45         account.set_json('password', new_password)
46         await transaction.commit()
47       }
48       catch (error) {
49         transaction.rollback()
50         throw error
51       }
52     }
53   )
54 }