-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
347 lines (311 loc) · 9.33 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
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
"use strict";
const log = console.log;
const express = require("express");
const session = require("express-session");
const crypto = require("crypto");
const app = express();
const server = require("http").createServer(app);
// const io = require('socket.io')(server);
const sessionMiddleware = session({
secret: "thisisthesecretpleasedontreadthis",
resave: false,
saveUninitialized: false,
cookie: {
expires: 60000 * 1000,
httpOnly: true
}
});
/*
io.use((socket, next) => {
sessionMiddleware(socket.request, socket.request.res, next);
});
*/
const { User, Item, Room } = require("./schemas.js");
//const socket_setup = require('./socket-setup.js');
const mongoose = require("mongoose");
const dbpath = process.env.DB_PATH || "mongodb://localhost:27017/test";
mongoose.connect(dbpath);
const cloudinary = require("cloudinary").v2;
cloudinary.config({
cloud_name: process.env.cloudinary_cloud_name,
api_key: process.env.cloudinary_api_key,
api_secret: process.env.cloudinary_api_secret
});
app.use(express.static(__dirname + "/pub"));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(sessionMiddleware);
function existsUserPass(req, res, next) {
const body = req.body;
if (typeof body.password === "undefined" || typeof body.user === "undefined") {
res.status(400).send("Username and password cannot be empty");
} else if (body.password.length === 0 || body.user.length === 0) {
res.status(400).send("Username and password cannot be empty");
} else {
next();
}
}
function authenticate(req, res, next) {
if (!req.session.username) res.sendStatus(401);
else next();
}
app.post("/api/signup", existsUserPass, async (req, res) => {
const body = req.body;
const docs = await User.find({ user: body.user }).exec();
if (docs.length > 0) {
res.status(400).send("Username is already taken.");
return;
}
const user = new User({ user: body.user, password: body.password });
await user.save();
res.sendStatus(200);
});
app.post("/api/login", existsUserPass, async (req, res) => {
try {
const user = await User.authenticate(req.body.user, req.body.password);
req.session.username = user.user;
await res.sendStatus(200);
} catch (e) {
console.error(e);
await res.status(400).send("Invalid username or password");
}
});
app.get("/api/logout", (req, res) => {
req.session.destroy(error => {
if (error) {
res.sendStatus(500);
} else {
res.redirect("/");
}
});
});
app.get("/api/room/:id", async (req, res) => {
const room = await Room.findById(req.params.id);
for (let i = 0; i < room.users.length; i++) {
room.users[i] = await User.findById(room.users[i]);
}
res.json(room);
});
app.get("/api/id/:username", (req, res) => {
User.findOne({ user: req.params.username }).then(
user => {
if (user) res.send(user);
else res.sendStatus(404);
},
error => {
res.status(500).send(error);
}
);
});
app.get("/api/user/:id", (req, res) => {
const id = req.params.id;
User.findById(id)
.then(user => {
if (!user) {
res.status(404).send();
} else {
res.send(user);
}
})
.catch(e => {
res.status(500).send(e);
});
});
app.get("/api/shop", (req, res) => {
Item.find({}, (err, items) => {
res.json(items);
});
});
app.get("/api/shop/user", authenticate, async (req, res) => {
const items = await Item.find({});
const user = await User.findOne({ user: req.session.username });
if (!user) {
res.sendStatus(404);
return;
}
await res.json(items.filter(x => !user.itemsOwned.includes(x._id)));
});
app.get("/api/shop/:itemid", async (req, res) => {
let item;
try {
item = await Item.findById(req.params.itemid);
} catch (e) {
res.sendStatus(404);
return;
}
if (!item) {
res.sendStatus(404);
return;
}
await res.json(item);
});
app.put("/api/shop/:itemid", authenticate, async (req, res) => {
let user;
let item;
try {
user = await User.findOne({ user: req.session.username });
item = await Item.findById(req.params.itemid);
} catch (e) {
res.sendStatus(403);
return;
}
if (!user || !item) {
res.sendStatus(404);
} else if (user.money < item.price && !user.isAdmin) {
res.status(401).send("Not enough money");
} else if (user.itemsOwned.includes(item._id)) {
res.status(401).send("Already owned");
} else {
user.itemsOwned.push(item._id);
user.money -= item.price;
await res.json(user);
await user.save();
}
});
// Post item
app.post("/api/shop/item", async (req, res) => {
const item = new Item({
name: req.body.name,
description: req.body.description,
image: req.body.image,
price: req.body.price
});
await item.save();
res.sendStatus(200);
});
app.get("/api/item/:id", async (req, res) => {
try {
const item = await Item.findById(req.params.id);
if (!item) {
res.sendStatus(404);
} else {
await res.json(item);
}
} catch (e) {
res.sendStatus(404);
}
});
// Get current User
app.get("/api/user", authenticate, async (req, res) => {
// console.log(req.session.username)
try {
const user = await User.findOne({ user: req.session.username });
if (!user) {
return res.sendStatus(404);
}
const items = [];
for (let i = 0; i < user.itemsOwned.length; i++) {
items.push(await Item.findById(user.itemsOwned[i]));
}
items.push({
name: "Default",
description: "This is the default item",
behaviourId: 0,
image: "img/default.png"
});
user.itemsOwned = items;
user.itemSelected = await Item.findById(user.itemSelected);
await res.json(user);
} catch (e) {
res.status(500).send(e);
}
});
// Get list of all existing (non-admin) users
app.get("/api/users", (req, res) => {
User.find().then(
users => {
users = users.filter(user => !user.isAdmin);
res.send(users);
},
error => {
res.status(500).send(error);
}
);
});
// Get list of all existing users (including admin)
app.get("/api/users/all", (req, res) => {
User.find().then(
users => {
res.send(users);
},
error => {
res.status(500).send(error);
}
);
});
// update given user's info
app.patch("/api/user", authenticate, (req, res) => {
const username = req.body.username;
const money = req.body.money;
const wins = req.body.wins;
const points = req.body.points;
const itemSelected = req.body.itemSelected;
const image = req.body.image;
User.find().then(allUsers => {
const targetUser = allUsers.filter(user => user.user === username);
targetUser[0].money = money;
targetUser[0].wins = wins;
targetUser[0].points = points;
targetUser[0].image = image;
if (itemSelected || itemSelected === null) {
targetUser[0].itemSelected = itemSelected;
}
targetUser[0].save().then(
resultUser => {
// do nothing for now
},
error => {
res.status(400).send(error);
}
);
});
});
app.get("/api/createGame", authenticate, async (req, res) => {
const user = await User.findOne({ user: req.session.username });
if (!user) return res.sendStatus(404);
const room = new Room({ users: [user._id] });
await room.save();
return res.redirect("/room/" + room._id);
});
app.get("/room/:id", authenticate, async (req, res) => {
if (await Room.findById(req.params.id)) res.sendFile("./pub/room.html", { root: __dirname });
else res.sendStatus(404);
});
app.get("/board/:id", authenticate, async (req, res) => {
if (await Board.findById(req.params.id)) res.sendFile("./pub/board.html", { root: __dirname });
else res.sendStatus(404);
});
app.put("/api/win", authenticate, async (req, res) => {
const user = await User.findOne({ user: req.session.username });
user.wins += 1;
user.points += 0.2;
user.money += 100 + user.points * 100;
await user.save();
res.sendStatus(200);
});
/*
io.on('connection', (socket) => {
if(!socket.request.session.username){
return socket.disconnect(true);
} else {
socket_setup(socket);
}
});
*/
app.get("/signature", function signatureCallback(req, res) {
const time = Date.now();
const str = `public_id=${req.session.username}&source=uw×tamp=${time}&upload_preset=ml_default${process.env.cloudinary_api_secret}`;
const shasum = crypto.createHash("sha1");
shasum.update(str);
const shastr = shasum.digest("hex");
res.json({
shastr: shastr,
time: time,
api_key: process.env.cloudinary_api_key,
cloud_name: process.env.cloudinary_cloud_name
});
});
const port = process.env.PORT || 5000;
server.listen(port, () => {
log(`Server started on port ${port}...`);
});