d8fc5bebdc4c4141f39a6cce63249c02fd98a027
[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 session_cookie = await _require('/_lib/session_cookie.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         // initialize env.session_key, set cookie in env.response
29         await session_cookie(env, transaction)
30         if (env.signed_in_as === null)
31           throw new Problem('Unauthorized', 'Please sign in first.', 401)
32
33         let root = await transaction.get({})
34         let account = await (
35           await root.get('accounts', {})
36         ).get(env.signed_in_as)
37         if (!await account.get_json('administrator'))
38           throw new Problem('Unauthorized', 'Not administrator.', 401)
39
40         root.set_json('globals', globals)
41         await transaction.commit()
42       }
43       catch (error) {
44         transaction.rollback()
45         throw error
46       }
47     }
48   )
49 }