2022-02-14 17:40:41 +01:00
|
|
|
import { Logger } from '@nestjs/common';
|
2023-01-13 03:15:45 +01:00
|
|
|
import { OnGatewayConnection, OnGatewayDisconnect, WebSocketGateway, WebSocketServer } from '@nestjs/websockets';
|
|
|
|
import { Server, Socket } from 'socket.io';
|
2023-01-24 05:13:42 +01:00
|
|
|
import { AuthService } from '@app/domain';
|
2022-11-15 03:24:25 +01:00
|
|
|
|
2022-06-19 15:16:35 +02:00
|
|
|
@WebSocketGateway({ cors: true })
|
2022-02-14 17:40:41 +01:00
|
|
|
export class CommunicationGateway implements OnGatewayConnection, OnGatewayDisconnect {
|
2023-01-13 03:15:45 +01:00
|
|
|
private logger = new Logger(CommunicationGateway.name);
|
2022-02-14 17:40:41 +01:00
|
|
|
|
2023-01-24 05:13:42 +01:00
|
|
|
constructor(private authService: AuthService) {}
|
2022-02-14 17:40:41 +01:00
|
|
|
|
2022-06-25 19:53:06 +02:00
|
|
|
@WebSocketServer() server!: Server;
|
2022-02-14 17:40:41 +01:00
|
|
|
|
|
|
|
handleDisconnect(client: Socket) {
|
|
|
|
client.leave(client.nsp.name);
|
2023-01-13 03:15:45 +01:00
|
|
|
this.logger.log(`Client ${client.id} disconnected from Websocket`);
|
2022-02-14 17:40:41 +01:00
|
|
|
}
|
|
|
|
|
2022-06-25 19:53:06 +02:00
|
|
|
async handleConnection(client: Socket) {
|
2022-06-19 15:16:35 +02:00
|
|
|
try {
|
2023-01-13 03:15:45 +01:00
|
|
|
this.logger.log(`New websocket connection: ${client.id}`);
|
2023-01-31 19:11:49 +01:00
|
|
|
const user = await this.authService.validate(client.request.headers, {});
|
2023-01-13 03:15:45 +01:00
|
|
|
if (user) {
|
|
|
|
client.join(user.id);
|
2022-08-27 07:53:37 +02:00
|
|
|
} else {
|
|
|
|
client.emit('error', 'unauthorized');
|
|
|
|
client.disconnect();
|
|
|
|
}
|
2022-06-19 15:16:35 +02:00
|
|
|
} catch (e) {
|
2023-01-27 21:50:07 +01:00
|
|
|
client.emit('error', 'unauthorized');
|
|
|
|
client.disconnect();
|
2022-06-19 15:16:35 +02:00
|
|
|
}
|
2022-02-14 17:40:41 +01:00
|
|
|
}
|
|
|
|
}
|