-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
292 lines (267 loc) · 10 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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
/**
* Copyright (c) Microsoft Corporation
* All Rights Reserved
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the 'Software'), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify,
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
* OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
* OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
'use strict';
/******************************************************************************
* Module dependencies.
*****************************************************************************/
const express = require('express');
const cookieParser = require('cookie-parser');
const expressSession = require('express-session');
const bodyParser = require('body-parser');
const methodOverride = require('method-override');
const passport = require('passport');
const bunyan = require('bunyan');
const config = require('./config');
const address = require('address');
// set up database for express session
const MongoStore = require('connect-mongo')(expressSession);
const mongoose = require('mongoose');
// Start QuickStart here
const OIDCStrategy = require('passport-azure-ad').OIDCStrategy;
const log = bunyan.createLogger({
name: 'Microsoft OIDC Example Web Application'
});
/******************************************************************************
* Set up passport in the app
******************************************************************************/
//-----------------------------------------------------------------------------
// 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
const users = [];
const findByOid = function(oid, fn) {
for (let i = 0, len = users.length; i < len; i++) {
const 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.
//
// Strategies in passport require a `verify` function, which accepts credentials
// (in this case, the `oid` claim in id_token), and invoke a callback to find
// the corresponding user object.
//
// The following are the accepted prototypes for the `verify` function
// (1) function(iss, sub, done)
// (2) function(iss, sub, profile, done)
// (3) function(iss, sub, profile, access_token, refresh_token, done)
// (4) function(iss, sub, profile, access_token, refresh_token, params, done)
// (5) function(iss, sub, profile, jwtClaims, access_token, refresh_token, params, done)
// (6) prototype (1)-(5) with an additional `req` parameter as the first parameter
//
// To do prototype (6), passReqToCallback must be set to true in the config.
//-----------------------------------------------------------------------------
passport.use(
new OIDCStrategy(
{
identityMetadata: config.creds.identityMetadata,
clientID: config.creds.clientID,
responseType: config.creds.responseType,
responseMode: config.creds.responseMode,
redirectUrl: config.creds.redirectUrl,
allowHttpForRedirectUrl: config.creds.allowHttpForRedirectUrl,
clientSecret: config.creds.clientSecret,
validateIssuer: config.creds.validateIssuer,
isB2C: config.creds.isB2C,
issuer: config.creds.issuer,
passReqToCallback: config.creds.passReqToCallback,
scope: config.creds.scope,
loggingLevel: config.creds.loggingLevel,
nonceLifetime: config.creds.nonceLifetime,
nonceMaxAmount: config.creds.nonceMaxAmount,
useCookieInsteadOfSession: config.creds.useCookieInsteadOfSession,
cookieEncryptionKeys: config.creds.cookieEncryptionKeys,
clockSkew: config.creds.clockSkew
},
function(iss, sub, profile, accessToken, refreshToken, done) {
if (!profile.oid) {
return done(new Error('No oid 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);
});
});
}
)
);
//-----------------------------------------------------------------------------
// Config the app, include middlewares
//-----------------------------------------------------------------------------
const app = express();
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(methodOverride());
app.use(cookieParser());
// set up session middleware
if (config.useMongoDBSessionStore) {
mongoose.connect(config.databaseUri);
app.use(
express.session({
secret: 'secret',
cookie: { maxAge: config.mongoDBSessionMaxAge * 1000 },
store: new MongoStore({
mongooseConnection: mongoose.connection,
clear_interval: config.mongoDBSessionMaxAge
})
})
);
} else {
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(express.static(__dirname + '/../../public'));
//-----------------------------------------------------------------------------
// Set up the route controller
//
// 1. For 'login' route and 'returnURL' route, use `passport.authenticate`.
// This way the passport middleware can redirect the user to login page, receive
// id_token etc from returnURL.
//
// 2. For the routes you want to check if user is already logged in, use
// `ensureAuthenticated`. It checks if there is an user stored in session, if not
// it will call `passport.authenticate` to ask for user to log in.
//-----------------------------------------------------------------------------
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) {
return next();
}
res.redirect('/login');
}
app.get('/', function(req, res) {
res.render('index', { user: req.user });
});
// '/account' is only available to logged in user
app.get('/account', ensureAuthenticated, function(req, res) {
res.render('account', { user: req.user });
});
app.get(
'/login',
function(req, res, next) {
passport.authenticate('azuread-openidconnect', {
response: res, // required
resourceURL: config.resourceURL, // optional. Provide a value if you want to specify the resource.
customState: 'my_state', // optional. Provide a value if you want to provide custom state value.
failureRedirect: '/'
})(req, res, next);
},
function(req, res) {
log.info('Login was called in the Sample');
res.redirect('/');
}
);
// 'GET returnURL'
// `passport.authenticate` will try to authenticate the content returned in
// query (such as authorization code). If authentication fails, user will be
// redirected to '/' (home page); otherwise, it passes to the next middleware.
app.get(
'/auth/openid/return',
function(req, res, next) {
passport.authenticate('azuread-openidconnect', {
response: res, // required
failureRedirect: '/'
})(req, res, next);
},
function(req, res) {
log.info('We received a return from AzureAD.');
res.redirect('/');
}
);
// 'POST returnURL'
// `passport.authenticate` will try to authenticate the content returned in
// body (such as authorization code). If authentication fails, user will be
// redirected to '/' (home page); otherwise, it passes to the next middleware.
app.post(
'/auth/openid/return',
function(req, res, next) {
passport.authenticate('azuread-openidconnect', {
response: res, // required
failureRedirect: '/'
})(req, res, next);
},
function(req, res) {
log.info('We received a return from AzureAD.');
res.redirect('/');
}
);
// 'logout' route, logout from passport, and destroy the session with AAD.
app.get('/logout', function(req, res) {
// eslint-disable-next-line no-unused-vars
req.session.destroy(function(err) {
req.logOut();
res.redirect(config.destroySessionUrl);
});
});
const { HOST = '0.0.0.0' } = process.env;
const { PORT = 3000 } = process.env;
let localUrlForTerminal = `http://${HOST}:${PORT}/`;
let lanUrlForTerminal = `http://${HOST}:${PORT}/`;
if (HOST === '0.0.0.0' || HOST === '::') {
localUrlForTerminal = `http://localhost:${PORT}/`;
lanUrlForTerminal = `http://${address.ip()}:${PORT}/`;
}
app.listen(PORT, () =>
// eslint-disable-next-line no-console
console.log(`
Access URLs:
--------------------------------------
Localhost: ${localUrlForTerminal}
LAN: ${lanUrlForTerminal}
--------------------------------------
Press CTRL-C to stop`)
);