-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
69 lines (58 loc) · 1.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
/**
* Module dependencies
*/
var pwd = require('pwd');
/**
* Expose `model-auth`
*
* @param {String} prop
*
* @param {Model} model
*/
module.exports = function(opts) {
opts = opts || {};
var password = opts.password || 'password';
var salt = opts.salt || 'salt';
return function(Model) {
// attr
Model.attr(salt);
// on saving
Model.on('saving', function(model, done) {
if(model[salt]()) return done();
pwd.hash(model[password](), function(err, s, hash) {
model[salt](s);
model[password](hash);
done();
});
});
/**
* Model.authenticate
*
* @param {String} query or Model instance
* @param {String} password
* @param {Function} fn
*/
Model.authenticate =
Model.authorize = function authenticate(query, pass, fn) {
if(query instanceof Model) {
// query is model
checkPassword(query, pass, fn);
} else {
// find model
Model.find(query, function (err, model) {
if (err || !model) return fn(err, model);
checkPassword(model, pass, fn);
});
}
function checkPassword(model, pass, fn) {
pwd.hash(pass, model[salt](), function (err, hash) {
if (model[password]() == hash) {
return fn(null, model);
} else {
return fn(null, false);
}
});
}
};
}
};