-
Notifications
You must be signed in to change notification settings - Fork 0
/
express-example.js
67 lines (56 loc) · 1.87 KB
/
express-example.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
const express = require('express');
const passport = require('passport');
const ControlTowerStrategy = require('passport-control-tower');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const app = express();
function isAuthenticated(req, res, next) {
if (req.isAuthenticated()) return next();
// if they aren't redirect them to the home page
res.redirect('/');
}
// Use the Control Tower Strategy within Passport.
const controlTowerStrategy = new ControlTowerStrategy({
controlTowerUrl: '[CONTROL_TOWER_API_URL]',
callbackUrl: '[YOUR_CALLBACK_URL]' // auth path
});
passport.use(controlTowerStrategy);
// Passport session setup.
// To support persistent login sessions, Passport needs to be able to
// serialize users into and deserialize users out of the session.
passport.serializeUser(function (user, done) {
done(null, user);
});
passport.deserializeUser(function (obj, done) {
done(null, obj);
});
// configure Express
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(require('express-session')({ secret: 'keyboard cat', resave: false, saveUninitialized: false }));
// Initialize Passport! Also use passport.session() middleware, to support
// persistent login sessions (recommended).
app.use(passport.initialize());
app.use(passport.session());
app.get('/', function (req, res) {
res.send('Welcome!');
});
app.get('/private', isAuthenticated, function (req, res) {
res.send('Success!');
});
// This should be callback URL
app.get('/auth', passport.authenticate('control-tower'), function (req, res) {
// Success
res.redirect('/private');
});
app.get('/login', function(req, res) {
controlTowerStrategy.login(req, res);
});
app.get('/logout', function (req, res) {
req.session.destroy();
req.logout();
// Success
res.redirect('/');
});
app.listen(3000);