Improve username validation
This commit is contained in:
parent
82e24ad8b0
commit
0993a3b38c
1 changed files with 22 additions and 2 deletions
|
@ -1,10 +1,20 @@
|
||||||
|
use regex::Regex;
|
||||||
use crate::errors::ValidationError;
|
use crate::errors::ValidationError;
|
||||||
use crate::utils::html::{clean_html, clean_html_strict};
|
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> {
|
pub fn validate_username(username: &str) -> Result<(), ValidationError> {
|
||||||
|
if username.is_empty() {
|
||||||
|
return Err(ValidationError("username is empty"));
|
||||||
|
};
|
||||||
if username.len() > 100 {
|
if username.len() > 100 {
|
||||||
return Err(ValidationError("username is too long"));
|
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(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -41,8 +51,18 @@ mod tests {
|
||||||
fn test_validate_username() {
|
fn test_validate_username() {
|
||||||
let result_1 = validate_username("test");
|
let result_1 = validate_username("test");
|
||||||
assert!(result_1.is_ok());
|
assert!(result_1.is_ok());
|
||||||
let result_2 = validate_username(&"x".repeat(101));
|
let result_2 = validate_username("test_12-3.xyz");
|
||||||
assert!(result_2.is_err());
|
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]
|
#[test]
|
||||||
|
|
Loading…
Reference in a new issue