-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexpress_server.js
More file actions
291 lines (216 loc) · 6.66 KB
/
Copy pathexpress_server.js
File metadata and controls
291 lines (216 loc) · 6.66 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
// run server: npm start
const express = require("express");
const app = express();
const PORT = 8080;
// middleware
const bodyParser = require("body-parser");
const morgan = require('morgan');
const cookieSession = require('cookie-session');
const bcrypt = require('bcrypt');
app.use(bodyParser.urlencoded({ extended: true })); //formats the form POST requests
app.set("view engine", "ejs");
app.use(morgan('dev'));
app.use(cookieSession({
name: 'session',
keys: ['hamilton', 'biminibonboulash']
}));
// helper functions
const { getUserByEmail, generateRandomString, getUserUrls } = require('./helpers/userHelpers');
// 🌍 GLOBAL SCOPE VARIABLES
const urlDatabase = { // URL DATABASE
b6UTxQ: { longURL: "https://www.sorihan.com", userID: "sorihan1988" },
i3BoGr: { longURL: "https://www.google.ca", userID: "sorihan1988" },
'a2f747': { longURL: "https://www.enze.com", userID: "user2RandomID" },
'3f0037': { longURL: "https://www.yahoo.ca", userID: "user2RandomID" }
};
const users = { // USER DATABASE
"sorihan1988": {
userID: "sorihan1988",
email: "sori@sorihan.com",
password: '$2b$10$xecpVIvaXwHZN5l.vFIuruv3QffmyI/oi3NtwjrlgfRTq6.X265t.'
},
"user2RandomID": {
userID: "user2RandomID",
email: "user2@example.com",
password: '$2b$10$xecpVIvaXwHZN5l.vFIuruv3QffmyI/oi3NtwjrlgfRTq6.X265t.'
}
};
// 📗 GET
// HOME
app.get('/', (req, res) => {
res.redirect('login');
});
// REGISTER page renders if userId does not exist
app.get('/register', (req, res) => {
const userID = req.session.user_id;
if (!userID) {
const templateVars = {
user: null
};
res.render('register', templateVars);
return;
}
res.redirect('/urls')
});
// LOGIN if userID/ cookie does not exist render login page. Redirec to /urls if logged in.
app.get('/login', (req, res) => {
const userID = req.session.user_id;
if (!userID) {
const templateVars = {
user: null
};
res.render('login', templateVars);
return;
}
res.redirect('/urls')
});
// USER /URLS - only logged in users can view this page.
app.get('/urls', (req, res) => {
const userID = req.session.user_id;
if (!userID) {
res.status(403).send('please LOG-IN or REGISTER to use TinyApp!');
return;
}
const user = users[userID];
if (!user) {
res.status(403).send('please LOG-IN or REGISTER to use TinyApp!');
return;
}
let urls = getUserUrls(urlDatabase, userID);
const templateVars = { urls, user, };
res.render('urls_index', templateVars);
});
// /URLS/NEW - logged in users can create new URLs
app.get("/urls/new", (req, res) => {
const userID = req.session.user_id;
if (!userID) {
res.status(403).send('please LOG-IN or REGISTER to use TinyApp!');
return;
}
const user = users[userID];
if (!user) {
res.redirect(`/login`);
return;
}
const templateVars = {
user
};
res.render("urls_new", templateVars);
});
// Logged in users can access their shortURL to edit or visit the page
app.get('/urls/:shortURL', (req, res) => {
const userID = req.session.user_id;
if (!userID) {
res.status(403).send('please LOG-IN or REGISTER to use TinyApp!');
return;
}
const user = users[userID];
if (!user) {
res.send('please LOG-IN or REGISTER to use TinyApp!');
return;
}
const shortURL = req.params.shortURL;
const urlRecord = urlDatabase[shortURL];
if (!urlRecord) {
res.send('this short URL does not exist! 🤷🏽♂️');
return;
}
if (urlRecord.userID !== userID) {
res.send('this URL does not belong to you 🙅🏻♂️');
return;
}
const longURL = urlRecord.longURL;
const templateVars = { shortURL, longURL, user };
res.render('urls_show', templateVars);
});
// REDIRECT TO ORIGINAL LONG-URL PAGE
app.get("/u/:shortURL", (req, res) => {
const urlRecord = urlDatabase[req.params.shortURL];
if (!urlRecord) {
res.send('this short URL does not exist 🤡');
return;
}
res.redirect(urlRecord.longURL);
});
// ✏️ POST
// LOGIN / LOGOUT 🔑 - Checks credential for existing user to log in. Redirects to user's URLs
app.post("/login", (req, res) => {
const email = req.body.email;
const password = req.body.password;
if (email === '' || password === '') {
res.status(403).send('wrong credentials');
return;
}
const user = getUserByEmail(users, email);
if (!user) {
res.status(403).send('invalid credentials');
return;
}
if (!bcrypt.compareSync(password, user.password)) {
res.status(403).send('invalid credentials');
return;
}
req.session.user_id = user.userID;
res.redirect(`/urls`);
});
app.post("/logout", (req, res) => {
req.session = null;
res.redirect(`/login`);
});
// /REGISTER - Registration is successful if email doesn't exist in database
app.post("/register", (req, res) => {
const email = req.body.email;
const password = bcrypt.hashSync(req.body.password, 10);
if (email === '' || password === '') {
res.status(400).send("please check your email or password");
return;
}
if (!getUserByEmail(users, email)) {
const userID = generateRandomString();
req.session.user_id = userID;
users[userID] = { userID, email, password };
res.redirect(`/urls`);
}
res.send('this email already exists!');
return;
});
// SUBMIT NEW LONG-URL - stores new URL in database of user and adds URL prefix if non-existent
app.post("/urls", (req, res) => {
let { longURL } = req.body;
if (!longURL.startsWith('http')) {
longURL = `http://${longURL}`;
}
const userID = req.session.user_id;
const genShortURL = generateRandomString();
urlDatabase[genShortURL] = { longURL, userID, };
res.redirect(`/urls/${genShortURL}`);
});
// DELETE EXISTING URL - owner of existing URL can delete their stored URL
app.post("/urls/:shortURL/delete", (req, res) => {
const userID = req.session.user_id;
const { shortURL } = req.params;
if (userID !== urlDatabase[shortURL].userID) {
res.sendStatus(404);
return;
}
delete urlDatabase[shortURL];
res.redirect(`/urls`);
});
// EDIT EXISTING URL - owner if URL can edit URL. If no prefix for URL is given adds correct prefix
app.post("/urls/:shortURL/edit", (req, res) => {
const userID = req.session.user_id;
let { longURL } = req.body;
const { shortURL } = req.params;
if (userID !== urlDatabase[shortURL].userID) {
res.status(404).send('You do not have permission to edit this link');
return;
}
if (!longURL.startsWith('http')) {
longURL = `http://${longURL}`;
}
urlDatabase[shortURL] = { longURL, userID };
res.redirect(`/urls`);
});
app.listen(PORT, () => {
console.log(`(ノ◕ヮ◕)ノ*:・゚✧✧✧ TinyApp is running on PORT: ${PORT} ☆☆☆ミ(o*・ω・)ノ `);
});