-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.js
227 lines (194 loc) · 5.38 KB
/
server.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
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
"use strict";
const log = console.log;
const express = require("express");
// starting the express server
const app = express();
// mongoose and mongo connection
const { mongoose } = require("./db/mongoose");
// import the mongoose models
const { User } = require("./models/user");
const { Cover } = require("./models/cover");
// to validate object IDs
const { ObjectID } = require("mongodb");
// body-parser: middleware for parsing HTTP JSON body into a usable object
const bodyParser = require("body-parser");
app.use(bodyParser.json());
// express-session for managing user sessions
const session = require("express-session");
app.use(bodyParser.urlencoded({ extended: true }));
/*** User handling **************************************/
// Create a session cookie
app.use(
session({
secret: "oursecret",
resave: false,
saveUninitialized: false,
cookie: {
expires: new Date(253402300000000),
httpOnly: true
}
})
);
// A route to login and create a session
app.post("/users/login", (req, res) => {
const username = req.body.username.toLowerCase();
const password = req.body.password;
// Use the static method on the User model to find a user
// by their username and password
User.findByUsernamePassword(username, password)
.then(user => {
// Add the user's id to the session cookie.
// We can check later if this exists to ensure we are logged in.
req.session.user = user._id;
req.session.username = user.username;
res.send({ currentUser: user.username, userID: user._id });
})
.catch(error => {
res.status(400).send();
});
});
// A route to logout a user
app.get("/users/logout", (req, res) => {
// Remove the session
req.session.destroy(error => {
if (error) {
res.status(500).send(error);
} else {
res.send();
}
});
});
// A route to check if a use is logged in on the session cookie
app.get("/users/check-session", (req, res) => {
if (req.session.user) {
res.send({ currentUser: req.session.username, userID: req.session.user });
} else {
res.status(401).send();
}
});
// Set up a POST route to *create* a user
app.post("/users/register", (req, res) => {
// Create a new user
const user = new User({
username: req.body.username.toLowerCase(),
password: req.body.password
});
// Save the user
user.save().then(
user => {
res.send(user);
},
error => {
log(error);
res.status(400).send(error); // 400 for bad request
}
);
});
/*********************************************************/
/*** API Routes below ************************************/
/** Cover letter resource routes **/
// a POST request to create a user's cover letter
app.post("/covers/new", (req, res) => {
log(req.body);
const coverID = new mongoose.Types.ObjectId().toHexString();
const cover = new Cover({
_id: coverID,
title: req.body.title,
data: req.body.data,
owner: req.body.owner
});
cover.save().then(
result => {
// Append to list of covers
const userID = req.body.owner;
User.findOneAndUpdate(
{ _id: userID },
{ $push: { covers: coverID } },
{ upsert: true }
).then(
result => {
res.status(200).send(req.body.title + " created!");
},
error => {
res.status(500).send(error);
}
);
},
error => {
log(error);
res.status(500).send(error);
}
);
});
// a GET route to get covers based on user
app.get("/covers/:id", (req, res) => {
const id = req.params.id;
Cover.find({ owner: id })
.then(results => {
if (!results) {
res.status(404).send("Failed to get covers");
} else {
res.send(results);
}
})
.catch(error => {
log(error);
res.status(500).send(error);
});
});
// a PATCH route to save cover to a user
app.patch("/covers/:cid", (req, res) => {
const cid = req.params.cid;
// get the updated name and year only from the request body.
const { data } = req.body;
const body = { data };
if (!ObjectID.isValid(cid)) {
res.status(404).send();
}
// Update the cover by their id.
Cover.findByIdAndUpdate(cid, { $set: body }, { new: true })
.then(cover => {
if (!cover) {
res.status(404).send();
} else {
res.send(cover);
}
})
.catch(error => {
res.status(400).send();
});
});
// a DELETE route to delete cover to a user
app.delete("/covers/:cid", (req, res) => {
const cid = req.params.cid;
// get the updated name and year only from the request body.
const { data } = req.body;
const body = { data };
if (!ObjectID.isValid(cid)) {
res.status(404).send();
}
Cover.findByIdAndRemove(cid)
.then(cover => {
if (!cover) {
res.status(404).send();
} else {
res.send(cover);
}
})
.catch(error => {
res.status(500).send(); // server error, could not delete.
});
});
/*** Webpage routes below **********************************/
// Serve the build
app.use(express.static(__dirname + "/client/build"));
// All routes other than above will go to index.html
app.get("*", (req, res) => {
res.sendFile(__dirname + "/client/build/index.html");
});
/*************************************************/
// Express server listening...
const port = process.env.PORT || 3001;
app.listen(port, () => {
log(`Listening on port ${port}...`);
});