-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpass.js
80 lines (67 loc) · 2.14 KB
/
pass.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
var crypto = require('crypto');
var key = 'secret';
var algorithm = 'sha1';
var hash, hmac;
var mongoose = require( 'mongoose' );
var users = mongoose.model( 'users', users );
module.exports = function(passport, LocalStrategy){
function findById(id, fn) {
users.findOne({ _id : id},function(err,user){
if(err)
return fn(err);
if(user)
return fn(null,user);
return fn(new Error('User ' + id + ' does not exist'));
});
}
function findByUsername(username, fn) {
users.findOne({email : username.toLowerCase()},function(err,user){
if(err)
return fn(err);
if(user)
return fn(null,user);
return fn(null,null);
});
}
passport.serializeUser(function(user, done) {
done(null, user._id);
});
passport.deserializeUser(function(id, done) {
findById(id, function (err, user) {
done(err, user);
});
});
passport.use(new LocalStrategy(
function(username, password, done) {
// asynchronous verification, for effect...
process.nextTick(function () {
hmac = crypto.createHmac(algorithm, key);
// change to 'binary' if you want a binary digest
hmac.setEncoding('hex');
// write in the text that you want the hmac digest for
hmac.write(password);
// you can't read from the stream until you call end()
hmac.end();
// read out hmac digest
hash = hmac.read();
// Find the user by username. If there is no user with the given
// username, or the password is not correct, set the user to `false` to
// indicate failure and set a flash message. Otherwise, return the
// authenticated `user`.
findByUsername(username, function(err, user) {
if(err){
return done(err);
}
if(!user){
console.log("no user");
return done(null, false, { message: 'Username or Password were incorrect'});
}
if(user.password != hash){
return done(null, false, { message: 'Username or Password were incorrect' });
}
return done(null, user);
});
});
}
));
};