-
Notifications
You must be signed in to change notification settings - Fork 23
/
users.js
96 lines (73 loc) · 2.42 KB
/
users.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
var express = require('express');
var mongoose = require('mongoose');
var passport = require('passport');
var router = express.Router();
var localStrategy = require('passport-local').Strategy;
var User = require("../models/user");
router.post('/register', function (req,res){
var username = req.body.username;
var email = req.body.email;
var password = req.body.password;
var password2= req.body.password2;
//Validation
req.checkBody('username', 'Name is required').notEmpty();
req.checkBody('email', 'Email is not valid').isEmail();
req.checkBody('password', 'Password is required').notEmpty();
req.checkBody('password2', 'Passwords do not match').equals(req.body.password)
var errors = req.validationErrors();
if (errors) {
res.render('register', {
errors: errors
});
}
else {
var newUser = new User({
username: username,
email: email,
password: password
});
User.createUser(newUser, function (err, user){
if (err) throw err;
console.log(user);
});
req.flash("success_msg", "You are registered and can now login");
res.redirect("/#/users/login");
}
});
passport.use(new localStrategy(
function(username, password, done) {
User.getUserByUsername(username, function(err, user) {
if (err) throw err;
if (!user) {
return done(null, false, {message: 'Unknown User'});
}
User.comparePassword(password, user.password, function(err, isMatch){
if (err) throw err;
if (isMatch) {
return done(null, user);
} else {
return done(null, false, {message: 'Invalid Password'});
}
});
});
}
));
passport.serializeUser(function(user,done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done){
User.getUserById(id, function(err,user) {
done(err, user);
})
});
router.post('/login',
passport.authenticate('local', {successRedirect: '/', failureRedirect: 'users/login', failureFlash: true }),
function(req, res) {
res.redirect("/#/users/login");
});
router.get('/logout', function (req, res) {
req.logout();
req.flash('success_msg', 'You are logged out');
res.redirect('/#/users/login')
});
module.exports = router;