Major refactoring of get_session(), get_account(), get_nodemailer(), introduces ...
[ndcode_site.git] / api / globals / set.json.jst
1 let XDate = require('xdate')
2
3 return async env => {
4   let post_request = await _require('/_lib/post_request.jst')
5   let get_session = await _require('/_lib/get_session.jst')
6   let Problem = await _require('/_lib/Problem.jst')
7
8   await post_request(
9     // env
10     env,
11     // handler
12     async globals => {
13       // coerce and/or validate
14       globals = {
15         site_url: globals.site_url.slice(0, 1024),
16         site_title: globals.site_title.slice(0, 1024),
17         contact_from: globals.contact_from.slice(0, 1024),
18         contact_to: globals.contact_to.slice(0, 1024),
19         feedback_from: globals.feedback_from.slice(0, 1024),
20         feedback_to: globals.feedback_to.slice(0, 1024),
21         noreply_from: globals.noreply_from.slice(0, 1024),
22         noreply_signature: globals.noreply_signature.slice(0, 1024),
23         copyright: globals.copyright.slice(0, 1024)
24       }
25
26       let transaction = await env.site.database.Transaction()
27       try {
28         let root = await transaction.get({})
29         let session = await get_session(env, root)
30
31         let account = await get_account(root, session)
32         if (account === undefined)
33           throw new Problem('Unauthorized', 'Please sign in first.', 401)
34         if (!await account.get_json('administrator'))
35           throw new Problem('Unauthorized', 'Not administrator.', 401)
36
37         root.set_json('globals', globals)
38         await transaction.commit()
39       }
40       catch (error) {
41         transaction.rollback()
42         throw error
43       }
44     }
45   )
46 }