Skip to content

Commit

Permalink
Merge pull request #20 from sarvasvaKhare/server
Browse files Browse the repository at this point in the history
Server side code for socket.io step-2 backend
  • Loading branch information
pratham1002 authored Aug 17, 2020
2 parents ff5030e + 701ce2b commit a504bd1
Show file tree
Hide file tree
Showing 7 changed files with 144 additions and 50 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
21 changes: 10 additions & 11 deletions server/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,28 +2,27 @@
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
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
Expand All @@ -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
12 changes: 11 additions & 1 deletion server/index.js
Original file line number Diff line number Diff line change
@@ -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')
22 changes: 11 additions & 11 deletions server/middleware/auth.js
Original file line number Diff line number Diff line change
@@ -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 })
Expand All @@ -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);
});
});
Expand All @@ -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);
});
}
));
7 changes: 5 additions & 2 deletions server/models/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
54 changes: 30 additions & 24 deletions server/routers/index.js
Original file line number Diff line number Diff line change
@@ -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')
res.redirect('/rooms')
})

//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 }
76 changes: 76 additions & 0 deletions server/sockets/socket-server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
const {io} = require('./../index')

// on connecting with client socket
io.on('connection', (socket) => {
console.log('connected')
// join event listner
socket.once('join', function (roomname) {
let 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++) {
const 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) => {
let usernames = []; // array for storing usernames
let 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 => {
let 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
} 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')
})
})

0 comments on commit a504bd1

Please sign in to comment.