Add password check and error messages

This commit is contained in:
Hamcha 2019-09-04 15:04:48 +02:00
parent f0b8e98327
commit 2ed732fe7b
Signed by: hamcha
GPG key ID: 44AD3571EB09A39E
2 changed files with 36 additions and 2 deletions

View file

@ -1,6 +1,12 @@
import NetworkPeer from "./peer"; import NetworkPeer from "./peer";
import { DataConnection } from "peerjs"; import { DataConnection } from "peerjs";
import { RoomInfo, PasswordRequest, Room } from "./types"; import {
RoomInfo,
PasswordRequest,
Room,
ErrorMessage,
PasswordResponse
} from "./types";
export default class PeerServer extends NetworkPeer { export default class PeerServer extends NetworkPeer {
private room: Room; private room: Room;
@ -19,15 +25,38 @@ export default class PeerServer extends NetworkPeer {
// Check if room is full // Check if room is full
if (this.playerCount >= this.room.info.max_players) { if (this.playerCount >= this.room.info.max_players) {
//TODO Reject //TODO Reject
this.send<ErrorMessage>(conn, { kind: "error", error: "room is full" });
conn.close();
return;
} }
if (this.room.info.password != "") { if (this.room.info.password != "") {
this.send<PasswordRequest>(conn, { kind: "password-req" }); this.send<PasswordRequest>(conn, { kind: "password-req" });
conn.on("data", this.checkPasswordResponse.bind(this, conn));
} else { } else {
//TODO Add player //TODO Add player
} }
} }
private checkPasswordResponse(conn: DataConnection, data: any) {
try {
let resp = data as PasswordResponse;
if (resp.password != this.room.info.password) {
this.send<ErrorMessage>(conn, {
kind: "error",
error: "invalid password"
});
return;
}
//TODO Add player
} catch (e) {
this.send<ErrorMessage>(conn, {
kind: "error",
error: "not a password"
});
}
}
private get playerCount(): number { private get playerCount(): number {
return Object.keys(this.room.players).length; return Object.keys(this.room.players).length;
} }

View file

@ -46,7 +46,7 @@ type DraftInfo = {
// Message schemas // Message schemas
export type NetworkMessage = PasswordRequest | PasswordResponse; export type NetworkMessage = PasswordRequest | PasswordResponse | ErrorMessage;
export interface PasswordRequest { export interface PasswordRequest {
kind: "password-req"; kind: "password-req";
@ -56,3 +56,8 @@ export interface PasswordResponse {
kind: "password-resp"; kind: "password-resp";
password: string; password: string;
} }
export interface ErrorMessage {
kind: "error";
error: string;
}