-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
360 lines (323 loc) · 10.9 KB
/
index.js
File metadata and controls
360 lines (323 loc) · 10.9 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
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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
/**
* Imports required modules for the jMDB application.
* @module index
*/
const express = require ('express'),
fs = require('fs'), // import built in node modules fs and path
path = require('path'),
bodyParser = require('body-parser'),
uuid = require('uuid'),
morgan = require('morgan'),
mongoose = require('mongoose'),
Models = require('./models.js'),
dotenv = require('dotenv').config();
const { check, validationResult } = require('express-validator');
/**
* Access imported models for Movies and Users.
*/
const Movies = Models.Movie;
const Users = Models.User;
/**
* Creates the Express application instance.
*/
const app = express();
/**
* Middleware to parse JSON data in request bodies.
*/
app.use(bodyParser.json());
/**
* Establishes connection to MongoDB using the CONNECTION_URI environment variable.
* Logs connection errors and success messages.
*/
mongoose.connect(process.env.CONNECTION_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.catch((err) => console.error('MongoDb connection failed: ' + err));
mongoose.connection.on('error', (err) => {
console.error('MongoDb connection error: ' + err);
});
/**
* Middleware to enable CORS (Cross-Origin Resource Sharing).
* Needs to be placed before authorization and logging middleware.
*/
const cors = require('cors');
app.use(cors());
/**
* Imports and initializes authentication middleware from `auth.js`.
*/
let auth = require('./auth')(app);
const passport = require('passport');
require('./passport');
app.use(passport.initialize());
/**
* Creates a write stream (in append mode) for logging requests to `log.txt`.
*/
const accessLogStream = fs.createWriteStream(path.join(__dirname, 'log.txt'), {flags: 'a'})
/**
* Configures and uses the `morgan` middleware for logging requests.
*/
app.use(morgan('combined', {stream: accessLogStream}));
app.use('/documentation.html', express.static('public/documentation.html'));
/**
* GET request handler for the application landing page.
* Responds with a welcome message.
*/
app.get('/', (req, res) => {
res.send('Welcome to jMDB');
});
/**
* Logs the connection URI for debugging purposes.
*/
console.log("Connection URI:", process.env.CONNECTION_URI);
/**
* GET request handler for retrieving all movies.
* Requires JWT authentication before proceeding.
* @returns an array of movie objects on success, or @throws 500 error with details on failure.
*/
app.get('/movies', passport.authenticate('jwt', { session: false }), (req, res) => {
Movies.find()
.then((movies) => {
console.log('Movies fetched:', movies);
res.status(200).json(movies);
})
.catch((err) => {
console.error(err);
res.status(500).send('Error: ' + err);
});
});
/**
* GET request handler for retrieving a specific movie by name.
* Requires JWT authentication before proceeding.
* @returns with a movie object on success, or @throws a 500 error with details on failure.
*/
app.get('/movies/:Name', passport.authenticate('jwt', {session: false}), (req, res) => {
Movies.findOne({ Name: req.params.Name })
.then(movie => {
res.json(movie);
})
.catch(err => {
console.error(err);
res.status(500).send(err);
});
});
/**
* GET request handler for retrieving a director by name.
* Requires JWT authentication before proceeding.
* @returns with a director object on success, or @throws a 500 error with details on failure.
*/
app.get('/director/:Name', passport.authenticate('jwt', {session: false}), (req, res) => {
Directors.findOne({ Name : req.params.Name})
.then(director => {
res.json(director);
})
.catch(err => {
console.error(err);
res.status(500).send('Something broke!' + err);
});
});
/**
* GET request handler for retrieving a tag by name.
* Requires JWT authentication before proceeding.
* @returns with a tag object on success, or @throws a 500 error with details on failure.
*/
app.get('/tags/:Name', passport.authenticate('jwt', {session: false}), (req, res) => {
Tags.findOne({ Name : req.params.Name})
.then(tag => {
res.json(tag);
})
.catch(err => {
console.error(err);
res.status(500).send('Something broke!' + err);
});
});
/**
* GET request handler for retrieving all users.
* Requires JWT authentication before proceeding.
* @returns with an array of user objects on success, or @throws a 500 error with details on failure.
*/
app.get('/users', passport.authenticate('jwt', {session: false}), (req, res) => {
Users.find()
.then((users) => {
res.status(201).json(users);
})
.catch((err) => {
console.error(err);
res.status(500).send('Error: ' + err);
});
});
/**
* GET request handler for retrieving a user by username.
* Requires JWT authentication before proceeding.
* @returns with a user object on success, or @throws a 500 error with details on failure.
*/
app.get('/users/:Username', passport.authenticate('jwt', {session: false}), (req, res) => {
Users.findOne({ Username: req.params.Username })
.then((user) => {
res.json(user);
})
.catch((err) => {
console.error(err);
res.status(500).send('Error: ' + err);
});
});
/**
* POST request handler for creating a new user.
* Expects JSON data in the request body with specific validation requirements.
* @throws a 422 error if validation fails, or @returns 201 status with the created user object on success.
* If username already exists, @throws a 400 error.
*/
app.post('/users',
//Validation logic for request goes here
[
check('Username', 'Username is required').isLength({min: 5}),
check('Username', 'Username contains non alphanumeric characters - not allowed.').isAlphanumeric(),
check('Password', 'Password is required').not().isEmpty(),
check('Email', 'Email does not appear to be valid').isEmail()
],
(req, res) => {
//check validation object for errors here
let errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
}
// Hash password before creating user
let hashedPassword = Users.hashPassword(req.body.Password);
Users.findOne({ Username: req.body.Username }) //search to see if username already exists
.then((user) => {
if (user) {
return res.status(400).send(req.body.Username + 'already exists');
} else {
Users
.create({
Username: req.body.Username,
Password: hashedPassword,
Email: req.body.Email,
Birthdate: req.body.Birthdate
})
.then((user) =>{res.status(201).json(user)})
.catch((error) => {
console.error(error);
res.status(500).send('Error:' + error);
})
}
})
.catch((error) => {
console.error(error);
res.status(500).send('Error: ' + error);
});
});
/**
* PUT request handler for updating a user's information.
* Requires JWT authentication before proceeding.
* Expects JSON data in the request body with specific validation requirements.
* @throws a 422 error if validation fails, or @returns 200 status with the updated user object on success.
*/
app.put('/users/:Username', passport.authenticate('jwt', {session: false}),
[
check('Username', 'Username is required').isLength({min: 5}),
check('Username', 'Username contains non alphanumeric characters - not allowed.').isAlphanumeric(),
check('Password', 'Password is required').not().isEmpty(),
check('Email', 'Email does not appear to be valid').isEmail()
],
(req, res) => {
let errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
}
let hashedPassword = Users.hashPassword(req.body.Password);
Users.findOneAndUpdate({ Username: req.params.Username }, { $set:
{
Username: req.body.Username,
Password: hashedPassword,
Email: req.body.Email,
Birthdate: req.body.Birthdate
}
},
{ new: true }, // This line makes sure that the updated document is returned
(err, updatedUser) => {
if(err) {
console.error(err);
res.status(500).send('Error: ' + err);
} else {
res.json(updatedUser);
}
});
});
/**
* POST request handler for adding a movie to a user's list of favorites.
* Requires JWT authentication before proceeding.
* Expects the movie ID (`_id`) in the request path and username in the path and request body.
* @returns with the updated user object on success, or @throws a 500 error with details on failure.
*/
app.post('/users/:Username/movies/:_id', passport.authenticate('jwt', {session: false}), (req, res) => {
const movieId = req.params._id;
Users.findOneAndUpdate({ Username: req.params.Username }, {
$push: { FavMovies: movieId }
},
{ new: true })// makes sure that the updated document is returned
.then((updatedUser) => {
res.json(updatedUser);
})
.catch((err) => {
console.error(err);
res.status(500).send('Error: ' + err);
});
});
/**
* DELETE request handler for removing a movie from a user's list of favorites.
* Requires JWT authentication before proceeding.
* Expects the movie ID (`_id`) and username in the request path.
* @returns the updated user object on success, or @throws a 500 error with details on failure.
*/
app.delete('/users/:Username/movies/delete/:_id', passport.authenticate('jwt', {session: false}), (req, res) => {
const movieID = req.params._id;
Users.findOneAndUpdate({ Username: req.params.Username }, {
$pull: { FavMovies: movieID }
},
{ new: true }, // This line makes sure that the updated document is returned
(err, updatedUser) => {
if (err) {
console.error(err);
res.status(500).send('Error: ' + err);
} else {
res.json(updatedUser);
}
});
});
/**
* DELETE request handler for deleting a user by username.
* Requires JWT authentication before proceeding.
* Expects the username in the request path.
* @throws a 400 status and message if the user is not found, or @returns a 200 status and message if the user is deleted successfully.
*/
app.delete('/users/:Username', passport.authenticate('jwt', {session: false}), (req, res) => {
Users.findOneAndRemove({ Username: req.params.Username })
.then((user) => {
if (!user) {
res.status(400).send(req.params.Username + ' was not found');
} else {
res.status(200).send(req.params.Username + ' was deleted.');
}
})
.catch((err) => {
console.error(err);
res.status(500).send('Error: ' + err);
});
});
/**
* Generic error handling middleware for Express.
* Logs the error stack trace and sends a generic "Something broke!" message to the client.
*/
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
/**
* Starts the Express server and listens for requests on the specified port (default: 8080).
* Logs a message indicating the server is listening.
*/
const port = process.env.PORT || 8080;
app.listen(port, '0.0.0.0',() => {
console.log('Listening on Port ' + port);
});