This repository has been archived by the owner on Dec 6, 2017. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathauthentication.js
71 lines (62 loc) · 1.78 KB
/
authentication.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
var passport = require('passport')
, LocalStrategy = require('passport-local').Strategy
, session = require('express-session');
passport.serializeUser(function(user, done) {
done(null, JSON.stringify(user))
});
passport.deserializeUser(function(user, done) {
done(null, JSON.parse(user));
});
exports.init = function(app, db) {
passport.use(new LocalStrategy(
function(email, password, done) {
db.findUserByEmailAndPassword(email, password, function(err, user) {
if(user && user.approved) {
return done(null, user);
} else if (user && !user.approved) {
return done(null, false, { message: "Membership is still pending" });
} else {
return done(null, false, { message: "Member not found with that email and password" });
}
});
}
))
app.use(session({ secret: 'keyboard dog' }));
app.use(passport.initialize());
app.use(passport.session());
// Log in page
app.get('/log_in', function (req, res, next) {
res.render('login', { errors: req.flash('error')});
next();
});
//Sign up page
app.get('/sign_up', function(req, res, next) {
res.render('signup', {errors: req.flash('error')});
next();
});
//Handle signing up
app.post('/sign_up', function(req, res, next) {
db.createUser(req.body.email, req.body.password, function(err, result) {
if(err) {
res.render('signup', {errors: err});
}
else {
res.redirect('/');
}
next();
});
});
// Handle logging in
app.post('/log_in',
passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/log_in',
failureFlash: true
})
);
//Handle logging out
app.get('/log_out', function(req, res) {
req.logout();
res.redirect('/index');
});
}