-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
351 lines (294 loc) · 10.1 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
348
349
350
351
const express = require('express'); // npm install passport passport-google-oauth20 bcrypt jsonwebtoken express-validator axios dotenv passport-discord express-session mutler
const http = require('http');
const socketIo = require('socket.io');
const multer = require('multer');
const path = require('path');
const { body, validationResult } = require('express-validator');
const axios = require('axios');
const bcrypt = require('bcrypt');
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const DiscordStrategy = require('passport-discord').Strategy;
const session = require('express-session');
require('dotenv').config();
const app = express();
const server = http.createServer(app);
const io = socketIo(server);
app.use(express.json());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: true,
cookie: { secure: false } // Set to true if using HTTPS
}));
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser((user, done) => {
try {
done(null, user.id);
} catch (error) {
console.error('Error during serialization:', error);
done(error, null);
}
});
passport.deserializeUser(async (id, done) => {
try {
const user = await getUserById(id); // Fetch the user from DB
done(null, user);
} catch (error) {
console.error('Error during deserialization:', error);
done(error, null);
}
});
const GOOGLE_CLIENT_ID = process.env.GOOGLE_CLIENT_ID;
const GOOGLE_CLIENT_SECRET = process.env.GOOGLE_CLIENT_SECRET;
const DISCORD_CLIENT_ID = process.env.DISCORD_CLIENT_ID;
const DISCORD_CLIENT_SECRET = process.env.DISCORD_CLIENT_SECRET;
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'boardgame.html'));
});
const users = {}; // This should be replaced by a database in production.
async function getUserById(id) {
return users[id] || null;
}
// Signup route
app.post('/signup', [
body('username').isLength({ min: 3 }),
body('password').isLength({ min: 5 }),
body('recaptchaToken').notEmpty()
], async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { username, password, recaptchaToken } = req.body;
if (users[username]) {
return res.status(400).json({ message: 'Username already exists' });
}
// Verify reCAPTCHA
const secretKey = process.env.RECAPTCHA_SECRET_KEY;
const response = await axios.post('https://www.google.com/recaptcha/api/siteverify', null, {
params: {
secret: secretKey,
response: recaptchaToken
}
});
if (!response.data.success) {
return res.status(400).json({ message: 'Captcha verification failed' });
}
const hashedPassword = await bcrypt.hash(password, 10);
users[username] = { password: hashedPassword };
res.status(201).json({ message: 'User created successfully' });
});
// Login route
app.post('/login', [
body('username').isLength({ min: 3 }),
body('password').isLength({ min: 5 })
], async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { username, password } = req.body;
if (!users[username]) {
return res.status(400).json({ message: 'User does not exist' });
}
const match = await bcrypt.compare(password, users[username].password);
if (!match) {
return res.status(400).json({ message: 'Invalid password' });
}
const token = jwt.sign({ username }, process.env.JWT_SECRET, { expiresIn: '1h' });
res.json({ token });
});
passport.use(new GoogleStrategy({
clientID: GOOGLE_CLIENT_ID,
clientSecret: GOOGLE_CLIENT_SECRET,
callbackURL: "/auth/google/callback"
}, (accessToken, refreshToken, profile, done) => {
// Here, you can find or create a user in your database based on the Google profile
return done(null, profile);
}));
// Initialize passport
app.use(passport.initialize());
// Routes
app.get('/auth/google',
passport.authenticate('google', { scope: ['profile', 'email'] })
);
app.get('/auth/google/callback',
passport.authenticate('google', { failureRedirect: '/login' }),
(req, res) => {
res.redirect('/');
}
);
passport.use(new DiscordStrategy({
clientID: DISCORD_CLIENT_ID,
clientSecret: DISCORD_CLIENT_SECRET,
callbackURL: "/auth/discord/callback",
scope: ['identify', 'email']
}, (accessToken, refreshToken, profile, done) => {
// Find or create a user in your database based on the Discord profile
return done(null, profile);
}));
// Routes
app.get('/auth/discord',
passport.authenticate('discord')
);
app.get('/auth/discord/callback',
passport.authenticate('discord', { failureRedirect: '/login' }),
(req, res) => {
// Successful authentication
res.redirect('/');
}
);
// Function for in-game auth
function authenticateToken(req, res, next) {
const token = req.headers['authorization'];
if (!token) return res.sendStatus(401);
jwt.verify(token, process.env.JWT_SECRET, (err, user) => {
if (err) return res.sendStatus(403);
req.user = user;
next();
});
}
// Profile Settings
// Set storage for profile pictures
const storage = multer.diskStorage({
destination: './uploads/',
filename: (req, file, cb) => {
cb(null, req.user.username + path.extname(file.originalname));
}
});
// Init multer upload
const upload = multer({
storage: storage,
limits: { fileSize: 3000000 }, // Limit size to 1MB
fileFilter: (req, file, cb) => {
const filetypes = /jpeg|jpg|png/;
const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
const mimetype = filetypes.test(file.mimetype);
if (mimetype && extname) {
return cb(null, true);
} else {
cb('Error: Images Only!');
}
}
}).single('profilePic');
// Route to upload profile picture
app.post('/profile/upload', (req, res) => {
upload(req, res, (err) => {
if (err) {
return res.status(400).json({ message: err });
}
// Save the uploaded file's path to the user's profile
users[req.user.username].profilePic = `/uploads/${req.file.filename}`;
res.json({ message: 'Profile picture updated successfully' });
});
});
app.post('/profile/update', (req, res) => {
const { name, status } = req.body;
if (!name || !status) {
return res.status(400).json({ message: 'Name and status are required' });
}
// Update user's profile data
users[req.user.username].name = name;
users[req.user.username].status = status;
res.json({ message: 'Profile updated successfully' });
});
// Fetch user profile data
app.get('/profile', (req, res) => {
const user = users[req.user.username];
if (!user) {
return res.status(404).json({ message: 'User not found' });
}
res.json({
profilePic: user.profilePic || '/default-avatar.png',
name: user.name || req.user.username,
status: user.status || 'offline',
level: user.level || 1,
wins: user.wins || 0
});
});
// Fetch friends list
app.get('/friends', (req, res) => {
const friends = req.user.friends || [];
const friendProfiles = friends.map(friendUsername => {
const friend = users[friendUsername];
return {
name: friend.name,
profilePic: friend.profilePic || '/default-avatar.png',
status: friend.status || 'offline',
level: friend.level || 1,
wins: friend.wins || 0
};
});
res.json(friendProfiles);
});
// Game Logic Starts Here
let availableLocations = [];
io.use((socket, next) => {
const token = socket.handshake.query.token;
if (token) {
jwt.verify(token, process.env.JWT_SECRET, (err, user) => {
if (err) return next(new Error('Authentication error'));
socket.user = user;
next();
});
} else {
next(new Error('Authentication error'));
}
}).on('connection', (socket) => {
console.log('A player connected:', socket.user.username);
socket.on('setLocations', (locations) => {
if (locations.length > 0) {
availableLocations = locations;
console.log('Available locations updated:', availableLocations);
} else {
socket.emit('errorMessage', 'Please choose locations from the map-board.');
}
});
socket.on('startGame', () => {
const players = getPlayers();
if (availableLocations.length === 0) {
socket.emit('errorMessage', 'Please choose locations from the map-board.');
return;
}
const location = chooseRandomLocation(availableLocations);
const roles = assignRoles(players, location);
players.forEach(player => {
io.to(player.id).emit('assignedRole', {
role: player.role,
location: player.location
});
});
});
socket.on('disconnect', () => {
console.log('A player disconnected');
});
});
function chooseRandomLocation(locations) {
const randomIndex = Math.floor(Math.random() * locations.length);
return locations[randomIndex].location;
}
function getPlayers() {
return Array.from(io.sockets.sockets.values()).map(socket => ({
id: socket.id,
username: socket.user.username,
socket: socket,
}));
}
function assignRoles(players, location) {
let spyIndex = Math.floor(Math.random() * players.length);
players.forEach((player, index) => {
if (index === spyIndex) {
player.role = 'spy';
player.location = null;
} else {
player.role = 'location';
player.location = location;
}
});
return players;
}
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => console.log(`Server running on port ${PORT}`));