From b7bfda95e9dba62586e3ec2fc31abd776a0275ad Mon Sep 17 00:00:00 2001 From: rasul Date: Tue, 7 Apr 2020 16:52:37 -0500 Subject: [PATCH] methods to check if a name or password are valid --- src/game/check_player.rs | 67 ++++++++++++++++++++++++++++++++++++++++ src/game/mod.rs | 2 ++ 2 files changed, 69 insertions(+) create mode 100644 src/game/check_player.rs diff --git a/src/game/check_player.rs b/src/game/check_player.rs new file mode 100644 index 0000000..b02ed45 --- /dev/null +++ b/src/game/check_player.rs @@ -0,0 +1,67 @@ +use lazy_static::lazy_static; + +use crate::game::Game; + +lazy_static! { + static ref NAME_CHARS: Vec = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".chars().collect(); + static ref PASS_CHARS: Vec = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 `~@#$%^&*()_+-=[]{};':\",./<>?" + .chars().collect(); +} + +pub enum PlayerCheck { + Ok(String), + Err(Vec), +} + +impl Game { + pub fn check_player_name>(name: S) -> PlayerCheck { + let name = name.into(); + let name = name.trim(); + let mut err_vec = Vec::::new(); + + if name.len() < 2 { + err_vec.push("2 character minimum".into()); + } else if name.len() > 20 { + err_vec.push("20 character maximum.".into()); + } + + for c in name.chars() { + if !NAME_CHARS.contains(&c) { + err_vec.push("English alphabetic characters only.".into()); + break; + } + } + + if !err_vec.is_empty() { + PlayerCheck::Err(err_vec) + } else { + PlayerCheck::Ok(name.into()) + } + } + + pub fn check_player_password>(password: S) -> PlayerCheck { + let password = password.into(); + let mut err_vec = Vec::::new(); + + if password.len() < 8 { + err_vec.push("8 character minimum.".into()); + } else if password.len() > 128 { + err_vec.push("128 character maximum.".into()); + } + + for c in password.chars() { + if !PASS_CHARS.contains(&c) { + err_vec.push("English alphanumeric characters or symbols only.".into()); + break; + } + } + + if err_vec.is_empty() { + PlayerCheck::Ok(password.into()) + } else { + PlayerCheck::Err(err_vec) + } + } +} diff --git a/src/game/mod.rs b/src/game/mod.rs index a1f3f3a..2d5902c 100644 --- a/src/game/mod.rs +++ b/src/game/mod.rs @@ -1,3 +1,4 @@ +mod check_player; #[allow(clippy::module_inception)] mod game; mod handle_events; @@ -6,4 +7,5 @@ mod new; mod process_recv_message; mod state; +pub use check_player::*; pub use game::Game;