From 6f8fac89aab1c98770fca0daa68ddaacbfa162dd Mon Sep 17 00:00:00 2001 From: Hamcha Date: Fri, 6 Sep 2019 14:23:12 +0200 Subject: [PATCH] Add password management and tests --- src/network/Client.ts | 11 ++++++++++- src/tests/unit/network.spec.ts | 26 ++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/src/network/Client.ts b/src/network/Client.ts index e7c96ec..2ac333a 100644 --- a/src/network/Client.ts +++ b/src/network/Client.ts @@ -1,4 +1,4 @@ -import { PeerMetadata, NetworkMessage } from "./types"; +import { PeerMetadata, NetworkMessage, PasswordResponse } from "./types"; import EventEmitter from "eventemitter3"; export abstract class Client extends EventEmitter { @@ -48,12 +48,21 @@ export abstract class Client extends EventEmitter { break; } this.players.splice(idx, 1); + case "password-req": + this.emit("password-required"); default: // For most cases, we can just use the kind as event type this.emit(data.kind, data); } } + public password(password: string) { + this.send({ + kind: "password-resp", + password + }); + } + public get name(): string { return this.metadata.name; } diff --git a/src/tests/unit/network.spec.ts b/src/tests/unit/network.spec.ts index 4fbc8d1..3a5a8a5 100644 --- a/src/tests/unit/network.spec.ts +++ b/src/tests/unit/network.spec.ts @@ -58,6 +58,32 @@ describe("network/PeerServer", () => { client.connect("test-server"); await hook.expect("local-joined", 1000); }); + + test("Server enforces password protection", async () => { + const mox = new MockHelper(); + const hook = new EventHook(); + const room = sampleRoom(); + const roomPassword = "test-pwd"; + room.password = roomPassword; + const server = mox.createServer(room, "test-server"); + + // This client will try the right password + const client1 = mox.createClient(); + hook.hookEmitter(client1, "data", "client1-data"); + client1.connect("test-server"); + await hook.expect("client1-data", 1000, messageKind("password-req")); + client1.password(roomPassword); + await hook.expect("client1-data", 1000, messageKind("room-info")); + await hook.expect("client1-data", 1000, messageKind("player-joined")); + + // This client will try an incorrect password + const client2 = mox.createClient("test-client2", "another-client"); + hook.hookEmitter(client2, "data", "client2-data"); + client2.connect("test-server"); + await hook.expect("client2-data", 1000, messageKind("password-req")); + client2.password("not the right password"); + await hook.expect("client2-data", 1000, messageKind("error")); + }); }); describe("network/PeerClient", () => {