-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
248 lines (218 loc) · 6.21 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
const express = require("express");
const mongoose = require("mongoose");
const dotenv = require("dotenv");
const jwt = require("jsonwebtoken");
const cookieParser = require("cookie-parser");
const User = require("./models/User.js");
const Message = require("./models/Message.js");
const cors = require("cors");
const bcrypt = require("bcryptjs");
const ws = require("ws");
const fs = require("fs");
dotenv.config();
mongoose
.connect(process.env.MONGO_URL_2, {})
.then(() => console.log("Database connected!"))
.catch((err) => console.log(err));
jwtSecret = process.env.JWT_SECRET;
const bcryptSalt = bcrypt.genSaltSync(10);
const app = express();
app.use("/uploads", express.static(__dirname + "/uploads"));
app.use(express.json());
app.use(cookieParser());
app.use(
cors({
credentials: true,
origin: process.env.CLIENT_URL,
})
);
async function getUserDataFromRequest(req) {
return new Promise((resolve, reject) => {
const token = req.cookies?.token;
if (token) {
jwt.verify(token, jwtSecret, {}, (err, userData) => {
if (err) throw err;
// console.log(userData);
resolve(userData);
});
} else {
reject("no token");
}
});
}
app.get("/test", (req, res) => {
res.json("test ok");
});
app.post("/logout", (req, res) => {
res.cookie("token", "", { sameSite: "none", secure: true }).json("ok");
});
app.get("/messages/:userId", async (req, res) => {
const { userId } = req.params;
const userData = await getUserDataFromRequest(req);
const ourUserId = userData.userId;
const messages = await Message.find({
sender: { $in: [userId, ourUserId] },
recipient: { $in: [userId, ourUserId] },
}).sort({ createdAt: 1 });
res.json(messages);
});
app.get("/profile", (req, res) => {
const token = req.cookies?.token;
if (token) {
jwt.verify(token, jwtSecret, {}, (err, userData) => {
if (err) throw err;
res.json(userData);
});
} else {
res.status(401).json("no token");
}
});
app.post("/login", async (req, res) => {
const { username, password } = req.body;
const foundUser = await User.findOne({ username });
if (foundUser) {
const passOk = bcrypt.compareSync(password, foundUser.password);
if (passOk) {
jwt.sign(
{ userId: foundUser._id, username },
jwtSecret,
{},
(err, token) => {
if (err) throw err;
res
.cookie("token", token, { sameSite: "none", secure: true })
.status(201)
.json({
id: foundUser._id,
});
}
);
}
}
});
app.post("/register", async (req, res) => {
const { username, password } = req.body;
try {
const hashedPassword = bcrypt.hashSync(password, bcryptSalt);
const createdUser = await User.create({
username: username,
password: hashedPassword,
});
jwt.sign(
{ userId: createdUser._id, username },
jwtSecret,
{},
(err, token) => {
if (err) throw err;
res
.cookie("token", token, { sameSite: "none", secure: true })
.status(201)
.json({
id: createdUser._id,
});
}
);
} catch (err) {
if (err.code === 11000) {
return res.status(400).json({ message: "Username already exists" });
}
res.status(500).json("error");
}
});
app.get("/people", async (req, res) => {
const users = await User.find({}, { _id: 1, username: 1 });
res.json(users);
});
const server = app.listen(4040);
const wss = new ws.WebSocketServer({ server });
wss.on("connection", (connection, req) => {
function notifyAboutOnlinePeople() {
[...wss.clients].forEach((client) => {
client.send(
JSON.stringify({
online: [...wss.clients].map((c) => ({
userId: c.userId,
username: c.username,
})),
})
);
});
}
connection.isAlive = true;
connection.timer = setInterval(() => {
connection.ping();
connection.deathTimer = setTimeout(() => {
connection.isAlive = false;
connection.terminate();
notifyAboutOnlinePeople();
}, 1000);
}, 5000);
connection.on("pong", () => {
clearTimeout(connection.deathTimer);
});
// read username and id form the cookie for this connection
const cookies = req.headers.cookie;
if (cookies) {
const tokenCookieString = cookies
.split(";")
.find((str) => str.startsWith("token="));
if (tokenCookieString) {
const token = tokenCookieString.split("=")[1];
if (token) {
jwt.verify(token, jwtSecret, {}, (err, userData) => {
if (err) throw err;
const { userId, username } = userData;
connection.userId = userId;
connection.username = username;
});
}
}
}
// connection.on('message', (message, isBinary) => {
// console.log(isBinary ? message.toString() : message);
// });
// notify everyone about online people (when someone connnects)
notifyAboutOnlinePeople();
connection.on("message", async (message) => {
const messageData = JSON.parse(message.toString());
const { recipient, text, file } = messageData.message;
let filename = null;
if (file) {
console.log("size", file.data.length);
const parts = file.name.split(".");
const ext = parts[parts.length - 1];
filename = Date.now() + "." + ext;
const path = __dirname + "/uploads/" + filename;
const bufferData = new Buffer.from(file.data.split(",")[1], "base64");
fs.writeFile(path, bufferData, () => {
console.log("file saved:" + path);
});
}
if (recipient && (text || file)) {
const messageDoc = await Message.create({
sender: connection.userId,
recipient,
text,
file: file ? filename : null,
});
[...wss.clients]
.filter((c) => c.userId === recipient)
.forEach((c) =>
c.send(
JSON.stringify({
text,
sender: connection.userId,
recipient,
_id: messageDoc._id,
file: file ? filename : null,
})
)
);
}
});
});
wss.on("close", (data) => {
console.log("disconnect", data);
});
console.log("work");
//x98IAj8TgmBpLTUy