users.js
2.35 KB
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
var express = require('express');
var router = express.Router();
var User = require('../models/User');
var util = require('../util');
// New
router.get('/new', function(req, res){
var user = req.flash('user')[0] || {};
var errors = req.flash('errors')[0] || {};
res.render('users/new', { user:user, errors:errors });
});
// create
router.post('/', function(req, res){
User.create(req.body, function(err, user){
if(err){
req.flash('user', req.body);
req.flash('errors', util.parseError(err));
return res.redirect('/users/new');
}
res.redirect('/');
});
});
// show
router.get('/:username', util.isLoggedin, checkPermission, function(req, res){
User.findOne({username:req.params.username}, function(err, user){
if(err) return res.json(err);
res.render('users/show', {user:user});
});
});
// edit
router.get('/:username/edit', util.isLoggedin, checkPermission, function(req, res){
var user = req.flash('user')[0];
var errors = req.flash('errors')[0] || {};
if(!user){
User.findOne({username:req.params.username}, function(err, user){
if(err) return res.json(err);
res.render('users/edit', { username:req.params.username, user:user, errors:errors });
});
}
else {
res.render('users/edit', { username:req.params.username, user:user, errors:errors });
}
});
// update
router.put('/:username', util.isLoggedin, checkPermission, function(req, res, next){
User.findOne({username:req.params.username})
.select('password')
.exec(function(err, user){
if(err) return res.json(err);
// update user object
user.originalPassword = user.password;
user.password = req.body.newPassword? req.body.newPassword : user.password;
for(var p in req.body){
user[p] = req.body[p];
}
// save updated user
user.save(function(err, user){
if(err){
req.flash('user', req.body);
req.flash('errors', util.parseError(err));
return res.redirect('/users/'+req.params.username+'/edit');
}
res.redirect('/users/'+user.username);
});
});
});
module.exports = router;
// private functions
function checkPermission(req, res, next){
User.findOne({username:req.params.username}, function(err, user){
if(err) return res.json(err);
if(user.id != req.user.id) return util.noPermission(req, res);
next();
});
}