-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.js
69 lines (61 loc) · 1.98 KB
/
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
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
const passport = require('passport');
const LocalStrategy = require('passport-local');
const GitHubStrategy = require('passport-github').Strategy;
const bcrypt = require('bcrypt');
const ObjectID = require('mongodb').ObjectID;
const dotenv = require('dotenv');
dotenv.config();
module.exports = function(app, myDataBase) {
app.use(passport.initialize());
app.use(passport.session())
passport.serializeUser((user, done) => {
done(null, user._id);
});
passport.deserializeUser((id, done) => {
myDataBase.findOne({_id: new ObjectID(id)}, (err, doc) => {
done(null, doc);
});
});
passport.use(new LocalStrategy(
function(username, password, done) {
myDataBase.findOne({ username: username }, function(err, user) {
console.log('User ' + username + ' attempted to log in');
if (err) { return done(err); }
if (!user) { return done(null, false); }
if (!bcrypt.compareSync(password, user.password)) { return done(null, false); }
return done(null, user);
});
}
));
passport.use(new GitHubStrategy({
clientID: process.env.GITHUB_CLIENT_ID,
clientSecret: process.env.GITHUB_CLIENT_SECRET,
callbackURL: "https://boilerplate-advancednode.gitaud.repl.co/auth/github/callback"
}, function(accessToken, refreshToken, profile, cb) {
// console.log(profile);
// Database logic here
myDataBase.findOneAndUpdate(
{ id: profile.id },
{
$setOnInsert: {
id: profile.id,
name: profile.displayName || 'John Doe',
photo: profile._json.avatar_url || '',
email: Array.isArray(profile.emails) ? profile.emails[0].value : 'No public email',
created_on: new Date(),
provider: profile.provider || ''
},
$set: {
last_login: new Date()
},
$inc: {
login_count: 1
}
},
{upsert: true, new: true },
(err, doc) => {
return cb(null, doc.value);
}
);
}));
}