This repository has been archived by the owner on May 29, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
252 lines (226 loc) · 7.13 KB
/
app.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
/**
* Controller for the TinyApp
*
* TinyApp is a TinyURL clone made as part of the Lighthouse Labs web dev curriculum.
* Given a long url, it will give back a short url that redirects to the long url.
*/
"use strict";
/** Dependencies */
const express = require("express");
const bodyParser = require("body-parser");
const cookieSession = require('cookie-session');
const validator = require('validator');
const bcrypt = require('bcrypt');
const methodOverride = require('method-override');
const db = require("./data-model");
/** Init App */
const BCRYPT_SALT_ROUNDS = 10;
const app = express();
app.use(express.static(__dirname + '/static'));
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(methodOverride('_method'));
app.use(cookieSession({
name: 'session',
keys: process.env.session_keys || ['development'],
maxAge: 24 * 60 * 60 * 1000
}));
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => console.log(`TinyApp listening on port ${PORT}!`));
/** Helper Functions */
const getUrlsForUser = function getAllUrlsRecordsForAGivenUserId(userId) {
const urlRecords = db.urls.records;
for (let key of Object.keys(urlRecords)) {
if (urlRecords[key].userId !== userId) {
delete urlRecords[key];
}
}
return urlRecords;
};
const cleanEmail = function getTrimmedLowercaseString(str) {
return str.trim().toLowerCase();
};
const getUserForEmail = function findTheUserObjectForAGivenEmail(email) {
if (!email) { return undefined; }
const cleanedEmail = cleanEmail(email);
const userRecords = db.users.records;
const userIds = Object.keys(userRecords);
for (let id of userIds) {
if (userRecords[id].email === cleanedEmail) {
return [id, userRecords[id]];
}
}
return undefined;
};
const loginCheckMixin = function checkIfTheUserSessionIsValidThenRedirectIfNot(req, res, goTo = true) {
const user = db.users.get(req.session.userId);
if (user !== undefined) {
return true;
} else {
if (goTo) { res.redirect('/login'); }
return false;
}
};
const urlAuthCheckMixin = function checkIfTheUrlBelongsToTheUserThenRedirectIfNot(req, res, shortUrl) {
if (!loginCheckMixin(req, res)) {
return false;
}
const urlRecord = db.urls.get(shortUrl);
if (!urlRecord) {
res.status(404).send('URL not found');
return false;
}
if (urlRecord.userId !== req.session.userId) {
res.status(403).send('You cannot manage urls that aren\'t yours');
return false;
}
return true;
};
/** Routes */
/** Base Route */
app.get("/", (req, res) => {
if (loginCheckMixin(req, res)) {
res.redirect('urls');
}
});
/** Login Get Route */
app.get("/login", (req, res) => {
if (loginCheckMixin(req, res, false)) {
res.redirect('urls');
} else {
res.render('login');
}
});
/** Login Post Route */
app.post("/login", (req, res) => {
const user = getUserForEmail(req.body.email);
if (!user || !bcrypt.compareSync(req.body.password, user[1].password)) {
res.status(403).send('Invalid email and/or password!');
return;
}
req.session.userId = user[0];
res.redirect('urls');
});
/** Logout Route */
app.post("/logout", (req, res) => {
req.session.userId = null;
res.redirect('back');
});
/** Register Form Get */
app.get("/register", (req, res) => {
if (!loginCheckMixin(req, res, false)) {
const templateVars = {
user: db.users.get(req.session.userId)
};
res.render('register', templateVars);
} else {
res.redirect('urls');
}
});
/** Register Form Post */
app.post("/register", (req, res) => {
let error = undefined;
if (!validator.isEmail(req.body.email)) {
error = 'Please provide a valid email address';
} else if (!req.body.password || req.body.password.length < 6) {
error = 'Please provide a password that is 6 characters or longer';
} else {
const userRecords = db.users.records;
const userIds = Object.keys(userRecords);
const userEmails = userIds.map(id => userRecords[id].email);
const newEmail = cleanEmail(req.body.email);
if (userEmails.includes(newEmail)) {
error = 'That email is already in use';
}
}
if (error) {
res.status(400).send(error);
return;
}
const key = db.users.create({
email: cleanEmail(req.body.email),
password: bcrypt.hashSync(req.body.password, BCRYPT_SALT_ROUNDS)
});
req.session.userId = key;
res.redirect('/urls');
});
/** For listing existing url records for the user */
app.get("/urls", (req, res) => {
const templateVars = {
urls: getUrlsForUser(req.session.userId),
user: db.users.get(req.session.userId)
};
res.render("urls_list", templateVars);
});
/** POST method to add a new short url record */
app.post("/urls", (req, res) => {
if (loginCheckMixin(req, res)) {
const newKey = db.urls.create({
longUrl: req.body.longUrl,
userId: req.session.userId,
dateCreated: new Date(Date.now()),
visitors: []
});
res.redirect('/urls/' + newKey);
}
});
/** API endpoint for getting a json object of all user-associated url records */
app.get("/urls.json", (req, res) => {
if (loginCheckMixin(req, res)) {
const userUrls = getUrlsForUser(req.session.userId);
res.status(200).json(userUrls);
}
});
/** Displays a form for creating a new url pair */
app.get("/urls/new", (req, res) => {
if (loginCheckMixin(req, res)) {
const templateVars = {
user: db.users.get(req.session.userId)
};
res.render("urls_new", templateVars);
}
});
/** For viewing an individual url record */
app.get("/urls/:shortUrl", (req, res) => {
if (urlAuthCheckMixin(req, res, req.params.shortUrl)) {
const templateVars = {
key: req.params.shortUrl,
url: db.urls.get(req.params.shortUrl),
user: db.users.get(req.session.userId)
};
res.render("urls_show", templateVars);
}
});
/** For updating an individual url record associated to a given user */
app.patch("/urls/:shortUrl", (req, res) => {
if (urlAuthCheckMixin(req, res, req.params.shortUrl)) {
db.urls.update(req.params.shortUrl, { longUrl: req.body.longUrl });
res.redirect("/urls");
}
});
/** Deletes a given url pair specified by the short url */
app.delete("/urls/:shortUrl", (req, res) => {
if (urlAuthCheckMixin(req, res, req.params.shortUrl)) {
db.urls.delete(req.params.shortUrl);
res.redirect("/urls");
}
});
/** Redirects directly from a short url to its matching long url */
app.get("/u/:shortUrl", (req, res) => {
const urlRecord = db.urls.get(req.params.shortUrl);
if (urlRecord) {
if (req.session.id) {
req.session.visitorId = req.session.id;
} else if (!req.session.visitorId) {
const ip = bcrypt.hash(req.headers['x-forwarded-for'] || req.connection.remoteAddress);
const visitTime = Date.now();
req.session.visitorId = (bcrypt.hashSync(visitTime.toString(), BCRYPT_SALT_ROUNDS)).slice(30, 45);
}
urlRecord.visitors.push({ id: req.session.visitorId, timestamp: Date.now() });
db.urls.update(req.params.shortUrl, urlRecord);
res.redirect((urlRecord.longUrl.startsWith('http') ? '' : '//') + urlRecord.longUrl);
} else {
res.status(404).send('URL not found');
}
});
app.get('*', (req, res) => res.status(404).send('404: Page Not Found'));