Make get_session() readonly and throw an exception if session cannot be found rather...
[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 (old_password !== await account.get_json('password'))
32           throw new jst_server.Problem(
33             'Incorrect password',
34             `Provided old password did not match the expected value.`,
35             426
36           )
37
38         account.set_json('password', new_password)
39         await transaction.commit()
40       }
41       catch (error) {
42         transaction.rollback()
43         throw error
44       }
45     }
46   )
47 }