Implement a command-line interface to the running webserver, and a way to get/set...
[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         if (env.signed_in_as === null)
30           throw new Problem('Unauthorized', 'Please sign in first.', 401)
31
32         let account = await (
33           await (
34             await transaction.get({})
35           ).get('accounts', {})
36         ).get(env.signed_in_as)
37
38         if (
39           old_password !== await logjson.logjson_to_json(
40             await account.get('password')
41           )
42         )
43           throw new Problem(
44             'Incorrect password',
45             `Provided old password did not match the expected value.`,
46             426
47           )
48
49         await account.set(
50           'password',
51           transaction.json_to_logjson(new_password)
52         )
53
54         await transaction.commit()
55       }
56       catch (error) {
57         transaction.rollback()
58         throw error
59       }
60     }
61   )
62 }