Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
64 lines (44 loc) · 1.27 KB
/
Copy pathapp.js
File metadata and controls
64 lines (44 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
"use strict"
const
Router = require('koa-router'),
passport = require('./auth'),
koa = require('koa'),
app = koa();
//Middleware: request logger
function *reqlogger(next){
console.log('%s - %s %s',new Date().toISOString(), this.req.method, this.req.url);
yield next;
}
app.use(reqlogger);
//Initialize passport
app.use(passport.initialize());
app.use(Router(app));
app.get('/', function *(){
console.log('Express-style example');
this.body = "This is root page ('/')";
});
const publicRouter = new Router();
//Configure /auth/github & /auth/github/callback
publicRouter.get('/auth/github', passport.authenticate('github', {scope: ['user','repo']}));
publicRouter.get('/auth/github/callback',
passport.authenticate('github', {successRedirect:'/', failureRedirect: '/'})
);
app.use(publicRouter.middleware());
//Secures routes
const securedRouter = new Router();
//Middleware: authed
function *authed(next){
if (this.req.isAuthenticated()){
yield next;
} else {
this.redirect('/auth/github');
}
}
securedRouter.get('/app', authed, function *(){
this.body = 'Secured Zone: koa-tutorial\n' + JSON.stringify(this.req.user, null, '\t');
});
app.use(securedRouter.middleware());
app.use(function *(){
this.body = 'Hello World';
});
app.listen(3000);