-
Notifications
You must be signed in to change notification settings - Fork 326
/
Copy pathauth.js
307 lines (255 loc) · 8.99 KB
/
auth.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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
'use strict';
// Define some pseudo module globals
var isPro = require('../libs/debug').isPro;
var isDev = require('../libs/debug').isDev;
var isDbg = require('../libs/debug').isDbg;
//
//--- Dependency inclusions
var passport = require('passport');
var jwt = require('jwt-simple');
var url = require('url');
var colors = require('ansi-colors');
//--- Model inclusions
var Strategy = require('../models/strategy.js').Strategy;
var User = require('../models/user').User;
//--- Controller inclusions
//--- Library inclusions
// var authLib = require('../libs/auth');
var loadPassport = require('../libs/passportLoader').loadPassport;
var strategyInstances = require('../libs/passportLoader').strategyInstances;
var verifyPassport = require('../libs/passportVerify').verify;
var cleanFilename = require('../libs/helpers').cleanFilename;
var addSession = require('../libs/modifySessions').add;
//--- Configuration inclusions
var allStrategies = require('./strategies.json');
//---
// Unused but removing it breaks passport
passport.serializeUser(function (aUser, aDone) {
aDone(null, aUser._id);
});
// Setup all the auth strategies
var openIdStrategies = {};
Strategy.find({}, function (aErr, aStrategies) {
// Get OpenId strategies
for (var name in allStrategies) {
if (!allStrategies[name].oauth) {
openIdStrategies[name] = true;
aStrategies.push({ 'name': name, 'openid': true });
}
}
// Load the passport module for each strategy
aStrategies.forEach(function (aStrategy) {
loadPassport(aStrategy);
});
});
// Get the referer url for redirect after login/logout
// WARNING: Also found in `./controller/index.js`
function getRedirect(aReq) {
var referer = aReq.get('Referer');
var redirect = '/';
if (referer) {
referer = url.parse(referer);
if (referer.hostname === aReq.hostname) {
redirect = referer.path;
}
}
return redirect;
}
exports.auth = function (aReq, aRes, aNext) {
function auth() {
var authenticate = null;
// Just in case someone tries a bad /auth/* url
if (!strategyInstances[strategy]) {
aNext();
return;
}
if (strategy === 'google') {
authOpts.scope = ['https://www.googleapis.com/auth/plus.login'];
}
authenticate = passport.authenticate(strategy, authOpts);
authenticate(aReq, aRes, aNext);
}
var authedUser = aReq.session.user;
var strategy = aReq.body.auth || aReq.params.strategy;
var username = aReq.body.username || aReq.session.username ||
(authedUser ? authedUser.name : null);
var authOpts = { failureRedirect: '/login?stratfail' };
var passportKey = aReq._passport.instance._key;
// Yet another passport hack.
// Initialize the passport session data only when we need it.
if (!aReq.session[passportKey] && aReq._passport.session) {
aReq.session[passportKey] = {};
aReq._passport.session = aReq.session[passportKey];
}
// Save redirect url from the form submission on the session
aReq.session.redirectTo = aReq.body.redirectTo || getRedirect(aReq);
// Allow a logged in user to add a new strategy
if (strategy && authedUser) {
aReq.session.newstrategy = strategy;
aReq.session.username = authedUser.name;
} else if (authedUser) {
aRes.redirect(aReq.session.redirectTo || '/');
delete aReq.session.redirectTo;
return;
}
if (!username) {
aRes.redirect('/login?noname');
return;
}
// Clean the username of leading and trailing whitespace,
// and other stuff that is unsafe in a url
username = cleanFilename(username.replace(/^\s+|\s+$/g, ''));
// The username could be empty after the replacements
if (!username) {
aRes.redirect('/login?noname');
return;
}
// Store the username in the session so we still have it when they
// get back from authentication
if (!aReq.session.username) {
aReq.session.username = username;
}
User.findOne({ name: { $regex: new RegExp('^' + username + '$', 'i') } },
function (aErr, aUser) {
// WARNING: No error handling at this stage
var strategies = null;
var strat = null;
if (aUser) {
// Ensure that casing is identical so we still have it, correctly, when they
// get back from authentication
if (aUser.name !== username) {
aReq.session.username = aUser.name;
}
strategies = aUser.strategies;
strat = strategies.pop();
if (aReq.session.newstrategy) { // authenticate with a new strategy
strategy = aReq.session.newstrategy;
} else if (!strategy) { // use an existing strategy
strategy = strat;
} else if (strategies.indexOf(strategy) === -1) {
// add a new strategy but first authenticate with existing strategy
aReq.session.newstrategy = strategy;
strategy = strat;
} // else use the strategy that was given in the POST
}
if (!strategy) {
aRes.redirect('/login');
return;
} else {
auth();
return;
}
});
};
exports.callback = function (aReq, aRes, aNext) {
var strategy = aReq.params.strategy;
var username = aReq.session.username;
var newstrategy = aReq.session.newstrategy;
var strategyInstance = null;
var doneUri = aReq.session.user ? '/user/preferences' : '/';
// The callback was called improperly
if (!strategy || !username) {
aNext();
return;
}
// Get the passport strategy instance so we can alter the _verify method
strategyInstance = strategyInstances[strategy];
// Hijack the private verify method so we can mess stuff up freely
// We use this library for things it was never intended to do
if (openIdStrategies[strategy]) {
if (strategy === 'steam') {
strategyInstance._verify = function (aIgnore, aId, aDone) {
verifyPassport(aId, strategy, username, aReq.session.user, aDone);
};
} else {
strategyInstance._verify = function (aId, aDone) {
verifyPassport(aId, strategy, username, aReq.session.user, aDone);
};
}
} else if (strategy === 'google') { // OpenID to OAuth2 migration
strategyInstance._verify =
function(aAccessToken, aRefreshToken, aParams, aProfile, aDone) {
var openIdId = jwt.decode(aParams.id_token, null, true).openid_id;
var oAuthId = aProfile.id;
verifyPassport([openIdId, oAuthId], strategy, username, aReq.session.user, aDone);
};
} else {
strategyInstance._verify =
function (aToken, aRefreshOrSecretToken, aProfile, aDone) {
aReq.session.profile = aProfile;
verifyPassport(aProfile.id, strategy, username, aReq.session.user, aDone);
};
}
// This callback will happen after the verify routine
var authenticate = passport.authenticate(strategy, function (aErr, aUser, aInfo) {
if (aErr) {
// Some possible catastrophic error with *passport*... and/or authentication
console.error(colors.red(aErr));
if (aInfo) {
console.warn(colors.yellow(aInfo));
}
aNext(aErr);
return;
}
// If there is some info from *passport*... display it only in development and debug modes
// This includes, but not limited to, `username is taken`
if ((isDev || isDbg) && aInfo) {
console.warn(colors.yellow(aInfo));
}
if (!aUser) {
// If there is no User then authentication could have failed
// Only display if development or debug modes
if (isDev || isDbg) {
console.error(colors.red('`User` not found'));
}
aRes.redirect(doneUri + (doneUri === '/' ? 'login' : '') + '?authfail');
return;
}
aReq.logIn(aUser, function (aErr) {
if (aErr) {
console.error('Not logged in');
console.error(aErr);
aNext(aErr);
return;
}
// Show a console notice that successfully logged in
if (isDev || isDbg) {
console.log(colors.green('Logged in'));
}
// Store the user info in the session
aReq.session.user = aUser;
// Save the last date a user sucessfully logged in
aUser.authed = new Date();
// Save the session id on the user model
aUser.sessionId = aReq.sessionID;
// Save GitHub username.
if (aReq.session.profile && aReq.session.profile.provider === 'github') {
aUser.ghUsername = aReq.session.profile.username;
}
addSession(aReq, aUser, function () {
if (newstrategy && newstrategy !== strategy) {
// Allow a user to link to another account
aRes.redirect('/auth/' + newstrategy); // NOTE: Watchpoint... careful with encoding
return;
} else {
// Delete the username that was temporarily stored
delete aReq.session.username;
delete aReq.session.newstrategy;
doneUri = aReq.session.redirectTo;
delete aReq.session.redirectTo;
aRes.redirect(doneUri);
return;
}
});
});
});
authenticate(aReq, aRes, aNext);
};
exports.validateUser = function validateUser(aReq, aRes, aNext) {
if (!aReq.session.user) {
aRes.redirect('/login');
return;
}
aNext();
return;
};