From 2ed732fe7bb9c803aed56e9a3d6610bd3bf72a6c Mon Sep 17 00:00:00 2001 From: Hamcha Date: Wed, 4 Sep 2019 15:04:48 +0200 Subject: [PATCH] Add password check and error messages --- src/network/server.ts | 31 ++++++++++++++++++++++++++++++- src/network/types.ts | 7 ++++++- 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/src/network/server.ts b/src/network/server.ts index 4f2709e..0bb1886 100644 --- a/src/network/server.ts +++ b/src/network/server.ts @@ -1,6 +1,12 @@ import NetworkPeer from "./peer"; import { DataConnection } from "peerjs"; -import { RoomInfo, PasswordRequest, Room } from "./types"; +import { + RoomInfo, + PasswordRequest, + Room, + ErrorMessage, + PasswordResponse +} from "./types"; export default class PeerServer extends NetworkPeer { private room: Room; @@ -19,15 +25,38 @@ export default class PeerServer extends NetworkPeer { // Check if room is full if (this.playerCount >= this.room.info.max_players) { //TODO Reject + this.send(conn, { kind: "error", error: "room is full" }); + conn.close(); + return; } if (this.room.info.password != "") { this.send(conn, { kind: "password-req" }); + conn.on("data", this.checkPasswordResponse.bind(this, conn)); } else { //TODO Add player } } + private checkPasswordResponse(conn: DataConnection, data: any) { + try { + let resp = data as PasswordResponse; + if (resp.password != this.room.info.password) { + this.send(conn, { + kind: "error", + error: "invalid password" + }); + return; + } + //TODO Add player + } catch (e) { + this.send(conn, { + kind: "error", + error: "not a password" + }); + } + } + private get playerCount(): number { return Object.keys(this.room.players).length; } diff --git a/src/network/types.ts b/src/network/types.ts index 7ee6881..414656d 100644 --- a/src/network/types.ts +++ b/src/network/types.ts @@ -46,7 +46,7 @@ type DraftInfo = { // Message schemas -export type NetworkMessage = PasswordRequest | PasswordResponse; +export type NetworkMessage = PasswordRequest | PasswordResponse | ErrorMessage; export interface PasswordRequest { kind: "password-req"; @@ -56,3 +56,8 @@ export interface PasswordResponse { kind: "password-resp"; password: string; } + +export interface ErrorMessage { + kind: "error"; + error: string; +}