Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding TypeScript boilerplate code with authentication, room, and namespace examples #4674

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions examples/secured-room-namespace/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 Ahsan Aasim

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
15 changes: 15 additions & 0 deletions examples/secured-room-namespace/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<p>
<img src="socketio.png" width="120" alt="Socket IO Logo" />
</p>

<p>

[![Codacy Badge](https://app.codacy.com/project/badge/Grade/c23b48873d0e4a5eb60c198c62776921)](https://app.codacy.com/gh/ahsanaasim/boiled-socket.io/dashboard?utm_source=gh&utm_medium=referral&utm_content=&utm_campaign=Badge_grade)

</p>

## Socket.IO Secured Room & Namespace Example

This is a Socket.IO boilerplate code in TypeScript that includes an example of authentication for securing the socket server, as well as examples of room and namespace usage.

You can check out [this blog on Medium](https://medium.com/@ahsan.aasim/building-a-secured-socket-server-with-express-and-socket-io-in-typescript-eaa8eac54889) to gain a better understanding of the concept and codes used in building a secured socket server with Express and Socket.IO in TypeScript."
34 changes: 34 additions & 0 deletions examples/secured-room-namespace/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<head></head>

<body>
<script type="text/javascript" src="https://cdn.socket.io/4.6.1/socket.io.js"></script>
<script type="text/javascript">
const params = new Proxy(new URLSearchParams(window.location.search), {
get: (searchParams, prop) => searchParams.get(prop),
});
console.log(params.id)
var is = io('http://localhost:3000/sessions', {
auth: {
token: 'aa',
room: params.id,
},
});

is.on('connect', () => {
console.log('a user connected');

});

is.on('disconnect', () => {
console.log('user disconnected');
});

is.on('connect_error', (err) => {
console.log('connect_error', err.message); // prints the message associated with the error
});

is.on('connect_msg', (data) => {
console.log('connect_msg', data); // prints the message associated with the error
});
</script>
</body>
22 changes: 22 additions & 0 deletions examples/secured-room-namespace/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import express, { Express, Request, Response } from 'express';
import { createServer } from 'http';
import { Socket } from './src/socket';

const app: Express = express();

app.get('/', (req: Request, res: Response) => {
res.sendFile('index.html', { root: __dirname });
});

const httpServer = createServer(app);

const socket = new Socket(httpServer);
const space = socket.createNamespace('sessions');

socket.onConnect(space, (s) => {
const room = 'room_' + s.handshake.auth.room;
socket.joinRoom(room, s);
socket.emitToRoomInSpace('connect_msg', space, room, { test: 'test', room: s.handshake.auth.room });
});

httpServer.listen(3000);
55 changes: 55 additions & 0 deletions examples/secured-room-namespace/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
{
"name": "boiled-socket.io",
"version": "1.0.1",
"description": "",
"main": "index.ts",
"scripts": {
"start:dev": "npx nodemon",
"build": "tsc",
"prepare": "npm run build",
"preversion": "npm run lint",
"version": "npm run format && git add -A src",
"postversion": "git push && git push --tags",
"format": "prettier --config .prettierrc 'src/**/*.ts' --write",
"lint": "tslint -p tsconfig.json",
"test": "mocha --timeout 10000 -r ts-node/register src/**/*.test.ts",
"test-single": "mocha --timeout 10000 -r ts-node/register",
"coverage": "nyc -r lcov -e .ts -x \"*.test.ts\" npm run test"
},
"repository": {
"type": "git",
"url": "git+https://github.com/ahsanaasim/boiled-socket.io.git"
},
"author": "",
"license": "ISC",
"bugs": {
"url": "https://github.com/ahsanaasim/boiled-socket.io/issues"
},
"homepage": "https://github.com/ahsanaasim/boiled-socket.io#readme",
"dependencies": {
"@types/uuid": "^9.0.1",
"express": "^4.18.2",
"socket.io": "^4.6.1",
"socket.io-client": "^4.6.1",
"uuid": "^9.0.0"
},
"optionalDependencies": {
"bufferutil": "^4.0.7",
"utf-8-validate": "^5.0.10"
},
"devDependencies": {
"@types/chai": "^4.3.4",
"@types/express": "^4.17.17",
"@types/mocha": "^10.0.1",
"@types/node": "^18.15.6",
"chai": "^4.3.7",
"mocha": "^10.2.0",
"nodemon": "^2.0.22",
"nyc": "^15.1.0",
"prettier": "^2.8.7",
"ts-node": "^10.9.1",
"tslint": "^6.1.3",
"tslint-config-prettier": "^1.18.0",
"typescript": "^5.0.2"
}
}
Binary file added examples/secured-room-namespace/socketio.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
50 changes: 50 additions & 0 deletions examples/secured-room-namespace/src/socket.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { Namespace, Server, Socket as IOSocket } from 'socket.io';

export class Socket {
io: Server;

constructor(httpServer: any) {
this.io = new Server(httpServer, {
/* options */
});

this.init();
}

private init = () => {
this.io.use(async (socket, next) => {
try {
if (socket.handshake.auth.token === 'aa') {
next();
} else {
const err = new Error('unauthorized');
next(err);
}
} catch (e) {
next(new Error('unauthorized'));
}
});
};

public createNamespace = (spaceName: string): Namespace => {
return this.io.of('/' + spaceName);
};

public onConnect = (space: Namespace, cb: (socket: IOSocket) => void) => {
space.on('connection', (socket: IOSocket) => {
cb(socket);
});
};

public joinRoom = (room: string, socket: IOSocket) => {
socket.join(room);
};

public emitToRoomInSpace = (name: string, space: Namespace, room: string, data: any) => {
space.to(room).emit(name, data);
};

public emitToSpace = (name: string, space: Namespace, data: any) => {
space.emit(name, data);
};
}
19 changes: 19 additions & 0 deletions examples/secured-room-namespace/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"compilerOptions": {
"esModuleInterop": true,
"target": "es5",
"module": "commonjs",
"declaration": true,
"outDir": "./lib",
"strict": true,
"rootDir": "./src",
"baseUrl": "./"
},
"include": [
"src"
],
"exclude": [
"node_modules",
"**/__tests__/*"
]
}
6 changes: 6 additions & 0 deletions examples/secured-room-namespace/tslint.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"extends": [
"tslint:recommended",
"tslint-config-prettier"
]
}