Files: fa11a79692a0715b585e25e0ddbeef8c39e0d6fa / example.js
2029 bytesRaw
1 | const Server = require('http').createServer |
2 | const Cookie = require('cookie') |
3 | const Route = require('./') |
4 | |
5 | const routeHandler = Route([ |
6 | Route([ |
7 | // login and set cookies |
8 | ['/login/:id', function login (req, res, context, next) { |
9 | res.setHeader('Set-Cookie', Cookie.serialize('id', context.params.id, { path: '/' })) |
10 | res.setHeader('Location', '/whoami') // redirect to the whoami page. |
11 | res.statusCode = 303 |
12 | res.end() |
13 | }], |
14 | // logout and clear cookies |
15 | ['/login', { |
16 | get: function view (req, res, context, next) { |
17 | const newId = Math.random().toString(8).substring(2) |
18 | const html = `<a href='/login/${newId}'>login!</a>` |
19 | res.setHeader('Content-Type', 'text/html') |
20 | next(null, html) |
21 | } |
22 | }], |
23 | Route(['/logout', function logout (req, res, context, next) { |
24 | res.setHeader('Set-Cookie', Cookie.serialize('id', '', { path: '/' })) |
25 | res.setHeader('Location', '/whoami') // redirect to the whoami page |
26 | res.statusCode = 303 |
27 | res.end() |
28 | }]) |
29 | ]), |
30 | // check cookies, and authorize this connection (or not) |
31 | function authorize (req, res, context, next) { |
32 | context.id = Cookie.parse(req.headers.cookie).id || null |
33 | next() |
34 | }, |
35 | // return list of the current access rights. (for debugging) |
36 | Route('/whoami', function whoami (req, res, context, next) { |
37 | res.setHeader('Content-Type', 'application/json') |
38 | next(null, context.id) |
39 | }) |
40 | ]) |
41 | |
42 | const finalHandler = (req, res) => (err, value) => { |
43 | if (err) { |
44 | console.error(err.stack) |
45 | res.statusCode = 500 |
46 | res.setHeader('Content-Type', 'text/plain') |
47 | res.end(err.stack + '\n') |
48 | } else if (value) { |
49 | res.statusCode = 200 |
50 | if (typeof value === 'string') { |
51 | res.end(value) |
52 | } else { |
53 | res.end(JSON.stringify(value, null, 2) + '\n') |
54 | } |
55 | } else { |
56 | res.statusCode = 404 |
57 | res.setHeader('Content-Type', 'text/plain') |
58 | res.end('Not Found\n') |
59 | } |
60 | } |
61 | |
62 | Server((req, res) => { |
63 | routeHandler(req, res, {}, finalHandler(req, res)) |
64 | }).listen(5000) |
65 |
Built with git-ssb-web