Add /_lib/get_account.jst, remove env.signed_in_as
[ndcode_site.git] / api / account / change_password.json.jst
1 let crypto = require('crypto')
2 let XDate = require('xdate')
3
4 return async env => {
5   let get_account = await _require('/_lib/get_account.jst')
6   let get_session = await _require('/_lib/get_session.jst')
7   let post_request = await _require('/_lib/post_request.jst')
8   let Problem = await _require('/_lib/Problem.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 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 account = await get_account(
28           env,
29           transaction,
30           await get_session(env, transaction)
31         )
32         if (account === undefined)
33           throw new Problem('Unauthorized', 'Please sign in first.', 401)
34
35         if (old_password !== await account.get_json('password'))
36           throw new Problem(
37             'Incorrect password',
38             `Provided old password did not match the expected value.`,
39             426
40           )
41
42         account.set_json('password', new_password)
43         await transaction.commit()
44       }
45       catch (error) {
46         transaction.rollback()
47         throw error
48       }
49     }
50   )
51 }