-
Notifications
You must be signed in to change notification settings - Fork 40
/
app.js
171 lines (144 loc) · 4.7 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
const express = require("express");
const app = express();
const server = require("http").Server(app);
const io = require("socket.io")(server);
const cors = require("cors");
const connectDB = require("./config/db");
const jwt = require("jsonwebtoken");
const bcrypt = require("bcrypt");
const User = require("./models/user");
const { userJoin, userLeave, getUser, users } = require("./utils/users");
const user = require("./models/user");
const path = require("path");
app.use(express.static("public"));
app.use(express.json({ extended: false }));
app.use(cors({ origin: true, credentials: true }));
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "DELETE, PUT, GET, POST");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
next();
});
connectDB();
let userPeers = [];
app.get("/auth", function (req, res) {
const token = req.headers["x-auth-token"];
if (token) {
const decoded = jwt.verify(token, "shhhhh");
return res
.status(200)
.json({ user: { email: decoded.email, name: decoded.name } });
}
res.json({ message: "Failed Auth" });
});
app.post("/login", async function (req, res) {
const { email, password } = req.body;
const user = await User.findOne({ email: email });
if (user) {
const checkPassword = await bcrypt.compare(password, user.password);
if (checkPassword) {
const token = jwt.sign(
{ email: email, password: password, name: user.name },
"shhhhh"
);
return res
.status(200)
.json({ token, user: { email: user.email, name: user.name } });
}
return res.status(403).json({ message: "Failed" });
}
res.json({ message: "Failed" });
});
app.post("/register", async function (req, res) {
const { name, email, password } = req.body;
if (!name || !email || !password)
return res.status(500).json({ msg: "Please fill all!" });
let user = await User.findOne({ email });
if (user) {
return res.status(500).json({ msg: "Account exists" });
}
const salt = await bcrypt.genSalt(10);
user = new User({ name, email, password });
user.password = await bcrypt.hash(password, salt);
await user.save();
res.status(200).json({ user: email });
});
if (process.env.NODE_ENV === "production") {
// Set static folder
app.use(express.static("client/build"));
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "client", "build", "index.html"));
});
}
const port = process.env.PORT || 5000;
io.on("connection", (socket) => {
socket.on("joinRoom", ({ name, room, peerID }) => {
const user = userJoin({ id: socket.id, name, room, peerID });
if (peerID) userPeers.push(peerID);
socket.join(user.room);
socket.peerID = peerID;
// Wellcome room
socket.emit("message", { name: "Admin", msg: "Wellcome to chat app" });
let allMembersInRoom = users
.filter((user) => user.room === room)
.map((user) => user.peerID);
io.to(room).emit("allMembers", allMembersInRoom);
socket.broadcast.to(user.room).emit("message", {
name: "Admin",
msg: `${name} has joined to room`,
});
});
socket.on("sendMessage", ({ name, msg, room }) => {
io.to(room).emit("message", {
name,
msg,
});
});
socket.on("disconnect", () => {
const user = userLeave(socket.id);
if (user) {
socket.broadcast.to(user.room).emit("message", {
name: "Admin",
msg: `${user.name} has left to room`,
});
let allMembersInRoom = users
.filter((_user) => _user.room === user.room)
.map((user) => user.peerID);
io.to(user.room).emit("allMembers", allMembersInRoom);
}
userPeers = userPeers.filter((id) => id !== socket.peerID);
if (socket.client.conn.server.clientsCount == 0) {
userPeers = [];
}
});
socket.on("peerClose", ({ peerId }) => {
if (peerId) {
userPeers = userPeers.filter((id) => id !== peerId);
socket.peerID = null;
let user = userLeave(socket.id);
if (user) {
socket.broadcast.to(user.room).emit("message", {
name: "Admin",
msg: `${user.name} has left to room`,
});
let allMembersInRoom = users
.filter((_user) => _user.room === user.room)
.map((user) => user.peerID);
io.to(user.room).emit("allMembers", allMembersInRoom);
}
}
});
socket.on("getPeers", ({ room }) => {
console.log(room);
let peers = users
.filter((user) => user.room === room)
.map((user) => user.peerId);
io.to(room).emit("sendPeers", peers);
});
});
server.listen(port, () => {
console.log(`App is running on http://localhost:${port}`);
});