-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
398 lines (343 loc) · 12 KB
/
index.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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
const express = require("express");
const app = express();
const compression = require("compression");
const db = require("./utils/db");
const bc = require("./utils/bc");
const bodyParser = require("body-parser");
const cookieSession = require("cookie-session");
const csurf = require("csurf");
const moment = require("moment");
//----------------------socket.io--------------------------------
//this has to happen after const app = express() line
const server = require("http").Server(app);
const io = require("socket.io")(server, {
origins: "localhost:8080 192.168.50.*:*"
});
//-------------has to be above the routes, handling file uploads
const multer = require("multer");
const uidSafe = require("uid-safe");
const path = require("path");
const s3 = require("./s3");
const config = require("./config");
//-------- multer saves the file to uploads directory -------//
app.use(express.static("./public"));
app.use(bodyParser.json());
app.use(compression());
//----------------------- cookies ----------------------------------
const cookieSessionMiddleware = cookieSession({
secret: `I'm always hungry.`,
maxAge: 1000 * 60 * 60 * 24 * 90
});
app.use(cookieSessionMiddleware);
io.use(function(socket, next) {
cookieSessionMiddleware(socket.request, socket.request.res, next);
});
// app.use(
// cookieSession({
// secret: `I'm always hungry.`,
// maxAge: 1000 * 60 * 60 * 24 * 14 //in two weeks cookie will be deleted
// })
// );
app.use(csurf());
app.use(function(req, res, next) {
res.cookie("mytoken", req.csrfToken());
next();
});
if (process.env.NODE_ENV != "production") {
app.use(
"/bundle.js",
require("http-proxy-middleware")({
target: "http://localhost:8081/"
})
);
} else {
app.use("/bundle.js", (req, res) => res.sendFile(`${__dirname}/bundle.js`));
}
//---multer saves the file to uploads directory ----//
//filename function tells multer to use as the file name the unique id generated by the call to uidSafe with the extension of the original file name appended to it//
var diskStorage = multer.diskStorage({
destination: function(req, file, callback) {
callback(null, __dirname + "/uploads");
},
filename: function(req, file, callback) {
uidSafe(24).then(function(uid) {
callback(null, uid + path.extname(file.originalname));
});
}
});
var uploader = multer({
storage: diskStorage,
limits: {
fileSize: 2097152
}
});
//----------------------------------------------
app.post("/welcome", async (req, res) => {
const { first, last, email, password } = req.body;
try {
let hash = await bc.hashPassword(password);
let result = await db.newUser(first, last, email, hash);
req.session.userId = result.rows[0].id;
res.json({ success: true });
} catch (err) {
console.log("err in POST /welcome", err);
}
});
app.post("/login", async (req, res) => {
const { email, password } = req.body;
try {
let result = await db.getPassword(email);
// console.log("result is:", result.rows.length);
if (result.rows.length == 0) {
throw new Error("email is not registered");
}
let didMatch = await bc.checkPassword(
password,
result.rows[0].password
);
// console.log("didMatch", didMatch);
req.session.userId = result.rows[0].id;
res.json({ didMatch });
} catch (err) {
console.log("err in POST /login", err);
res.json({ didMatch: false });
}
});
//----------------------logout--------------------------------
app.get("/logout", (req, res) => {
req.session = null;
res.redirect("/welcome");
});
//--------------------------------------------------------------
app.get("/user", async (req, res) => {
try {
const result = await db.getUserInfo(req.session.userId);
res.json(result.rows[0]);
} catch (err) {
console.log("err in GET /user", err);
}
});
//--------------------------------------------------------
//single indicates that we are only expecting one file. The string passed to single is the name of the field in the request.
app.post("/upload", uploader.single("file"), s3.upload, async (req, res) => {
// console.log("req.file: ", req.file);
const url = config.s3Url + req.file.filename;
try {
const result = await db.insertImage(url, req.session.userId);
res.json(result.rows[0].image);
} catch (err) {
console.log("err in POST /upload", err);
}
});
///------------------adding bio to database------------------
app.post("/bio", async (req, res) => {
try {
const result = await db.addBio(req.session.userId, req.body.draftBio);
res.json(result.rows[0].bio);
} catch (err) {
console.log("err in POST /bio", err);
}
});
//------------------getting other user ------------------
app.get("/user/:id.json", async (req, res) => {
try {
if (req.params.id == req.session.userId) {
throw new Error("same user");
}
const result = await db.getUserInfo(req.params.id);
if (result.rows.length == 0) {
res.json({
noUser: true
});
}
res.json(result.rows[0]);
} catch (err) {
console.log("err in get /user/id", err);
res.json({
sameUser: true
});
}
});
//------------------getting last 3 users --------------------
app.get("/users.json", async (req, res) => {
try {
const result = await db.latestUsers();
// console.log(result.rows);
res.json(result.rows);
} catch (err) {
console.log("err in GET /users", err);
}
});
//------------------searching users --------------------
app.get("/search/:val.json", async (req, res) => {
try {
const result = await db.searchUser(req.params.val);
// console.log(result.rows);
res.json(result.rows);
// if (result.rows.length == 0) {
// throw new Error("no results");
// }
} catch (err) {
console.log("err in GET /users", err);
res.json({
noResults: true
});
}
});
//------------------ check friendship ------------------------
app.get("/friendship/:othProfId", async (req, res) => {
try {
const result = await db.checkFriendship(
req.session.userId,
req.params.othProfId
);
if (result.rows.length == 0) {
res.json({ buttonText: "Add friend" });
} else if (result.rows[0].accepted) {
res.json({ buttonText: "Unfriend" });
} else if (result.rows[0].sender_id == req.params.othProfId) {
res.json({ buttonText: "Accept friend request" });
} else {
res.json({ buttonText: "Cancel friend request" });
}
// res.json(result.rows[0]);
} catch (err) {
console.log("err in GET /frienship", err);
}
});
//------------------ send friend request ------------------------
app.post("/friendship/:othProfId", async (req, res) => {
try {
console.log(req.body.button);
if (req.body.button == "Add friend") {
const result = await db.sendFriendRequest(
req.session.userId,
req.params.othProfId
);
// console.log("accepted", result.rows);
res.json({ buttonText: "Cancel friend request" });
} else if (req.body.button == "Accept friend request") {
const results = await db.acceptFriendRequest(
req.params.othProfId,
req.session.userId
);
res.json({ buttonText: "Unfriend" });
} else if (
req.body.button == "Unfriend" ||
req.body.button == "Cancel friend request"
) {
const results = await db.deleteFriend(
req.params.othProfId,
req.session.userId
);
res.json({ buttonText: "Add friend" });
}
} catch (err) {
console.log("err in GET /frienship", err);
}
});
//---------------- Getting all friends------------------------
app.get("/friends.json", async (req, res) => {
try {
const friends = await db.getFriendsList(req.session.userId);
// console.log("friends", friends);
res.json(friends.rows);
} catch (err) {
console.log("err in GET /friends", err);
}
});
///-------------- Do not delete this!!! ---------------------
//this route has to be after all get routes.
app.get("*", function(req, res) {
if (!req.session.userId && req.url != "/welcome") {
res.redirect("/welcome");
} else if (req.session.userId && req.url == "/welcome") {
res.redirect("/");
} else {
res.sendFile(__dirname + "/index.html");
}
});
// app.listen(8080, function() {
// console.log("I'm listening.");
// });
server.listen(8080, function() {
console.log("I'm listening");
});
//----------------- socket.io / chat --------------------------------
let usersConnectedNow = [];
//we pass to this function an object represents a connection between me and client
io.on("connection", async socket => {
console.log(`A socket with the id ${socket.id} just connected.`);
if (!socket.request.session.userId) {
return socket.disconnect(true);
}
//here we're grabbing their userId
let userId = socket.request.session.userId;
const newUserConnected = {
userid: userId,
[userId]: socket.id
};
usersConnectedNow.push(newUserConnected);
console.log("connected users:", usersConnectedNow);
const result = await db.lastTenMessages();
result.rows.forEach(i => {
i.created_at = moment(i.created_at, moment.ISO_8601).fromNow();
});
io.emit("chatMessages", result.rows);
socket.on("new chat message", async msg => {
// console.log(`message is: ${msg} from ${userId}`);
const message = await db.addMessage(msg, userId);
const user = await db.getUserInfo(userId);
message.rows[0].created_at = moment(
message.rows[0].created_at,
moment.ISO_8601
).fromNow();
const result = { ...message.rows[0], ...user.rows[0] };
// console.log("result", result);
io.sockets.emit("newChatMessage", result);
});
//--------------------- last private messages -------------------------
//
socket.on("get last private messages", async id => {
const data = await db.lastPrivateMessages(id.receiver_id, userId);
// console.log("last private messages", data.rows);
io.emit("privateMessages", data.rows);
});
//--------------------- private messages -------------------------
socket.on("private message", async (msg, id) => {
console.log(
`private message to ${id.receiver_id} from ${userId} is: ${msg}`
);
const privateMessage = await db.addPrivateMessage(
msg,
userId,
id.receiver_id
);
const sender = await db.getUserInfo(userId);
const dataForPm = { ...privateMessage.rows[0], ...sender.rows[0] };
const newUserConnected = {
userid: userId,
[userId]: socket.id
};
let receiverId = usersConnectedNow.filter(
i => i.userid == id.receiver_id
);
let senderId = usersConnectedNow.filter(i => i.userid == userId);
// console.log("data for pm", dataForPm);
receiverId.forEach(i =>
io.to(i[id.receiver_id]).emit("newPrivateMessage", dataForPm)
);
senderId.forEach(i =>
io.to(i[userId]).emit("newPrivateMessage", dataForPm)
);
});
socket.on("disconnect", () => {
console.log(`A socket with the id ${socket.id} just disconnected.`);
const socketDisconnected = socket.id;
// console.log("socketToRemove:", socketDisconnected);
usersConnectedNow = usersConnectedNow.filter(
i => i[userId] !== socketDisconnected
);
console.log("new users that are connected", usersConnectedNow);
});
});