diff --git a/package.json b/package.json index 4e27896..7554983 100644 --- a/package.json +++ b/package.json @@ -41,7 +41,7 @@ }, "devDependencies": { "env-cmd": "^8.0.2", - "eslint": "^7.3.1", + "eslint": "^7.6.0", "eslint-config-standard": "^14.1.1", "eslint-plugin-import": "^2.22.0", "eslint-plugin-node": "^11.1.0", diff --git a/server/app.js b/server/app.js index 63b8c61..1311a82 100644 --- a/server/app.js +++ b/server/app.js @@ -2,10 +2,10 @@ const express = require('express') const path = require('path') const dotenv = require('dotenv') -dotenv.config( {path: 'server/.env'}); +dotenv.config({ path: 'server/.env' }); //database setup -const mongoose =require('mongoose') +const mongoose = require('mongoose') require('./db/mongoose') //passport setup for authentication and sessions @@ -13,17 +13,16 @@ const app = express() const session = require('express-session'); const passport = require("passport"); app.use(session({ - secret: process.env.SECRET, - resave: false, - saveUninitialized: false - })); + secret: process.env.SECRET, + resave: false, + saveUninitialized: false +})); app.use(passport.initialize()); app.use(passport.session()); const passports = require('./middleware/auth') - // index router for various routes -const indexRouter = require('./routers/index') +const { router } = require('./routers/index') //file location for different ejs files @@ -32,8 +31,8 @@ const publicDirectoryPath = path.join(__dirname, '../client') //ejs setup app.set('view engine', 'ejs') app.set('views', publicDirectoryPath) -app.use(express.static(publicDirectoryPath, { index: '_' })) -app.use(indexRouter) +app.use(express.static(publicDirectoryPath, { index: '_' })) +app.use(router) //exporting module for index.js -module.exports = app +module.exports = app \ No newline at end of file diff --git a/server/index.js b/server/index.js index cd7bc19..87277ae 100644 --- a/server/index.js +++ b/server/index.js @@ -1,8 +1,18 @@ //importing app const app = require('./app') +const http = require('http') +const socket = require('socket.io') + //port as enviroment variable const port = process.env.PORT || 3000 +const server = http.createServer(app) + //server up check -app.listen(port, () => { +server.listen(port, () => { console.log('Server is up on port ' + port) }) + +//socket setup +const io = socket(server) +module.exports = { io } +require('./sockets/socket-server') \ No newline at end of file diff --git a/server/middleware/auth.js b/server/middleware/auth.js index ebec376..94c9acf 100644 --- a/server/middleware/auth.js +++ b/server/middleware/auth.js @@ -1,9 +1,9 @@ //userSchema const User = require("./../models/user") const bodyParser = require('body-parser') - const passport = require("passport"); +const passport = require("passport"); - const GoogleStrategy = require('passport-google-oauth20').Strategy; +const GoogleStrategy = require('passport-google-oauth20').Strategy; var urlencodedParser = bodyParser.urlencoded({ extended: false }) @@ -12,13 +12,13 @@ var urlencodedParser = bodyParser.urlencoded({ extended: false }) passport.use(User.createStrategy()); //serializing user creating session cookie -passport.serializeUser(function(user, done) { +passport.serializeUser(function (user, done) { done(null, user.id); }); // deserializing cookie to get user info -passport.deserializeUser(function(id, done) { - User.findById(id, function(err, user) { +passport.deserializeUser(function (id, done) { + User.findById(id, function (err, user) { done(err, user); }); }); @@ -28,10 +28,10 @@ passport.use(new GoogleStrategy({ callbackURL: "https://acm-bluff.herokuapp.com/auth/google/home", userProfileURL: "https://www.googleapis.com/oauth2/v3/userinfo" }, -// function for verify and storing user into database -function(accessToken, refreshToken, profile, cb) { - User.findOrCreate({ googleId: profile.id}, function (err, user) { - return cb(err, user); - }); -} + // function for verify and storing user into database + function (accessToken, refreshToken, profile, cb) { + User.findOrCreate({ googleId: profile.id }, function (err, user) { + return cb(err, user); + }); + } )); diff --git a/server/models/user.js b/server/models/user.js index 64cf08a..1df214c 100644 --- a/server/models/user.js +++ b/server/models/user.js @@ -2,13 +2,16 @@ const mongoose = require('mongoose'); const passportLocalMongoose = require("passport-local-mongoose"); + //findOrCreate module for using function in passport const findOrCreate = require('mongoose-findorcreate') + //userSchema const userSchema = new mongoose.Schema({ - googleId: {type: String, index: true, unique: true}, + googleId: { type: String, index: true, unique: true }, }); -userSchema.plugin(passportLocalMongoose,{usernameField:'googleId',saltField: process.env.SALT,hashField: process.env.HASH}) +userSchema.plugin(passportLocalMongoose, { usernameField: 'googleId', saltField: process.env.SALT, hashField: process.env.HASH }) userSchema.plugin(findOrCreate); + const User = mongoose.model('user', userSchema, 'user'); module.exports = User \ No newline at end of file diff --git a/server/routers/index.js b/server/routers/index.js index 975f272..08cc546 100644 --- a/server/routers/index.js +++ b/server/routers/index.js @@ -1,41 +1,47 @@ -//router setup +// router setup const express = require('express') const router = new express.Router() -//authentication setup -const passport = require("passport"); +// authentication setup +const passport = require('passport') -//index route +// index route router.get('', (req, res) => { res.render('index') }) -//google auth entry route -router.get('/login',(req,res)=>{ -res.redirect('/auth/google') +// google auth entry route +router.get('/login', (req, res) => { + res.redirect('/auth/google') }) -//route authenticating user by google +// route authenticating user by google router.get('/auth/google', - passport.authenticate('google',{scope: ["profile"]}) + passport.authenticate('google', { + scope: ['profile'] + }) ) -//route redirected to after sucessfull authentication from google -router.get('/auth/google/home',passport.authenticate('google', { failureRedirect: "/login" }), -function(req, res) { - res.redirect("/result"); -}); +// route redirected to after sucessfull authentication from google +router.get('/auth/google/home', passport.authenticate('google', { + failureRedirect: '/login' +}), +function (req, res) { + res.redirect('/result') +}) // redirected route to render result page -router.get('/result',(req,res)=>{ - if (req.isAuthenticated()){ +router.get('/result', (req, res) => { + if (req.isAuthenticated()) { res.render('index') - }else{ - res.redirect('/login') - } - - + } else { + res.redirect('/login') + } }) -//exporting module for app.js -module.exports = router +// route for socket testing +router.get('/rooms', (req, res) => { + res.render('test') +}) +// exporting module for app.js +module.exports = { router } diff --git a/server/sockets/socket-server.js b/server/sockets/socket-server.js new file mode 100644 index 0000000..dad5548 --- /dev/null +++ b/server/sockets/socket-server.js @@ -0,0 +1,115 @@ +const { io } = require('./../index') + +// on connecting with client socket +io.on('connection', (socket) => { + console.log('connected') + // join event listner + socket.once('join', function (roomname) { + const people = io.nsps['/'].adapter.rooms[roomname] + // checks for maximum users and if game started? + + if ((people && people.length > 11) || (people && people.allowed !== undefined)) { + } else { + socket.join(roomname) // if passed checks joins room + socket.broadcast.emit('broadcast', 'new player joined') // brodcast every other a player has joined + socket.emit('connectToRoom', 'You are in room ' + roomname) // emit user the roomname + } + }) + + // set username event listner + socket.on('setUsername', function (data) { + let usernameTaken = 0 // var for checking unique username + io.in(data.roomname).clients((error, clients) => { // getting all clients in room + if (error) throw error + // loop for checking username of every other player with given username + for (var i = 0; i < clients.length; i++) { + var user = io.sockets.sockets[clients[i]] // saving socket into user + + if (user.username === data.username) { // if equal therfore username taken + usernameTaken = 1 // setting var to 1 + break // break from loop + } + } + + if (!usernameTaken) { + socket.username = data.username // setting username in socket of that client + socket.emit('userSet', { username: data.username }) // emiting username to client side + } else { + // emitting dupilicate username to client side + socket.emit('userExists', data.username + ' username is taken! Try some other username.') + socket.emit('newPrompt') // emitting new Prompt for new username + } + }) + }) + + // gameStart listner + socket.on('gameStart', (data) => { + const usernames = [] // array for storing usernames + const people = io.nsps['/'].adapter.rooms[data.roomname] + io.in(data.roomname).clients((error, clients) => { // getting all clients in a room + if (error) throw error + clients.forEach(client => { + const person = io.sockets.sockets[client] + usernames.push(person.username) // adding their username to usernames array + }) + }) + if (people.length > 1) { + people.allowed = 1 // setting var for game started true + io.in(data.roomname).emit('usersList', usernames) // emitting usernames list to clients + const players = people.length // no of players + // shuffled cards array + var cards = 54 + if (players > 4 && players < 10) { + cards = 108 + } else if (players > 9) { + cards = 162 + } + for (var a = [], i = 0; i < cards; ++i) a[i] = i + + a = shuffle(a) // shuffles cards array a + const playerscards = new Array(players) // creating arrays for storing playerscards + for (let i = 0; i < players; i++) { + playerscards[i] = [] + } + let x = cards + let j = 0 + while (x) { + for (let i = 0; i < players; i++) { + if (x) { + playerscards[i][j] = a[--x] + } else { + break + } + } + j++ + } + io.in(data.roomname).emit('playerCards', playerscards) // emiting playercards array to everyone + } else { + io.in(data.roomname).emit('lessPlayers', 'need more to start game') + } + }) + // cardHandToDeck event listner + socket.on('cardHandToDeck', (data) => { + io.in(data.roomname).emit('cardsInDeck', data.ids) + }) + // endGame event listner + socket.on('endGame', (data) => { + io.in(data.roomname).emit('redirect', '/') + }) + // dissconection event + socket.once('disconnect', function () { + console.log('disconnected') + }) +}) +function shuffle (array) { + let tmp; let current; let top = array.length + if (top) { + while (--top) { + current = Math.floor(Math.random() * (top + 1)) + tmp = array[current] + array[current] = array[top] + array[top] = tmp + } + } + return array +}