Skip to content
Snippets Groups Projects
Commit d9bf196c authored by narindra.rajohnso's avatar narindra.rajohnso
Browse files

add socket io logic

parent cf85e1ea
No related branches found
No related tags found
No related merge requests found
No preview for this file type
......@@ -10,16 +10,26 @@ import multer from 'multer';
import Config from '../config/Config';
import BaseRoutes from '../routes/BaseRoutes';
import ServerIO from '../socket.io/ServerIO';
import routerUser from "../routes/router-gamer";
import routerGamer from "../routes/router-gamer";
import routerGuest from "../routes/router-guest";
import routerAdmin from "../routes/router-admin";
import jwt from 'jsonwebtoken';
import * as IO from 'socket.io';
export interface SocketIoInfo extends IO.Socket{
user :any;
}
class Server {
private readonly backend: Express;
private readonly server: http.Server;
private readonly io: ServerIO;
public static invalidTokens: string[] = [];
constructor() {
this.backend = express();
......@@ -52,6 +62,16 @@ class Server {
this.server = http.createServer(this.backend);
this.io = new ServerIO(this.server);
this.io.use((socket: SocketIoInfo, next) => {
const token = socket.handshake.auth.token;
try {
socket.user = jwt.verify(token, process.env.SECRET_KEY);
next();
} catch (error) {
next(new Error('Invalid token'));
}
});
}
run() {
......
......@@ -47,6 +47,8 @@ export interface TokenRequest extends express.Request {
user?: any;
}
export async function verifyToken(req: TokenRequest, res: express.Response, next: express.NextFunction) {
const authHeader = req.headers['authorization'];
......@@ -59,7 +61,7 @@ export async function verifyToken(req: TokenRequest, res: express.Response, next
try {
req.user = jwt.verify(token, secretKey);
if(req.user.username !== req.params.admin)
if(req.user.username !== req.params.admin && req.user.username !== req.params.username)
return res.status(403).json({message: 'Invalid token user'});
//check if admin or user
next();
......
......@@ -29,7 +29,7 @@ router.post('/:username', checkExistingUser, async (req: express.Request, res: e
let usertype=user.dataValues.type === "user"?"USER":"ADMIN"
if (user.dataValues.password === data.password) {
// Génération du token JWT
const userInfo={ type: userType, username: req.params.username, firstname: user.dataValues.firstname, lastname: user.dataValues.lastname }
const userInfo={ type: user.dataValues.type, username: req.params.username, firstname: user.dataValues.firstname, lastname: user.dataValues.lastname }
const secretKey=process.env.SECRET_KEY;
const token = jwt.sign(userInfo, secretKey);
res.status(StatusCodes.OK).json({message: usertype+"_ALLOWED", token: token, firstname: user.dataValues.firstname, lastname: user.dataValues.lastname});
......
import * as IO from 'socket.io';
import logger from '../logging/WinstonLogger';
import http from 'http';
import Server, {SocketIoInfo} from "../express/Server";
import {UserInfo} from "./UserInfo"
//TODO: In this file you can add/edit all things about socket.io
class ServerIO extends IO.Server {
players: { [key: string]: UserInfo } = {};
constructor(server: http.Server) {
super(server, {
cors: {
......@@ -13,18 +18,67 @@ class ServerIO extends IO.Server {
}
});
this.on('connection', (socket: IO.Socket) => {
this.on('connection', (socket: SocketIoInfo) => {
logger.info(`Nouveau socket vers ${ socket.client.conn.remoteAddress }`) ;
console.log(`Socket info: ${ socket.user.username } // ${ socket.user.firstname } // ${socket.user.lastname}`);
const playerKey = socket.user.username;
// Vérifiez si le joueur existe déjà dans le dictionnaire
if (this.players[playerKey]) {
// Le joueur est déjà connecté, vous pouvez effectuer une action appropriée ici
console.log(`Player ${playerKey} is already connected.`);
} else {
// Le joueur n'est pas encore connecté, ajoutez-le au dictionnaire
this.players[playerKey] = new UserInfo(
socket.user.username,
socket.user.firstname,
socket.user.lastname
);
console.log(`Player ${playerKey} is connected.`);
}
this.testNumberofPlayer();
this.registerEventsOnSocket(socket);
});
}
private registerEventsOnSocket(socket: SocketIoInfo) {
socket.on('disconnect', () => {
logger.info(`Deconnexion du socket ${ socket.client.conn.remoteAddress }`) ;
console.log(`Socket info: ${ socket.user.username } // ${ socket.user.firstname } // ${socket.user.lastname}`);
const playerKey = socket.user.username;
// Vérifiez si le joueur est dans le dictionnaire
if (this.players[playerKey]) {
// Le joueur est connecté, retirez-le du dictionnaire
delete this.players[playerKey];
console.log(`Player ${playerKey} is disconnected.`);
} else {
// Le joueur n'est pas trouvé dans le dictionnaire, cela peut être un cas anormal
console.log(`Player ${playerKey} is not connected.`);
}
this.testNumberofPlayer();
private registerEventsOnSocket(socket: IO.Socket) {
socket.on('Hello World', _ => {
socket.emit('Bienvenue', socket.id);
});
}
private testNumberofPlayer(){
if(Object.keys(this.players).length < 3){
this.emit("players-left", 3 - Object.keys(this.players).length)
console.log(Object.keys(this.players).length)
}
if (Object.keys(this.players).length === 3) {
// Démarre le jeu
this.emit('start-game');
}
}
}
......
export class UserInfo {
constructor(
public username: string,
public firstname: string,
public lastname: string
){}
}
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment