-
Notifications
You must be signed in to change notification settings - Fork 0
/
routes.js
106 lines (87 loc) · 2.55 KB
/
routes.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
97
98
99
100
101
102
103
104
105
106
var express = require('express');
var User = require('./models/user');
var passport = require('passport');
var router = express.Router();
router.use(function(req, res, next) {
res.locals.currentUser = req.user;
res.locals.errors = req.flash('error');
res.locals.infos = req.flash('info');
next();
});
router.get('/signup', function(req, res) {
res.render('signup');
});
router.get('/login', function(req, res) {
res.render('login');
});
router.post('/signup', function(req, res, next) {
var username = req.body.username;
var password = req.body.password;
User.findOne({ username: username }, function(err, user) {
if (err) { return next(err); }
if (user) {
req.flash('error', 'User already exists');
return res.redirect('/signup');
}
// TODO: instantiate a new User
// and save it to the database
var newUser = new User((
username: username
password: password
));
newUser.save(next);
});
}, passport.authenticate('login', {
successRedirect: '/',
failureRedirect: '/signup',
failureFlash: true
}));
router.get('/', function(req, res, next) {
User.find()
.sort({ createdAt: 'descending' })
.exec(function(err, users) {
if (err) { return next(err); }
res.render('index', { users: users });
});
});
router.post('/login', passport.authenticate('login', {
successRedirect: '/',
failureRedirect: '/login',
failureFlash: true
}));
router.get('/logout', function(req, res) {
req.logout();
res.redirect('/');
});
router.get('/users/:username', function(req, res, next) {
User.findOne({ username: req.params.username }, function(err, user) {
if (err) { return next(err); }
if (!user) { return next(404); }
res.render('profile', { user: user });
});
});
router.get('/edit', ensureAuthenticated, function(req, res) {
res.render('edit');
});
router.post('/edit', ensureAuthenticated, function(req, res, next) {
req.user.displayName = req.body.displayName;
req.user.bio = req.body.bio;
req.user.save(function(err) {
if (err) {
next(err);
return;
}
req.flash("info", "Profile Updated");
res.redirect('/edit');
});
});
// TODO: Add a protected route to GET '/protected'
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) {
next();
} else {
req.flash("info", "You must be logged in to see this page.");
res.redirect('/login');
}
}
module.exports = router;