Files: 28e873b27f171cc148c3c2ee000fc70a5bc13873 / example.js
1389 bytesRaw
1 | const Server = require('http').createServer |
2 | const Stack = require('stack') |
3 | const Cookie = require('cookie') |
4 | const Route = require('./') |
5 | |
6 | const stack = Stack( |
7 | Route([ |
8 | // login and set cookies |
9 | ['login/:id', function login (req, res, next) { |
10 | res.setHeader('Set-Cookie', Cookie.serialize('id', req.params.id, { path: '/' })) |
11 | res.setHeader('Location', '/whoami') // redirect to the whoami page. |
12 | res.statusCode = 303 |
13 | res.end() |
14 | }], |
15 | // logout and clear cookies |
16 | ['login', { |
17 | get: function view (req, res, next) { |
18 | const newId = Math.random().toString(8).substring(2) |
19 | const html = `<a href='/login/${newId}'>login!</a>` |
20 | res.setHeader('Content-Type', 'text/html') |
21 | res.end(html) |
22 | }, |
23 | }], |
24 | ['logout', function logout (req, res, next) { |
25 | res.setHeader('Set-Cookie', Cookie.serialize('id', '', { path: '/' })) |
26 | res.setHeader('Location', '/whoami') // redirect to the whoami page |
27 | res.statusCode = 303 |
28 | res.end() |
29 | }] |
30 | ]), |
31 | // check cookies, and authorize this connection (or not) |
32 | function authorize (req, res, next) { |
33 | req.id = Cookie.parse(req.headers.cookie).id || null |
34 | next() |
35 | }, |
36 | // return list of the current access rights. (for debugging) |
37 | Route('whoami', function whoami (req, res, next) { |
38 | res.end(JSON.stringify(req.id) + '\n') |
39 | }) |
40 | ) |
41 | |
42 | Server(stack).listen(5000) |
43 |
Built with git-ssb-web