-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.js
38 lines (35 loc) · 977 Bytes
/
auth.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
var passport = require('koa-passport');
var LocalStrategy = require('passport-local').Strategy;
var User = require('./models/user');
passport.serializeUser(function (user, done) {
done(null, user._id)
})
passport.deserializeUser(function (_id, done) {
User.findOne({ _id: _id }).exec()
.then((user) => {
if (!user) {
done(new Error('Deserialize error, no user found of _id', _id));
}
done(null, user)
})
})
passport.use(new LocalStrategy(
function (username, password, done) {
User.findOne({ username: username }).exec()
.then((user) => {
if (!user) {
return done(null, false, { message: 'Incorrect username.' })
}
return user.comparePassword(password);
})
.then((user) => {
if (!user) {
return done(null, false, { message: 'Incorrect password.' });
}
return done(null, user)
})
.catch((err) => {
done(err)
})
}
));