fix(task4): enforce unified password validation rule

This commit is contained in:
Atharv1705
2026-11-17 17:58:20 +05:30
parent c086833163
commit 5f649e3e4c
8 changed files with 264 additions and 29 deletions
+68
View File
@@ -1,9 +1,77 @@
from datetime import timedelta
import bcrypt
from fastapi import HTTPException, status
from jose import JWTError, jwt
from .config import settings
from .time_utils import utc_now
BLOCKLIST_PASSWORDS = {
"123456",
"12345678",
"password",
"password1",
"qwerty123",
"admin123",
"welcome1",
}
def validate_password(password: str, email: str | None = None) -> None:
"""Validate password rules:
- Length: at least 8, at most 128 characters.
- Characters: at least one letter and at least one digit. (Special characters allowed, not required. Case insensitive.)
- Must NOT start or end with a space (reject with a clear message, do not silently strip).
- Blocklist (case-insensitive): '123456', '12345678', 'password', 'password1', 'qwerty123', 'admin123', 'welcome1'.
(NOTE: demo password 'demo@123' must remain allowed)
- Must not contain the user's username/email local-part if length >= 4 (case-insensitive).
"""
if not isinstance(password, str):
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="Password must be a string.",
)
if password.startswith(" ") or password.endswith(" "):
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="Password must not start or end with a space.",
)
if len(password) < 8:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="Password must be at least 8 characters long.",
)
if len(password) > 128:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="Password must be at most 128 characters long.",
)
has_letter = any(c.isalpha() for c in password)
has_digit = any(c.isdigit() for c in password)
if not has_letter or not has_digit:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="Password must contain at least one letter and at least one digit.",
)
lower_pass = password.lower()
if lower_pass in BLOCKLIST_PASSWORDS:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="Password is too common or easily guessable.",
)
if email:
local_part = email.split("@")[0].strip().lower()
if len(local_part) >= 4 and local_part in lower_pass:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="Password must not contain your email username.",
)
def verify_password(plain: str, hashed: str) -> bool:
if not plain or not hashed: