This repository was archived by the owner on Aug 29, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathhash-password.js
More file actions
55 lines (42 loc) · 1.74 KB
/
hash-password.js
File metadata and controls
55 lines (42 loc) · 1.74 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
const hasher = require('../utils/hash');
const merge = require('lodash.merge');
const Debug = require('debug');
const debug = Debug('@feathersjs/authentication-local:hooks:hash-password');
module.exports = function hashPassword (options = {}) {
return function (context) {
if (context.type !== 'before') {
return Promise.reject(new Error(`The 'hashPassword' hook should only be used as a 'before' hook.`));
}
const app = context.app;
const authOptions = app.get('authentication') || {};
options = merge({ passwordField: 'password' }, authOptions.local, options);
debug('Running hashPassword hook with options:', options);
const field = options.passwordField;
const hashPw = options.hash || hasher;
if (typeof field !== 'string') {
return Promise.reject(new Error(`You must provide a 'passwordField' in your authentication configuration or pass one explicitly`));
}
if (typeof hashPw !== 'function') {
return Promise.reject(new Error(`'hash' must be a function that takes a password and returns Promise that resolves with a hashed password.`));
}
if (context.data === undefined) {
debug(`hook.data is undefined. Skipping hashPassword hook.`);
return Promise.resolve(context);
}
const dataIsArray = Array.isArray(context.data);
const data = dataIsArray ? context.data : [ context.data ];
return Promise.all(data.map(item => {
if (item.hasOwnProperty(field)) {
return hashPw(item[field]).then(hashedPassword => {
return Object.assign(item, {
[field]: hashedPassword
});
});
}
return item;
})).then(results => {
context.data = dataIsArray ? results : results[0];
return context;
});
};
};