-
Notifications
You must be signed in to change notification settings - Fork 0
/
users-router.js
181 lines (166 loc) · 4.48 KB
/
users-router.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
'use strict';
const express = require('express');
const mongoose = require('mongoose');
const router = express.Router();
router.use(express.json());
router.use(express.static('public/searches'));
mongoose.Promise = global.Promise;
const { Users } = require('./model');
router.get('/', (req, res) => {
console.log('Retrieving Users');
Users.find()
.then(users => {
res.json({
users: users.map(
(user) => user.serialize())
});
})
.catch(err => {
console.error(err);
res.status(500).json({ message: 'Internal server error' });
});
});
router.get('/:username', (req, res) => {
let username = req.params.username.toLowerCase();
Users
.findOne({username: username})
.then(user => res.json(user.serialize()))
.catch(err => {
console.error(err);
res.status(500).json({ error: 'something went wrong' });
});
});
router.post('/', (req, res) => {
console.log('creating a new user');
const requiredFields = ['username', 'email', 'password'];
requiredFields.forEach(field => {
if (!(field in req.body)) {
console.error(`Missing ${field} in request body`);
return res.status(422).json({
code: 422,
reason: 'Validation Error',
message: 'Missing Field',
location: field
});
}
if ((field in req.body) && typeof req.body[field] !== 'string') {
console.error(`${field} needs to be a string`);
return res.status(422).json({
code: 422,
reason: 'Validation Error',
message: 'Incorrect field type: expected string',
location: field
});
}
});
const trimmedFields = ['username', 'password'];
const nonTrimmedField = trimmedFields.find(
field => req.body[field].trim() !== req.body[field]);
if (nonTrimmedField) {
return res.status(422).json({
code: 422,
reason: 'Validation Error',
message: 'Username and password cannot start or end with whitespace',
location: nonTrimmedField
});
}
const sizedFields = {
username: {
min: 1
},
password: {
min: 8,
max: 72
}
};
const tooSmallField = Object.keys(sizedFields).find(
field =>
'min' in sizedFields[field] &&
req.body[field].trim().length < sizedFields[field].min
);
const tooLargeField = Object.keys(sizedFields).find(
field =>
'max' in sizedFields[field] &&
req.body[field].trim().length > sizedFields[field].max
);
if (tooSmallField || tooLargeField) {
return res.status(422).json({
code: 422,
reason: 'Validation Error',
message: tooSmallField
? `Password must be at least ${sizedFields[tooSmallField]
.min} characters long`
: `Password can only be ${sizedFields[tooLargeField]
.max} characters long`,
location: tooSmallField || tooLargeField
});
}
let { username, password, email = '' } = req.body;
// trim only email since username/password have already been checked for whitespace
email = email.trim();
username = username.toLowerCase();
return Users
.findOne({ username: username })
.then(user => {
if (user) {
const message = 'This username is already taken.';
console.error(message);
return Promise.reject({
code: 422,
reason: 'Validation Error',
message: 'Username already taken',
location: 'username'
});
}
return Users.hashPassword(password);
})
.then(hash => {
username = username.toLowerCase();
return Users
.create({
username,
email,
password: hash
});
})
.then(user => res.status(201).json(user.serialize()))
.catch(err => {
if (err.reason === 'Validation Error') {
return res.status(err.code).json(err);
}
res.status(500).json({code: 500, message: 'Internal Server Error'});
});
});
router.put('/:id', (req, res) => {
if (!(req.body.id)) {
res.status(400).json({
error: 'Please provide the user id in the request body'
});
}
if (!(req.params.id && req.params.id === req.body.id)) {
res.status(400).json({
error: 'Request path id and request body id values must match'
});
}
const updated = {};
const updateableFields = ['username', 'email', 'password'];
updateableFields.forEach(field => {
if (field in req.body) {
updated[field] = req.body[field];
}
});
Users
.findByIdAndUpdate(req.params.id, { $set: updated }, { new: true })
.then(updatedUser => res.status(200).json(updatedUser.serialize()))
.catch(err => res.status(500).json({ message: err }));
});
router.delete('/:id', (req, res) => {
console.log('deleting user');
Users
.findByIdAndRemove(req.params.id)
.then(() => {
console.log(`Deleted user with id ${req.params.id}`);
res.status(204).end();
});
});
module.exports = router;