users.js
2.83 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
var express = require('express');
var router = express.Router();
var User = require('../models/User');
// Index // 1
router.get('/', function(req, res){
User.find({})
.sort({username:1})
.exec(function(err, users){
if(err) return res.json(err);
res.render('users/index', {users:users});
});
});
// 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', parseError(err));
return res.redirect('/users/new');
}
res.redirect('/users');
});
});
// show
router.get('/:username', 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', 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', function(req, res, next){
User.findOne({username:req.params.username}) // 2-1
.select('password') // 2-2
.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; // 2-3
for(var p in req.body){ // 2-4
user[p] = req.body[p];
}
// save updated user
user.save(function(err, user){
if(err){
req.flash('user', req.body);
req.flash('errors', parseError(err));
return res.redirect('/users/'+req.params.username+'/edit');
}
res.redirect('/users/'+user.username);
});
});
});
// destroy
router.delete('/:username', function(req, res){
User.deleteOne({username:req.params.username}, function(err){
if(err) return res.json(err);
res.redirect('/users');
});
});
module.exports = router;
function parseError(errors){
var parsed = {};
if(errors.name == 'ValidationError'){
for(var name in errors.errors){
var validationError = errors.errors[name];
parsed[name] = {message:validationError.message};
}
}
else if(errors.code == '11000' && errors.errmsg.indexOf('username') > 0){
parsed.username = {message:'Already exists!'};
}
else {
parsed.unhandled = JSON.stringify(errors);
}
return parsed;
}