Use (Transaction|LazyValue).get_json() instead of logjson.logjson_to_json() and ...
[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 post_request = await _require('/_lib/post_request.jst')
6   let session_cookie = await _require('/_lib/session_cookie.jst')
7   let Problem = await _require('/_lib/Problem.jst')
8
9   await post_request(
10     // env
11     env,
12     // handler
13     async (old_password, new_password) => {
14       // coerce and/or validate
15       old_password = old_password.slice(0, 256)
16       new_password = new_password.slice(0, 256)
17       if (old_password.length < 8 || new_password.length < 8)
18         throw new Problem(
19           'Bad request',
20           'Minimum length check failed',
21           400
22         )
23
24       let transaction = await env.site.database.Transaction()
25       try {
26         // initialize env.session_key, set cookie in env.response
27         await session_cookie(env, transaction)
28         if (env.signed_in_as === null)
29           throw new Problem('Unauthorized', 'Please sign in first.', 401)
30
31         let account = await (
32           await (
33             await transaction.get({})
34           ).get('accounts', {})
35         ).get(env.signed_in_as)
36
37         if (old_password !== await account.get_json('password'))
38           throw new Problem(
39             'Incorrect password',
40             `Provided old password did not match the expected value.`,
41             426
42           )
43
44         account.set_json('password', new_password)
45         await transaction.commit()
46       }
47       catch (error) {
48         transaction.rollback()
49         throw error
50       }
51     }
52   )
53 }