Setup web-socket connection
- Add authentification socket.io with jwt token
This commit is contained in:
parent
cb11acc428
commit
ba47d8b1d4
5 changed files with 120 additions and 3 deletions
|
@ -2,18 +2,35 @@ import socketIO = require('socket.io');
|
|||
import {Socket} from "socket.io";
|
||||
import * as http from "http";
|
||||
import {MessageUserPosition} from "@Model/Websocket/MessageUserPosition";
|
||||
import {ExSocketInterface} from "@Model/Websocket/ExSocketInterface";
|
||||
import Jwt, {JsonWebTokenError} from "jsonwebtoken";
|
||||
|
||||
const SECRET_KEY = process.env.SECRET_KEY || "THECODINGMACHINE_SECRET_KEY";
|
||||
|
||||
export class IoSocketController{
|
||||
Io: socketIO.Server;
|
||||
constructor(server : http.Server) {
|
||||
this.Io = socketIO(server);
|
||||
|
||||
//authentication with token. it will be decodes and stock in socket.
|
||||
this.Io.use( (socket: Socket, next) => {
|
||||
if (!socket.handshake.query || !socket.handshake.query.token) {
|
||||
return next(new Error('Authentication error'));
|
||||
}
|
||||
Jwt.verify(socket.handshake.query.token, SECRET_KEY, (err: JsonWebTokenError, tokenDecoded: object) => {
|
||||
if (err) {
|
||||
return next(new Error('Authentication error'));
|
||||
}
|
||||
(socket as ExSocketInterface).token = tokenDecoded;
|
||||
next();
|
||||
});
|
||||
});
|
||||
|
||||
this.ioConnection();
|
||||
}
|
||||
|
||||
ioConnection() {
|
||||
this.Io.on('connection', (socket: Socket) => {
|
||||
//TODO check token access
|
||||
|
||||
/*join-rom event permit to join one room.
|
||||
message :
|
||||
userId : user identification
|
||||
|
|
5
back/src/Model/Websocket/ExSocketInterface.ts
Normal file
5
back/src/Model/Websocket/ExSocketInterface.ts
Normal file
|
@ -0,0 +1,5 @@
|
|||
import {Socket} from "socket.io";
|
||||
|
||||
export interface ExSocketInterface extends Socket {
|
||||
token: object;
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue