-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
254 lines (234 loc) · 5.7 KB
/
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
require("dotenv").config();
const express = require("express");
const mongoose = require("mongoose");
const session = require("express-session");
const passport = require("passport");
const ejs = require("ejs");
const passportLocalMongoose = require("passport-local-mongoose");
const socketio = require("socket.io");
const moment = require("moment");
const http = require("http");
const bodyParser = require("body-parser");
const { use } = require("passport");
// defining app, server and socket
const app = express();
const server = http.createServer(app);
const io = socketio(server);
// middleware stuff
app.use(express.static("public"));
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({ extended: true }));
// passport stuff
app.use(
session({
secret: process.env.SECRET,
resave: false,
saveUninitialized: false,
})
);
app.use(passport.initialize());
app.use(passport.session());
// connecting to database
mongoose.connect(
process.env.DB_STRING,
{ useNewUrlParser: true, useUnifiedTopology: true },
(err) => {
if (!err) {
console.log("connected to database");
} else {
console.log(err);
}
}
);
// fixing deprecation warning
mongoose.set("useCreateIndex", true);
// defining the schemas and models wuth passport plugin
const userSchema = new mongoose.Schema({
email: String,
password: String,
halls: [],
});
userSchema.plugin(passportLocalMongoose);
const User = mongoose.model("User", userSchema);
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
// defining the non passport schemas and models
const hallSchema = new mongoose.Schema({
name: String,
members: [],
messages: [],
});
const Hall = mongoose.model("Hall", hallSchema);
// setting up server to listen
const PORT = process.env.PORT;
server.listen(PORT, () => console.log(`server is live on port ${PORT}`));
// =============== routes ============================
// serving the home page
app.get("/home", (req, res) => {
if (req.isAuthenticated()) {
res.render("home", { user: req.user });
} else {
res.redirect("/login");
}
});
// serving the hall page
app.get("/hall/:hall", (req, res) => {
if (req.isAuthenticated()) {
Hall.findOne({ name: req.params.hall }, (err, hall) => {
if (!err && hall !== null) {
res.render("hall", { hall: hall, user: req.user });
} else {
res.redirect("/home");
}
});
} else {
res.redirect("/login");
}
});
// creating new hall
app
.route("/create")
.get((req, res) => {
if (req.isAuthenticated()) {
res.render("create");
} else {
res.redirect("/login");
}
})
.post((req, res) => {
if (req.isAuthenticated()) {
Hall.findOne({ name: req.body.name }, (err, hall) => {
if (!err && hall === null) {
User.findById(req.user.id, (err, user) => {
if (!err) {
// creating the new hall
user.halls.push(req.body.name);
user.save();
createdHall = Hall({
name: req.body.name,
members: [req.user.username],
});
createdHall.save();
// redirecting to created hall
res.redirect(`/hall/${req.body.name}`);
} else {
res.redirect("/home");
}
});
} else {
res.redirect("/home");
}
});
} else {
res.redirect("/login");
}
});
// joining hall
app
.route("/join")
.get((req, res) => {
if (req.isAuthenticated()) {
res.render("join");
} else {
res.redirect("/login");
}
})
.post((req, res) => {
if (req.isAuthenticated()) {
Hall.findById(req.body.code, (err, hall) => {
if (!err && hall !== null && !req.user.halls.includes(hall.name)) {
// get user to add to hall
User.findById(req.user.id, (err, user) => {
if (!err && user !== null) {
// add hall to user
user.halls.push(hall.name);
user.save();
// add user to hall
hall.members.push(user.username);
hall.save();
res.redirect(`/hall/${hall.name}`);
} else {
res.redirect("/home");
}
});
} else {
res.redirect("/home");
}
});
} else {
res.redirect("/login");
}
});
// register new user
app.post("/register", (req, res) => {
User.register(
{
username: req.body.username,
},
req.body.password,
(err, user) => {
if (err) {
console.log(err);
res.redirect("/register");
} else {
passport.authenticate("local")(req, res, () => {
// everything is succesfull
res.redirect("/home");
});
}
}
);
});
// login old user
app.post("/login", (req, res) => {
const user = new User({
username: req.body.username,
password: req.body.password,
});
req.logIn(user, (err) => {
if (err) {
console.log();
} else {
passport.authenticate("local")(req, res, () => {
// eveything is succesfull
res.redirect("/home");
});
}
});
});
// logout
app.get("/logout", (req, res) => {
req.logout();
res.redirect("/");
});
// ================= socket stuff ======================
io.on("connection", (socket) => {
socket.on("greeting", (details) => {
socket.join(details.hall);
// socket has joined hall
// send recent messages to socket
sendMessages(socket, details.hall);
socket.on("messageSend", (message) => {
// adding timestamp to messages
const timestamp = moment().format("h:mm:ss a, MMMM Do YYYY");
message.timestamp = timestamp;
saveMessage(message, details.hall);
io.to(details.hall).emit("messageRecieve", message);
});
});
});
function sendMessages(socket, hallName) {
Hall.findOne({ name: hallName }, (err, hall) => {
if (!err && hall !== null) {
socket.emit("oldMessages", hall.messages);
}
});
}
function saveMessage(message, hallName) {
Hall.findOne({ name: hallName }, (err, hall) => {
if (!err && hall !== null) {
hall.messages.push(message);
hall.save();
}
});
}