From 0993a3b38c702e3737b797cd239031e116bec84b Mon Sep 17 00:00:00 2001 From: silverpill Date: Thu, 17 Feb 2022 20:15:30 +0000 Subject: [PATCH] Improve username validation --- src/models/profiles/validators.rs | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/src/models/profiles/validators.rs b/src/models/profiles/validators.rs index 772fa0e..5ff36f6 100644 --- a/src/models/profiles/validators.rs +++ b/src/models/profiles/validators.rs @@ -1,10 +1,20 @@ +use regex::Regex; use crate::errors::ValidationError; use crate::utils::html::{clean_html, clean_html_strict}; +const USERNAME_RE: &str = r"^[a-zA-Z0-9_\.-]+$"; + pub fn validate_username(username: &str) -> Result<(), ValidationError> { + if username.is_empty() { + return Err(ValidationError("username is empty")); + }; if username.len() > 100 { return Err(ValidationError("username is too long")); }; + let username_regexp = Regex::new(USERNAME_RE).unwrap(); + if !username_regexp.is_match(username) { + return Err(ValidationError("invalid username")); + }; Ok(()) } @@ -41,8 +51,18 @@ mod tests { fn test_validate_username() { let result_1 = validate_username("test"); assert!(result_1.is_ok()); - let result_2 = validate_username(&"x".repeat(101)); - assert!(result_2.is_err()); + let result_2 = validate_username("test_12-3.xyz"); + assert!(result_2.is_ok()); + } + + #[test] + fn test_validate_username_error() { + let error = validate_username(&"x".repeat(101)).unwrap_err(); + assert_eq!(error.to_string(), "username is too long"); + let error = validate_username("").unwrap_err(); + assert_eq!(error.to_string(), "username is empty"); + let error = validate_username("abc&").unwrap_err(); + assert_eq!(error.to_string(), "invalid username"); } #[test]