Refactor phone number validation and enhance test coverage
All checks were successful
Build and Push Docker Images / changes (push) Successful in 6s
Build and Push Docker Images / build-backend (push) Successful in 54s
Build and Push Docker Images / build-frontend (push) Has been skipped

Improved phone number validation logic with stricter rules and better error messages in `UserBase`. Updated access token expiration to 1 day in config. Added extensive tests for phone number validation, including valid and invalid cases across different formats.
This commit is contained in:
2025-03-04 17:34:15 +01:00
parent b6006d5218
commit f2851bcb7a
4 changed files with 157 additions and 6 deletions

View File

@@ -41,7 +41,7 @@ class Settings(BaseSettings):
# JWT configuration
SECRET_KEY: str = "your_secret_key_here"
ALGORITHM: str = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES: int = 30
ACCESS_TOKEN_EXPIRE_MINUTES: int = 1440 # 1 day
# CORS configuration
BACKEND_CORS_ORIGINS: List[str] = ["http://localhost:3000"]

View File

@@ -48,14 +48,38 @@ class UserUpdate(BaseModel):
preferences: Optional[Dict[str, Any]] = None
@field_validator('phone_number')
@classmethod
def validate_phone_number(cls, v: Optional[str]) -> Optional[str]:
if v is None:
return v
# Simple regex for phone validation
if not re.match(r'^\+?[0-9\s\-\(\)]{8,20}$', v):
raise ValueError('Invalid phone number format')
return v
# Return early for empty strings or whitespace-only strings
if not v or v.strip() == "":
raise ValueError('Phone number cannot be empty')
# Remove all spaces and formatting characters
cleaned = re.sub(r'[\s\-\(\)]', '', v)
# Basic pattern:
# Must start with + or 0
# After + must have at least 8 digits
# After 0 must have at least 8 digits
# Maximum total length of 15 digits (international standard)
# Only allowed characters are + at start and digits
pattern = r'^(?:\+[0-9]{8,14}|0[0-9]{8,14})$'
if not re.match(pattern, cleaned):
raise ValueError('Phone number must start with + or 0 followed by 8-14 digits')
# Additional validation to catch specific invalid cases
if cleaned.count('+') > 1:
raise ValueError('Phone number can only contain one + symbol at the start')
# Check for any non-digit characters (except the leading +)
if not all(c.isdigit() for c in cleaned[1:]):
raise ValueError('Phone number can only contain digits after the prefix')
return cleaned
class UserInDB(UserBase):