From 150c35628386a3ee1c88064e56ca0d28bab222a5 Mon Sep 17 00:00:00 2001 From: Sebastian Lohff Date: Thu, 30 Dec 2021 23:57:03 +0100 Subject: [PATCH] Duplicate nick check --- src/main.rs | 28 +++++++++++++++++++--------- 1 file changed, 19 insertions(+), 9 deletions(-) diff --git a/src/main.rs b/src/main.rs index 93bedd0..fe19d2f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -80,6 +80,9 @@ impl ChatServer { Ok(()) } + pub fn is_nick_in_use(&self, name: &str) -> bool { + self.user_map.values().any(|client| { client.name == name }) + } } #[derive(Debug)] @@ -108,16 +111,23 @@ fn handle_client(mut stream: TcpStream, server: Arc>, client_i // greet and recv nick write!(writer, "Hello and welcome to RustChat!\nNick: ")?; - let nick = lines.next().ok_or(ChatError::Protocol(String::from("Could not recv nickname")))??; - // FIXME: check for nick name uniqueness + let mut nick; + loop { + nick = lines.next().ok_or(ChatError::Protocol(String::from("Could not recv nickname")))??; + // check for nick name uniqueness + let mut srv = server.lock()?; + if ! srv.is_nick_in_use(&nick) { + // print joined msg and register at server + srv.send_to_all(&format!("* {} has joined the chat", nick))?; + let curr_users = srv.get_user_count(); + let users_in_room_msg = if curr_users == 1 { String::from("is 1 user") } else { format!("are {} users", curr_users) }; + write!(writer, " *** {}\n *** You are known as {}. There {} in the room.\n", srv.config.greeting_msg, nick, users_in_room_msg)?; + *client_id = Some(srv.register(nick.clone(), writer)); - // print joined msg and register at server - server.lock()?.send_to_all(&format!("* {} has joined the chat", nick))?; - let curr_users = server.lock()?.get_user_count(); - let users_in_room_msg = if curr_users == 1 { String::from("is 1 user") } else { format!("are {} users", curr_users) }; - write!(writer, "Welcome, {}! You can now start to chat! There {} in the room.\n", nick, users_in_room_msg)?; - // server.lock()?.borrow_mut().push(ChatUser::new(nick.clone(), writer)); - *client_id = Some(server.lock()?.register(nick.clone(), writer)); + break; + } + write!(writer, "This nickname is already in use, please choose another.\nNick: ")?; + } // read lines for line in lines {