/
express_server.js
232 lines (209 loc) · 6.68 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
const express = require("express");
const {generateRandomString, userAlreadyExists, userAuthenticator, userIDReturner, urlsForUser} = require('./helpers');
const bodyParser = require("body-parser");
const cookieSession = require('cookie-session');
const methodOverride = require('method-override');
const bcrypt = require('bcrypt');
const saltRounds = 10;
const app = express();
const PORT = 8080;
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieSession({
name: 'session',
keys: ['key1', 'key2']
}));
app.use(methodOverride('_method'));
app.set("view engine", "ejs");
//Global url database for current users
const urlDatabase = {
"b2xVn2": {longURL: "http://www.lighthouselabs.ca", userID:"userRandomID"},
"9sm5xK": {longURL:"http://www.google.ca", userID:"user2RandomID"}
};
//Global object for users database
const users = {
"userRandomID": {
id: "userRandomID",
email: "user@example.com",
password: bcrypt.hashSync("puppies", saltRounds)
},
"user2RandomID": {
id: "user2RandomID",
email: "user2@example.com",
password: bcrypt.hashSync("kitties", saltRounds)
}
};
//Routing GET requests below
app.get("/", (req, res) => {
let currentUser = users[req.session["user_id"]];
if (currentUser) {
res.redirect("/urls");
} else {
res.redirect("/login");
}
});
app.get("/urls", (req, res) => {
let currentUser = users[req.session["user_id"]];
if (currentUser) {
let userSpecificURLs = urlsForUser(urlDatabase, currentUser["id"]);
const templateVars = {
user: currentUser,
urls: userSpecificURLs
};
res.render("urls_index", templateVars);
} else {
const templateVars = {
user: false //needs to be false to to show error on page to login/register
};
res.render("urls_index", templateVars);
}
});
app.get("/urls/new", (req, res) => {
let currentUser = users[req.session["user_id"]];
const templateVars = {
user: currentUser
};
//Only allow registered and logged in users to create tiny URLS
if (!currentUser) {
res.redirect("/login");
} else {
res.render("urls_new", templateVars);
}
});
app.get("/register", (req, res) => {
let currentUser = users[req.session["user_id"]];
const templateVars = {
user: currentUser,
error: null //to stop error from showing on page because POST request has error response
};
res.render("register", templateVars);
});
app.get("/login", (req, res) => {
let currentUser = users[req.session["user_id"]];
const templateVars = {
user: currentUser,
error: null //to stop error from showing up on page because POST request has error response
};
res.render("login", templateVars);
});
app.get("/urls/:shortURL", (req, res) => {
let longURL = urlDatabase[req.params.shortURL].longURL;
let currentUser = users[req.session["user_id"]];
let display;
//to determine if url belongs to current user
if (currentUser) {
if (urlsForUser(urlDatabase, currentUser.id)[req.params.shortURL]) {
display = true; //will show urls on page
} else {
display = false; //will trigger error on page
}
//check if long URL is true/false to determine if can show page or not
if (longURL) {
const templateVars = {
user: currentUser,
shortURL: req.params.shortURL,
longURL: longURL,
display
};
res.render("urls_shows", templateVars);
} else {
res.send("URL does not exist.");
}
} else {
res.status(403).redirect("/login");
}
});
app.get("/u/:shortURL", (req, res) => {
const longURL = urlDatabase[req.params.shortURL].longURL;
res.redirect(longURL);
});
//POST requests below
app.post("/urls", (req, res) => {
let currentUser = users[req.session["user_id"]];
let id = generateRandomString();
urlDatabase[id] = {longURL: req.body.longURL, userID: currentUser.id};
res.redirect(`/urls/${id}`);
});
app.delete("/urls/:shortURL", (req, res) => {
let currentUser = users[req.session["user_id"]];
// check if current user is logged in
if (currentUser) {
//check if url belongs to urls for user before allowing them to delete
if (urlsForUser(urlDatabase, currentUser.id)[req.params.shortURL]) {
delete urlDatabase[req.params.shortURL];
res.redirect("/urls");
}
} else {
//send status code Forbidden if not on their list
res.status(403).redirect("/login");
}
});
//To Update a long url
app.put("/urls/:shortURL", (req, res) => {
let currentUser = users[req.session["user_id"]];
//check if URL belongs to user's list then they can edit
if (urlsForUser(urlDatabase, currentUser.id)[req.params.shortURL]) {
let newURL = req.body.newURL;
//updating new URL to database
urlDatabase[req.params.shortURL].longURL = newURL;
res.redirect("/urls");
}
});
app.post("/login", (req, res) => {
let userEmail = req.body.email;
let userPassword = req.body.password;
let userID = userIDReturner(users, userEmail);
//check if it exists and using right credentials for user
if (userAuthenticator(users, userEmail, userPassword)) {
//if both pass, set user_id cookie matching users random ID and redirect to /urls
req.session['user_id'] = userID;
res.redirect("/urls");
} else {
const templateVars = {
error: "Error in credentials",
user: null
};
res.render("login", templateVars);
// res.status(403).redirect("/login"); -- alternative way to send error
}
});
app.post("/logout", (req, res) => {
// req.session['user_id'] = null; -- also another way to delete cookies?
delete req.session['user_id'];
res.redirect("/urls");
});
app.post("/register", (req, res) => {
let newId = generateRandomString();
let newEmail = req.body.email;
let newPassword = req.body.password;
//if email or password send error msg
if (!newEmail || !newPassword) {
const templateVars = {
user: null,
error: "Email or Password input error!"
};
res.render("register", templateVars);
// res.status(400).redirect("/login"); --alternative send status code and redirect to login
} else if (userAlreadyExists(users, newEmail)) {
const templateVars = {
user: null,
error: "Email already exists as user!"
};
res.render("register", templateVars);
// res.status(400).redirect("/login"); --alternative send status code and redirect to login
} else {
//if we have made it this far, we can create the new user
const newUser = {
id: newId,
email: newEmail,
password: bcrypt.hashSync(newPassword, saltRounds),
};
//Adding new user to database
users[newId] = newUser;
//add encypted cookies
req.session['user_id'] = newId;
res.redirect("/urls");
}
});
app.listen(PORT, () => {
console.log(`Example app listening on port ${PORT}!`);
});