-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexpress_server.js
268 lines (234 loc) · 7.12 KB
/
express_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
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
const express = require("express");
const app = express();
const PORT = process.env.TINYAPP_PORT || 8080;
const bodyParser = require("body-parser");
const cookieSession = require("cookie-session");
const bcrypt = require('bcrypt');
const methodOverride = require('method-override');
const {
getIdFromEmail,
generateRandomString,
urlsMadeByUser,
isLoggedIn,
getVisitSummary,
getUniqueVisitors,
displayError,
fixUrl,
getMostVisitedUrls
} = require('./helpers');
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({ extended: true }));
// req.session.user_id will be set upon login/registration
// req.session.visitor_id is set for everyone once they visit a shortURL, for analytics
app.use(cookieSession({
name: 'session',
keys: ['secret', 'moresecret', 'evenmore'],
maxAge: 24 * 60 * 60 * 1000 // 24 hours
}));
app.use(methodOverride('_method'));
const urlDatabase = {
"b2xVn2": {
longURL: "http://answers.yahoo.com",
userID: "userRandomID",
visits: []
},
"9sm5xK": {
longURL: "http://www.askjeeves.com",
userID: "user2RandomID",
visits: []
},
"b2xVn3": {
longURL: "http://www.neopets.com",
userID: "userRandomID",
visits: []
},
"b2xVn4": {
longURL: "http://www.altavista.com",
userID: "userRandomID",
visits: []
},
"b2xVn5": {
longURL: "http://www.geocities.com",
userID: "userRandomID",
visits: []
},
"b2xVn6": {
longURL: "http://www.lycos.com",
userID: "userRandomID",
visits: []
},
"b2xVn7": {
longURL: "http://www.aol.com",
userID: "userRandomID",
visits: []
}
};
const users = {
"userRandomID": {
id: "userRandomID",
email: "a@a.com",
hashedPassword: bcrypt.hashSync("purple", 10)
},
"user2RandomID": {
id: "user2RandomID",
email: "b@b.com",
hashedPassword: bcrypt.hashSync("dishwasher", 10)
}
};
app.get("/", (req, res) => {
if (!isLoggedIn(req.session, users)) {
return res.redirect("hot");
}
return res.redirect("urls");
});
app.get("/urls.json", (req, res) => {
return res.json(urlDatabase);
});
// Displays analytics for user's own shortURL creations
app.get("/urls", (req, res) => {
if (!isLoggedIn(req.session, users)) {
return displayError(res, 401, "You must be logged in for that!", null);
}
const user = users[req.session.user_id];
const urls = urlsMadeByUser(user.id, urlDatabase);
// Calculate unique visitors for each url
for (const url in urls) {
{
urls[url].uniqueVisitors = getUniqueVisitors(urls[url].visits);
}
}
let templateVars = { urls, user };
return res.render("urls_index", templateVars);
});
// Create a new shortURL
app.get("/urls/new", (req, res) => {
if (!isLoggedIn(req.session, users)) {
return res.redirect("../login");
} else {
return res.render("urls_new", { user: users[(req.session.user_id)] });
}
});
// Details/edit page for existing shortURL
app.get("/urls/:shortURL", (req, res) => {
const { shortURL } = req.params;
const url = urlDatabase[shortURL];
// Check if url exists
if (!url) {
return displayError(res, 404, "URL does not exist!", users[(req.session.user_id)]);
}
// Check if user is owner of url
if (url.userID !== req.session.user_id) {
return displayError(res, 401, "You cannot do that!", users[(req.session.user_id)]);
}
let templateVars = { shortURL, url, user: users[(req.session.user_id)] };
return res.render("urls_show", templateVars);
});
// Adding a new URL
app.post("/urls", (req, res) => {
const shortURL = generateRandomString();
// Making sure no collisions in shortURL generation
while (urlDatabase[shortURL]) {
shortURL = generateRandomString();
}
urlDatabase[shortURL] = {
longURL: fixUrl(req.body.longURL),
userID: req.session.user_id,
visits: []
};
return res.redirect(`urls/${shortURL}`);
});
// Redirects a shortURL to its longURL
app.get("/u/:shortURL", (req, res) => {
const { shortURL } = req.params;
if (!urlDatabase[shortURL]) {
return displayError(res, 404, "ShortURL not found!", users[req.session.user_id]);
}
// Give a tracking cookie to determine unique visitors
if (!req.session.visitor_id) {
req.session.visitor_id = generateRandomString();
}
// Add this visit to shortURL's visits array with visitor_id and timestamp
const visit = {
visitor: req.session.visitor_id,
time: new Date(Date.now()),
};
urlDatabase[shortURL].visits.unshift(visit);
const { longURL } = urlDatabase[shortURL];
return res.redirect(longURL);
});
app.put("/urls/:shortURL", (req, res) => {
const { shortURL } = req.params;
const { newLongURL } = req.body;
urlDatabase[shortURL].longURL = fixUrl(newLongURL);
return res.redirect("..");
});
app.delete("/urls/:shortURL", (req, res) => {
const shortURL = req.params.shortURL;
const userID = req.session.user_id;
if (urlDatabase[shortURL] && urlDatabase[shortURL].userID === userID) {
delete urlDatabase[shortURL];
return res.redirect("..");
} else {
return displayError(res, 401, "Operation failed", users[req.session.user_id]);
}
});
app.post("/logout", (req, res) => {
req.session = null;
return res.redirect("hot");
});
app.get("/register", (req, res) => {
// Redirect to home if a logged-in user tries to register
if (isLoggedIn(req.session, users)) {
return res.redirect('/urls');
}
return res.render("register", { user: users[req.session.user_id] });
});
app.post("/register", (req, res) => {
const { email, password } = req.body;
if (!email || !password) {
return displayError(res, 400, "You did not fill out the form correctly!", null);
} else if (getIdFromEmail(email, users)) {
return displayError(res, 400, "Email already in use!", null);
}
// Collision handling during userID generation
const id = generateRandomString();
while (users[id]) {
id = generateRandomString();
}
const hashedPassword = bcrypt.hashSync(password, 10);
const newUser = { id, email, hashedPassword };
users[id] = newUser;
req.session.user_id = id;
return res.redirect("urls");
});
app.get("/login", (req, res) => {
// Redirect to home if a logged-in user tries to login
if (isLoggedIn(req.session, users)) {
return res.redirect('/urls');
}
return res.render("login", { user: users[req.session.user_id] });
});
app.post("/login", (req, res) => {
const { email, password } = req.body;
const id = getIdFromEmail(email, users);
if (!id) {
return displayError(res, 403, "Login failed", null);
} else if (bcrypt.compareSync(password, users[id].hashedPassword) === false) {
return displayError(res, 403, "Login failed", null);
} else {
req.session.user_id = id;
return res.redirect("urls");
}
});
// Displays list of most visited shortURLs
app.get("/hot", (req, res) => {
const hotUrls = getMostVisitedUrls(20, urlDatabase);
// Generate unique visitor stats for these hotUrl objs to pass in
for (const hotUrl of hotUrls) {
urlDatabase[hotUrl].uniqueVisitors = getUniqueVisitors(urlDatabase[hotUrl].visits);
}
return res.render("hot", { hotUrls, urls: urlDatabase, user: users[req.session.user_id] });
});
app.listen(PORT, () => {
console.log(`Example app listening on port ${PORT}!`);
});