index.js
10.1 KB
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
308
309
310
311
312
313
const crypto = require('crypto');
const LocalStrategy = require('passport-local').Strategy;
const pbkdf2 = require('./lib/pbkdf2');
const errors = require('./lib/errors');
const authenticate = require('./lib/authenticate');
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);
};
options.passwordValidatorAsync =
options.passwordValidatorAsync ||
function(password) {
return new Promise((resolve, reject) => {
options.passwordValidator(password, err => (err ? reject(err) : resolve()));
});
};
// 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 find username case insensitively
options.usernameCaseInsensitive = Boolean(options.usernameCaseInsensitive || false);
// 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.findByUsername =
options.findByUsername ||
function(model, queryParameters) {
return model.findOne(queryParameters);
};
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 is incorrect';
options.errorMessages.IncorrectUsernameError = options.errorMessages.IncorrectUsernameError || 'Password or username is 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';
const 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 (options.usernameLowerCase && this[options.usernameField]) {
this[options.usernameField] = this[options.usernameField].toLowerCase();
}
next();
});
schema.methods.setPassword = function(password, cb) {
const promise = Promise.resolve()
.then(() => {
if (!password) {
throw new errors.MissingPasswordError(options.errorMessages.MissingPasswordError);
}
})
.then(() => options.passwordValidatorAsync(password))
.then(() => randomBytes(options.saltlen))
.then(saltBuffer => saltBuffer.toString(options.encoding))
.then(salt => {
this.set(options.saltField, salt);
return salt;
})
.then(salt => pbkdf2Promisified(password, salt, options))
.then(hashRaw => {
this.set(options.hashField, Buffer.from(hashRaw, 'binary').toString(options.encoding));
})
.then(() => this);
if (!cb) {
return promise;
}
promise.then(result => cb(null, result)).catch(err => cb(err));
};
schema.methods.changePassword = function(oldPassword, newPassword, cb) {
const promise = Promise.resolve()
.then(() => {
if (!oldPassword || !newPassword) {
throw new errors.MissingPasswordError(options.errorMessages.MissingPasswordError);
}
})
.then(() => this.authenticate(oldPassword))
.then(({ user }) => {
if (!user) {
throw new errors.IncorrectPasswordError(options.errorMessages.IncorrectPasswordError);
}
})
.then(() => this.setPassword(newPassword))
.then(() => this.save())
.then(() => this);
if (!cb) {
return promise;
}
promise.then(result => cb(null, result)).catch(err => cb(err));
};
schema.methods.authenticate = function(password, cb) {
const promise = Promise.resolve().then(() => {
if (this.get(options.saltField)) {
return authenticate(this, password, options);
}
return this.constructor.findByUsername(this.get(options.usernameField), true).then(user => {
if (user) {
return authenticate(user, password, options);
}
return { user: false, error: new errors.IncorrectUsernameError(options.errorMessages.IncorrectUsernameError) };
});
});
if (!cb) {
return promise;
}
promise.then(({ user, error }) => cb(null, user, error)).catch(err => cb(err));
};
if (options.limitAttempts) {
schema.methods.resetAttempts = function(cb) {
const promise = Promise.resolve().then(() => {
this.set(options.attemptsField, 0);
return this.save();
});
if (!cb) {
return promise;
}
promise.then(result => cb(null, result)).catch(err => cb(err));
};
}
// Passport Local Interface
schema.statics.authenticate = function() {
return (username, password, cb) => {
const promise = Promise.resolve()
.then(() => this.findByUsername(username, true))
.then(user => {
if (user) {
return user.authenticate(password);
}
return { user: false, error: new errors.IncorrectUsernameError(options.errorMessages.IncorrectUsernameError) };
});
if (!cb) {
return promise;
}
promise.then(({ user, error }) => cb(null, user, error)).catch(err => cb(err));
};
};
// Passport Interface
schema.statics.serializeUser = function() {
return function(user, cb) {
cb(null, user.get(options.usernameField));
};
};
schema.statics.deserializeUser = function() {
return (username, cb) => {
this.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);
}
const promise = Promise.resolve()
.then(() => {
if (!user.get(options.usernameField)) {
throw new errors.MissingUsernameError(options.errorMessages.MissingUsernameError);
}
})
.then(() => this.findByUsername(user.get(options.usernameField)))
.then(existingUser => {
if (existingUser) {
throw new errors.UserExistsError(options.errorMessages.UserExistsError);
}
})
.then(() => user.setPassword(password))
.then(() => user.save());
if (!cb) {
return promise;
}
promise.then(result => cb(null, result)).catch(err => cb(err));
};
schema.statics.findByUsername = function(username, opts, cb) {
if (typeof opts === 'function') {
cb = opts;
opts = {};
}
if (typeof opts == 'boolean') {
opts = {
selectHashSaltFields: opts
};
}
opts = opts || {};
opts.selectHashSaltFields = !!opts.selectHashSaltFields;
// if specified, convert the username to lowercase
if (username !== undefined && options.usernameLowerCase) {
username = username.toLowerCase();
}
// Add each username query field
const queryOrParameters = [];
for (let i = 0; i < options.usernameQueryFields.length; i++) {
const parameter = {};
parameter[options.usernameQueryFields[i]] = options.usernameCaseInsensitive ? new RegExp(`^${username}$`, 'i') : username;
queryOrParameters.push(parameter);
}
const query = options.findByUsername(this, { $or: queryOrParameters });
if (opts.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);
return;
}
return query;
};
schema.statics.createStrategy = function() {
return new LocalStrategy(options, this.authenticate());
};
};
function pbkdf2Promisified(password, salt, options) {
return new Promise((resolve, reject) => pbkdf2(password, salt, options, (err, hashRaw) => (err ? reject(err) : resolve(hashRaw))));
}
function randomBytes(saltlen) {
return new Promise((resolve, reject) => crypto.randomBytes(saltlen, (err, saltBuffer) => (err ? reject(err) : resolve(saltBuffer))));
}
module.exports.errors = errors;