1b65966200d510b9d869cefaad25fa5bc1b19fe9
[ndcode_site.git] / api / account / verify_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 (email, link_code) => {
14       // coerce and/or validate
15       email = email.slice(0, 256).toLowerCase()
16       link_code = link_code.slice(0, 256).toLowerCase()
17       if (email.length === 0 || link_code.length < 32)
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
29         let account = await (
30           await (
31             await transaction.get({})
32           ).get('accounts', {})
33         ).get(email)
34         if (account === undefined)
35           throw new Problem(
36             'Account does not exist',
37             `Please create the account for "${email}" before attempting to verify the password reset link.`
38             421
39           )
40
41         let verify_password = await account.get('verify_password')
42         if (
43           verify_password === undefined ||
44             XDate.now() >= await verify_password.get_json('expires')
45         )
46           throw new Problem(
47             'Link code missing',
48             `Password reset link code for account "${email}" does not exist or has expired.`,
49             423
50           )
51         if (link_code !== await verify_password.get_json('link_code'))
52           throw new Problem(
53             'Link code mismatch',
54             `Provided password reset link code "${link_code}" does not match expected value.`,
55             423
56           )
57
58         await account.delete('verify_password')
59         await account.set('password', await verify_password.get('password'))
60
61         await transaction.commit()
62       }
63       catch (error) {
64         transaction.rollback()
65         throw error
66       }
67     }
68   )
69 }