]> git.r.bdr.sh - rbdr/dasein/blame - lib/dasein.js
Add Login (#2)
[rbdr/dasein] / lib / dasein.js
CommitLineData
cc69fef4
RBR
1'use strict';
2
287fa13b
RBR
3const Koa = require('koa');
4const KoaJwt = require('koa-jwt');
5const KoaStatic = require('koa-static');
6const KoaRoute = require('koa-route');
7
8const AuthHandler = require('./handlers/auth');
9
cc69fef4
RBR
10const internals = {};
11
287fa13b
RBR
12internals.k401Location = '/401.html';
13internals.kMainLocation = '/';
14
cc69fef4
RBR
15module.exports = internals.Dasein = class Dasein {
16
287fa13b
RBR
17 constructor(config) {
18
19 Object.assign(this, config);
20 }
21
cc69fef4
RBR
22 run() {
23
287fa13b
RBR
24 this._initializeServer();
25 this._startServer();
26 this._printBanner();
cc69fef4
RBR
27
28 return Promise.resolve();
29 }
287fa13b
RBR
30
31 _initializeServer() {
32
33 this._app = Koa();
34
35 this._app.keys = this.cookieKeys;
36
37 this._app.use(KoaStatic(this.staticDirectory));
38
39 // Redirect all 401s to the 401 static page
40
41 this._app.use(function * (next) {
42
43 try {
44 yield next;
45 }
46 catch (err) {
47 if (err.status === 401) {
48 return this.redirect(internals.k401Location);
49 }
50
51 throw err;
52 }
53 });
54
55 this._app.use(KoaJwt({
56 secret: this.jwt.secret,
57 passthrough: true,
58 cookie: this.jwt.cookieName
59 }));
60
61 // Handlers for Twitter Auth Related Routes
62
63 const authHandler = new AuthHandler({
64 hostname: this.hostname,
65 jwt: this.jwt,
66 twitter: this.twitter
67 });
68 this._app.use(KoaRoute.get('/login', authHandler.login()));
69 this._app.use(KoaRoute.get('/login-callback', authHandler.callback()));
70 this._app.use(KoaRoute.get('/logout', authHandler.logout()));
71
72 // The index
73
74 this._app.use(function * () {
75
76 if (this.state.user) {
77 this.body = `<img src="${this.state.user.profile_image_url_https}"> Hello ${this.state.user.screen_name}`;
78 return;
79 }
80
81 this.body = 'Go to /login to login';
82 return;
83 });
84 }
85
86 _startServer() {
87
88 this._app.listen(this.port);
89 }
90
91 // Prints the banner.
92 _printBanner() {
93
94 console.log(' .');
95 console.log(' /');
96 console.log(' +-----+');
97 console.log(` | o o | - Listening Gladly, Try me on port: ${this.port}`);
98 console.log(' +-----+');
99 console.log(' +---------+');
100 console.log(' /| [][] |\\');
101 console.log(' || | |');
102 console.log(' || | \\c');
103 console.log(' ^+---------+');
104 console.log(' (.) ');
105 }
cc69fef4 106};