forked from saintedlama/passport-local-mongoose
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
305 lines (248 loc) · 10.4 KB
/
index.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
var crypto = require('crypto');
var LocalStrategy = require('passport-local').Strategy;
var errors = require('./lib/errors.js');
var scmp = require('scmp');
module.exports = function(schema, options) {
options = options || {};
options.saltlen = options.saltlen || 32;
options.iterations = options.iterations || 25000;
options.keylen = options.keylen || 512;
options.encoding = options.encoding || 'hex';
options.digestAlgorithm = options.digestAlgorithm || 'sha256'; // To get a list of supported hashes use crypto.getHashes()
options.passwordValidator = options.passwordValidator || function(password, cb) { cb(null); };
// Populate field names with defaults if not set
options.usernameField = options.usernameField || 'username';
options.usernameUnique = options.usernameUnique === undefined ? true : options.usernameUnique;
// Populate username query fields with defaults if not set,
// otherwise add username field to query fields.
if (options.usernameQueryFields) {
options.usernameQueryFields.push(options.usernameField);
} else {
options.usernameQueryFields = [options.usernameField];
}
// option to convert username to lowercase when finding
options.usernameLowerCase = options.usernameLowerCase || false;
options.hashField = options.hashField || 'hash';
options.saltField = options.saltField || 'salt';
if (options.limitAttempts) {
options.lastLoginField = options.lastLoginField || 'last';
options.attemptsField = options.attemptsField || 'attempts';
options.interval = options.interval || 100; // 100 ms
options.maxInterval = options.maxInterval || 300000; // 5 min
options.maxAttempts = options.maxAttempts || Infinity;
}
options.errorMessages = options.errorMessages || {};
options.errorMessages.MissingPasswordError = options.errorMessages.MissingPasswordError || 'No password was given';
options.errorMessages.AttemptTooSoonError = options.errorMessages.AttemptTooSoonError || 'Account is currently locked. Try again later';
options.errorMessages.TooManyAttemptsError = options.errorMessages.TooManyAttemptsError || 'Account locked due to too many failed login attempts';
options.errorMessages.NoSaltValueStoredError = options.errorMessages.NoSaltValueStoredError || 'Authentication not possible. No salt value stored';
options.errorMessages.IncorrectPasswordError = options.errorMessages.IncorrectPasswordError || 'Password or username are incorrect';
options.errorMessages.IncorrectUsernameError = options.errorMessages.IncorrectUsernameError || 'Password or username are incorrect';
options.errorMessages.MissingUsernameError = options.errorMessages.MissingUsernameError|| 'No username was given';
options.errorMessages.UserExistsError = options.errorMessages.UserExistsError|| 'A user with the given username is already registered';
var pbkdf2 = function(password, salt, callback) {
if (crypto.pbkdf2.length >= 6) {
crypto.pbkdf2(password, salt, options.iterations, options.keylen, options.digestAlgorithm, callback);
} else {
crypto.pbkdf2(password, salt, options.iterations, options.keylen, callback);
}
};
var schemaFields = {};
if (!schema.path(options.usernameField)) {
schemaFields[options.usernameField] = {type: String, unique: options.usernameUnique};
}
schemaFields[options.hashField] = {type: String, select: false};
schemaFields[options.saltField] = {type: String, select: false};
if (options.limitAttempts) {
schemaFields[options.attemptsField] = {type: Number, default: 0};
schemaFields[options.lastLoginField] = {type: Date, default: Date.now};
}
schema.add(schemaFields);
schema.pre('save', function(next) {
// if specified, convert the username to lowercase
if (options.usernameLowerCase && this[options.usernameField]) {
this[options.usernameField] = this[options.usernameField].toLowerCase();
}
next();
});
schema.methods.setPassword = function(password, cb) {
if (!password) {
return cb(new errors.MissingPasswordError(options.errorMessages.MissingPasswordError));
}
var self = this;
options.passwordValidator(password, function(err) {
if (err) {
return cb(err);
}
crypto.randomBytes(options.saltlen, function(randomBytesErr, buf) {
if (randomBytesErr) {
return cb(randomBytesErr);
}
var salt = buf.toString(options.encoding);
pbkdf2(password, salt, function(pbkdf2Err, hashRaw) {
if (pbkdf2Err) {
return cb(pbkdf2Err);
}
self.set(options.hashField, new Buffer(hashRaw, 'binary').toString(options.encoding));
self.set(options.saltField, salt);
cb(null, self);
});
});
});
};
function authenticate(user, password, cb) {
if (options.limitAttempts) {
var attemptsInterval = Math.pow(options.interval, Math.log(user.get(options.attemptsField) + 1));
var calculatedInterval = (attemptsInterval < options.maxInterval) ? attemptsInterval : options.maxInterval;
if (Date.now() - user.get(options.lastLoginField) < calculatedInterval) {
user.set(options.lastLoginField, Date.now());
user.save();
return cb(null, false, new errors.AttemptTooSoonError(options.errorMessages.AttemptTooSoonError));
}
if (user.get(options.attemptsField) >= options.maxAttempts) {
return cb(null, false, new errors.TooManyAttemptsError(options.errorMessages.TooManyAttemptsError));
}
}
if (!user.get(options.saltField)) {
return cb(null, false, new errors.NoSaltValueStoredError(options.errorMessages.NoSaltValueStoredError));
}
pbkdf2(password, user.get(options.saltField), function(err, hashRaw) {
if (err) {
return cb(err);
}
var hash = new Buffer(hashRaw, 'binary').toString(options.encoding);
if (scmp(hash, user.get(options.hashField))) {
if (options.limitAttempts) {
user.set(options.lastLoginField, Date.now());
user.set(options.attemptsField, 0);
user.save();
}
return cb(null, user);
} else {
if (options.limitAttempts) {
user.set(options.lastLoginField, Date.now());
user.set(options.attemptsField, user.get(options.attemptsField) + 1);
user.save(function(saveErr) {
if (saveErr) { return cb(saveErr); }
if (user.get(options.attemptsField) >= options.maxAttempts) {
return cb(null, false, new errors.TooManyAttemptsError(options.errorMessages.TooManyAttemptsError));
} else {
return cb(null, false, new errors.IncorrectPasswordError(options.errorMessages.IncorrectPasswordError));
}
});
} else {
return cb(null, false, new errors.IncorrectPasswordError(options.errorMessages.IncorrectPasswordError));
}
}
});
}
schema.methods.authenticate = function(password, cb) {
var self = this;
// With hash/salt marked as "select: false" - load model including the salt/hash fields form db and authenticate
if (!self.get(options.saltField)) {
self.constructor.findByUsername(self.get(options.usernameField), true, function(err, user) {
if (err) { return cb(err); }
if (user) {
return authenticate(user, password, cb);
} else {
return cb(null, false, new errors.IncorrectUsernameError(options.errorMessages.IncorrectUsernameError));
}
});
} else {
return authenticate(self, password, cb);
}
};
if (options.limitAttempts) {
schema.methods.resetAttempts = function(cb) {
this.set(options.attemptsField, 0);
this.save(cb);
};
}
schema.statics.authenticate = function() {
var self = this;
return function(username, password, cb) {
self.findByUsername(username, true, function(err, user) {
if (err) { return cb(err); }
if (user) {
return user.authenticate(password, cb);
} else {
return cb(null, false, new errors.IncorrectUsernameError(options.errorMessages.IncorrectUsernameError));
}
});
};
};
schema.statics.serializeUser = function() {
return function(user, cb) {
cb(null, user.get(options.usernameField));
};
};
schema.statics.deserializeUser = function() {
var self = this;
return function(username, cb) {
self.findByUsername(username, cb);
};
};
schema.statics.register = function(user, password, cb) {
// Create an instance of this in case user isn't already an instance
if (!(user instanceof this)) {
user = new this(user);
}
if (!user.get(options.usernameField)) {
return cb(new errors.MissingUsernameError(options.errorMessages.MissingUsernameError));
}
var self = this;
self.findByUsername(user.get(options.usernameField), function(err, existingUser) {
if (err) { return cb(err); }
if (existingUser) {
return cb(new errors.UserExistsError(options.errorMessages.UserExistsError));
}
user.setPassword(password, function(setPasswordErr, user) {
if (setPasswordErr) {
return cb(setPasswordErr);
}
user.save(function(saveErr) {
if (saveErr) {
return cb(saveErr);
}
cb(null, user);
});
});
});
};
schema.statics.findByUsername = function(username, selectHashSaltFields, cb) {
if (typeof cb === 'undefined') {
cb = selectHashSaltFields;
selectHashSaltFields = false;
}
// if specified, convert the username to lowercase
if (username !== undefined && options.usernameLowerCase) {
username = username.toLowerCase();
}
// Add each username query field
var queryOrParameters = [];
for (var i = 0; i < options.usernameQueryFields.length; i++) {
var parameter = {};
parameter[options.usernameQueryFields[i]] = username;
queryOrParameters.push(parameter);
}
var query = this.findOne({$or: queryOrParameters});
if (selectHashSaltFields) {
query.select('+' + options.hashField + " +" + options.saltField);
}
if (options.selectFields) {
query.select(options.selectFields);
}
if (options.populateFields) {
query.populate(options.populateFields);
}
if (cb) {
query.exec(cb);
} else {
return query;
}
};
schema.statics.createStrategy = function() {
return new LocalStrategy(options, this.authenticate());
};
};
module.exports.errors = errors;