-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
41 lines (32 loc) · 1.12 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
const { ValidationError } = require('sequelize');
const bcrypt = require('bcryptjs');
const DEFAULT_OPTIONS = {
field: 'password',
rounds: 12,
compare: 'authenticate',
};
const useBcrypt = (Model, options = DEFAULT_OPTIONS) => {
const opts = { ...DEFAULT_OPTIONS, ...options };
const hashField = function (instance) {
try {
const changedKey = Array.from(instance._changed).find(key => key === opts.field);
if (!changedKey) return;
const fieldDefinition = instance.rawAttributes[changedKey];
if (!fieldDefinition) return;
const plainValue = instance[changedKey];
if (!plainValue) return;
const salt = bcrypt.genSaltSync(opts.rounds);
const hashedValue = bcrypt.hashSync(plainValue, salt);
instance[changedKey] = hashedValue;
} catch (err) {
throw new ValidationError(err.message);
}
};
Model.prototype[opts.compare] = function (plainValue) {
return bcrypt.compareSync(plainValue, this._previousDataValues[opts.field]);
};
Model.addHook('beforeSave', hashField);
};
exports.bcrypt = bcrypt;
exports.useBcrypt = useBcrypt;
module.exports = useBcrypt;