b36bb0d7ed81799b5b337baa97053be0edd98129
[ndcode_site.git] / api / account / change_password.json.jst
1 let crypto = require('crypto')
2 let logjson = (await import('@ndcode/logjson')).default
3 let XDate = require('xdate')
4
5 return async env => {
6   let post_request = await _require('/_lib/post_request.jst')
7   let session_cookie = await _require('/_lib/session_cookie.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         // initialize env.session_key, set cookie in env.response
28         await session_cookie(env, transaction)
29
30         let account = await (
31           await (
32             await transaction.get({})
33           ).get('accounts', {})
34         ).get(env.signed_in_as)
35
36         if (
37           old_password !== await logjson.logjson_to_json(
38             await account.get('password')
39           )
40         )
41           throw new Problem(
42             'Incorrect password',
43             `Provided old password did not match the expected value.`,
44             426
45           )
46
47         await account.set(
48           'password',
49           transaction.json_to_logjson(new_password)
50         )
51
52         await transaction.commit()
53       }
54       catch (error) {
55         transaction.rollback()
56         throw error
57       }
58     }
59   )
60 }