-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
207 lines (176 loc) · 6.42 KB
/
app.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
/**
* Copyright (c) Microsoft Corporation
* All Rights Reserved
* Apache License 2.0
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @flow
*/
'use strict';
/**
* Module dependencies.
*/
var express = require('express');
var cookieParser = require('cookie-parser');
var expressSession = require('express-session');
var bodyParser = require('body-parser');
var passport = require('passport');
var util = require('util');
var bunyan = require('bunyan');
var config = require('./config');
// Start QuickStart here
var OIDCStrategy = require('passport-azure-ad').OIDCStrategy;
var log = bunyan.createLogger({
name: 'Microsoft OIDC Example Web Application'
});
// Passport session setup. (Section 2)
// To support persistent login sessions, Passport needs to be able to
// serialize users into and deserialize users out of the session. Typically,
// this will be as simple as storing the user ID when serializing, and finding
// the user by ID when deserializing.
passport.serializeUser(function(user, done) {
done(null, user.oid);
});
passport.deserializeUser(function(oid, done) {
findByOid(oid, function (err, user) {
done(err, user);
});
});
// array to hold logged in users
var users = [];
var findByOid = function(oid, fn) {
for (var i = 0, len = users.length; i < len; i++) {
var user = users[i];
log.info('we are using user: ', user);
if (user.oid === oid) {
return fn(null, user);
}
}
return fn(null, null);
};
// Use the OIDCStrategy within Passport. (Section 2)
//
// Strategies in passport require a `validate` function, which accept
// credentials (in this case, an OpenID identifier), and invoke a callback
// with a user object.
passport.use(new OIDCStrategy({
redirectUrl: config.creds.returnURL,
realm: config.creds.realm,
clientID: config.creds.clientID,
clientSecret: config.creds.clientSecret,
oidcIssuer: config.creds.issuer,
identityMetadata: config.creds.identityMetadata,
skipUserProfile: config.creds.skipUserProfile,
responseType: config.creds.responseType,
responseMode: config.creds.responseMode,
allowHttpForRedirectUrl: config.creds.allowHttpForRedirectUrl,
},
function(iss, sub, profile, accessToken, refreshToken, done) {
if (!profile.oid) {
return done(new Error("No email found"), null);
}
// asynchronous verification, for effect...
process.nextTick(function () {
findByOid(profile.oid, function(err, user) {
if (err) {
return done(err);
}
if (!user) {
// "Auto-registration"
users.push(profile);
return done(null, profile);
}
return done(null, user);
});
});
}
));
// configure Express (Section 2)
var app = express();
app.configure(function() {
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.logger());
app.use(express.methodOverride());
app.use(cookieParser());
app.use(expressSession({ secret: 'keyboard cat', resave: true, saveUninitialized: false }));
app.use(bodyParser.urlencoded({ extended : true }));
// Initialize Passport! Also use passport.session() middleware, to support
// persistent login sessions (recommended).
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
app.use(express.static(__dirname + '/../../public'));
});
//Routes (Section 4)
app.get('/', function(req, res){
res.render('index', { user: req.user });
});
app.get('/account', ensureAuthenticated, function(req, res){
res.render('account', { user: req.user });
});
app.get('/login',
passport.authenticate('azuread-openidconnect', { failureRedirect: '/login' }),
function(req, res) {
log.info('Login was called in the Sample');
res.redirect('/');
});
// POST /auth/openid
// Use passport.authenticate() as route middleware to authenticate the
// request. The first step in OpenID authentication will involve redirecting
// the user to their OpenID provider. After authenticating, the OpenID
// provider will redirect the user back to this application at
// /auth/openid/return
app.get('/auth/openid',
passport.authenticate('azuread-openidconnect', { failureRedirect: '/login' }),
function(req, res) {
log.info('Authentication was called in the Sample');
res.redirect('/');
});
// GET /auth/openid/return
// Use passport.authenticate() as route middleware to authenticate the
// request. If authentication fails, the user will be redirected back to the
// login page. Otherwise, the primary route function function will be called,
// which, in this example, will redirect the user to the home page.
app.get('/auth/openid/return',
passport.authenticate('azuread-openidconnect', { failureRedirect: '/login' }),
function(req, res) {
log.info('We received a return from AzureAD.');
res.redirect('/');
});
// GET /auth/openid/return
// Use passport.authenticate() as route middleware to authenticate the
// request. If authentication fails, the user will be redirected back to the
// login page. Otherwise, the primary route function function will be called,
// which, in this example, will redirect the user to the home page.
app.post('/auth/openid/return',
passport.authenticate('azuread-openidconnect', { failureRedirect: '/login' }),
function(req, res) {
log.info('We received a return from AzureAD.');
res.redirect('/');
});
app.get('/logout', function(req, res){
req.logout();
res.redirect('/');
});
var port = process.env.PORT || 3000;
app.listen(port);
// Simple route middleware to ensure user is authenticated. (Section 4)
// Use this route middleware on any resource that needs to be protected. If
// the request is authenticated (typically via a persistent login session),
// the request will proceed. Otherwise, the user will be redirected to the
// login page.
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) { return next(); }
res.redirect('/login')
}