Implement feedback as a JSON API, fix missing await on all post_request() calls
[ndcode_site.git] / api / verify_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     // endpoint
14     '/api/verify_password.json',
15     // handler
16     async (email, link_code) => {
17       // coerce and/or validate
18       email = email.slice(0, 256).toLowerCase()
19       link_code = link_code.slice(0, 256).toLowerCase()
20       if (email.length === 0 || link_code.length < 32)
21         throw new Problem(
22           'Bad request',
23           'Minimum length check failed',
24           400
25         )
26
27       let transaction = await env.site.database.Transaction()
28       try {
29         // initialize env.session_key, set cookie in env.response
30         await session_cookie(env, transaction)
31
32         let account = await (
33           await (
34             await transaction.get({})
35           ).get('accounts', {})
36         ).get(email)
37         if (account === undefined)
38           throw new Problem(
39             'Account does not exist',
40             `Please create the account for "${email}" before attempting to verify the password reset link.`
41             421
42           )
43
44         let verify_password = await account.get('verify_password')
45         if (
46           verify_password === undefined ||
47             XDate.now() >= await logjson.logjson_to_json(
48               await verify_password.get('expires')
49             )
50         )
51           throw new Problem(
52             'Link code missing',
53             `Password reset link code for account "${email}" does not exist or has expired.`,
54             423
55           )
56         if (
57           link_code !== await logjson.logjson_to_json(
58             await verify_password.get('link_code')
59           )
60         )
61           throw new Problem(
62             'Link code mismatch',
63             `Provided password reset link code "${link_code}" does not match expected value.`,
64             423
65           )
66
67         await account.delete('verify_password')
68         await account.set('password', await verify_password.get('password'))
69
70         await transaction.commit()
71       }
72       catch (error) {
73         transaction.rollback()
74         throw error
75       }
76     }
77   )
78 }