forked from rkusa/koa-passport-example
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
105 lines (87 loc) · 2.13 KB
/
server.js
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
const Koa = require('koa')
const app = new Koa()
// trust proxy
app.proxy = true
// sessions
const session = require('koa-session')
app.keys = ['your-session-secret']
app.use(session({}, app))
// body parser
const bodyParser = require('koa-bodyparser')
app.use(bodyParser())
// authentication
require('./auth')
const passport = require('koa-passport')
app.use(passport.initialize())
app.use(passport.session())
// routes
const fs = require('fs')
const route = require('koa-route')
app.use(route.get('/', function(ctx) {
ctx.type = 'html'
ctx.body = fs.createReadStream('views/login.html')
}))
app.use(route.post('/custom', function(ctx) {
return passport.authenticate('local', function(err, user, info, status) {
if (user === false) {
ctx.body = { success: false }
ctx.throw(401)
} else {
ctx.body = { success: true }
return ctx.login(user)
}
})(ctx)
}))
// POST /login
app.use(route.post('/login',
passport.authenticate('local', {
successRedirect: '/app',
failureRedirect: '/'
})
))
app.use(route.get('/logout', function(ctx) {
ctx.logout()
ctx.redirect('/')
}))
app.use(route.get('/auth/facebook',
passport.authenticate('facebook')
))
app.use(route.get('/auth/facebook/callback',
passport.authenticate('facebook', {
successRedirect: '/app',
failureRedirect: '/'
})
))
app.use(route.get('/auth/twitter',
passport.authenticate('twitter')
))
app.use(route.get('/auth/twitter/callback',
passport.authenticate('twitter', {
successRedirect: '/app',
failureRedirect: '/'
})
))
app.use(route.get('/auth/google',
passport.authenticate('google')
))
app.use(route.get('/auth/google/callback',
passport.authenticate('google', {
successRedirect: '/app',
failureRedirect: '/'
})
))
// Require authentication for now
app.use(function(ctx, next) {
if (ctx.isAuthenticated()) {
return next()
} else {
ctx.redirect('/')
}
})
app.use(route.get('/app', function(ctx) {
ctx.type = 'html'
ctx.body = fs.createReadStream('views/app.html')
}))
// start server
const port = process.env.PORT || 3000
app.listen(port, () => console.log('Server listening on', port))