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:
+6 -6
View File
@@ -6,7 +6,7 @@ from sqlalchemy.orm import Session, joinedload
from ..core.db import get_db
from ..core.deps import get_current_user
from ..core.exceptions import CodedHTTPException
from ..core.security import create_access_token, hash_password, verify_password
from ..core.security import create_access_token, hash_password, validate_password, verify_password
from ..models.masters import User
from ..schemas.auth import LoginRequest, TokenResponse, UserOut
from ..services.settings_service import get_demo_as_of_date
@@ -17,7 +17,7 @@ router = APIRouter(prefix="/auth", tags=["auth"])
class ChangePasswordRequest(BaseModel):
current_password: str
new_password: str = Field(..., min_length=6)
new_password: str = Field(..., max_length=128)
MAX_LOGIN_ATTEMPTS = 15
LOGIN_WINDOW_SECONDS = 60.0
@@ -110,12 +110,12 @@ def change_password(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Current password is incorrect.",
)
new_pass = payload.new_password.strip()
if len(new_pass) < 6:
if payload.new_password == payload.current_password:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="New password must be at least 6 characters.",
detail="New password must be different.",
)
current_user.password_hash = hash_password(new_pass)
validate_password(payload.new_password, email=current_user.email)
current_user.password_hash = hash_password(payload.new_password)
db.commit()
return {"message": "Password changed successfully."}
+8 -15
View File
@@ -6,7 +6,7 @@ from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session, joinedload
from ..core.db import get_db
from ..core.deps import get_current_user, require_roles
from ..core.security import hash_password
from ..core.security import hash_password, validate_password
from ..models.masters import Department, User
from ..schemas.masters import (
PaginatedOut,
@@ -21,7 +21,7 @@ router = APIRouter(prefix="/users", tags=["users"])
class ResetPasswordRequest(BaseModel):
new_password: str = Field(..., min_length=6)
new_password: str = Field(..., max_length=128)
def _user_list_out(user: User) -> UserListOut:
@@ -93,6 +93,8 @@ def create_user(
if dept is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Department not found.")
validate_password(payload.password, email=payload.email)
user = User(
name=payload.name.strip(),
email=payload.email.strip().lower(),
@@ -175,12 +177,8 @@ def update_user(
data["email"] = data["email"].strip().lower()
password = data.pop("password", None)
if password is not None and password.strip():
if len(password) < 4:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="Password must be at least 4 characters.",
)
if password is not None and password != "":
validate_password(password, email=data.get("email", user.email))
user.password_hash = hash_password(password)
for k, v in data.items():
@@ -243,12 +241,7 @@ def reset_user_password(
user = db.query(User).filter(User.id == user_id).first()
if user is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found.")
new_pass = payload.new_password.strip()
if len(new_pass) < 6:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="Password must be at least 6 characters.",
)
user.password_hash = hash_password(new_pass)
validate_password(payload.new_password, email=user.email)
user.password_hash = hash_password(payload.new_password)
db.commit()
return {"message": f"Password for {user.name} has been reset successfully."}
+1 -1
View File
@@ -123,7 +123,7 @@ class VendorOut(BaseModel):
class UserCreate(BaseModel):
name: str = Field(..., min_length=1, max_length=150)
email: str = Field(..., min_length=3, max_length=200)
password: str = Field(..., min_length=4, max_length=128)
password: str = Field(..., max_length=128)
role: UserRole
department_id: Optional[int] = None
is_active: bool = True
+165
View File
@@ -0,0 +1,165 @@
import pytest
from fastapi.testclient import TestClient
from app.core.security import validate_password
from app.models.masters import User
from app.seed.seed import seed_database
@pytest.fixture(scope="module", autouse=True)
def seeded_task4_db(db, tmp_path_factory):
upload_dir = tmp_path_factory.mktemp("task4_test_uploads")
seed_database(db, upload_dir=upload_dir)
return upload_dir
def _auth_headers(client, email: str = "admin@poona.demo") -> dict[str, str]:
res = client.post("/api/auth/login", json={"email": email, "password": "Demo@123"})
assert res.status_code == 200, res.text
return {"Authorization": f"Bearer {res.json()['access_token']}"}
def test_validate_password_unit():
# 1. Short password (< 8)
with pytest.raises(Exception) as exc1:
validate_password("Short1", email="user@hospital.com")
assert "at least 8 characters" in str(exc1.value)
# 2. No digits
with pytest.raises(Exception) as exc2:
validate_password("NoDigitsHere", email="user@hospital.com")
assert "at least one letter and at least one digit" in str(exc2.value)
# 3. No letters
with pytest.raises(Exception) as exc3:
validate_password("1234567890", email="user@hospital.com")
assert "at least one letter and at least one digit" in str(exc3.value)
# 4. Leading / trailing space
with pytest.raises(Exception) as exc4a:
validate_password(" Secret123", email="user@hospital.com")
assert "space" in str(exc4a.value)
with pytest.raises(Exception) as exc4b:
validate_password("Secret123 ", email="user@hospital.com")
assert "space" in str(exc4b.value)
# 5. Blocklisted passwords
for bad in ("12345678", "password", "password1", "qwerty123", "admin123", "welcome1"):
with pytest.raises(Exception) as exc5:
validate_password(bad, email="user@hospital.com")
assert "easily guessable" in str(exc5.value) or "at least 8" in str(exc5.value) or "at least one" in str(exc5.value)
# 6. Demo password MUST be allowed
validate_password("demo@123", email="admin@poona.demo")
validate_password("Demo@123", email="admin@poona.demo")
# 7. Contains email local part (>= 4 chars)
with pytest.raises(Exception) as exc7:
validate_password("Secureadmin123", email="admin@poona.demo")
assert "username" in str(exc7.value).lower()
# Short local part (< 4 chars) does NOT trigger username check
validate_password("Securebio123", email="bio@poona.demo")
def test_api_create_user_password_validation(client, db):
headers = _auth_headers(client, "admin@poona.demo")
# Rejected: no digit
res_bad = client.post(
"/api/users",
headers=headers,
json={
"name": "Test User",
"email": "test_pw_rule@poona.demo",
"password": "NoDigitsPassword",
"role": "biomedical",
},
)
assert res_bad.status_code == 422
assert "letter and at least one digit" in res_bad.json()["detail"]
# Rejected: contains email username "tester123"
res_username = client.post(
"/api/users",
headers=headers,
json={
"name": "Test User 2",
"email": "tester123@poona.demo",
"password": "tester123Password1",
"role": "biomedical",
},
)
assert res_username.status_code == 422
assert "username" in res_username.json()["detail"].lower()
# Accepted: valid password with letters and numbers
res_ok = client.post(
"/api/users",
headers=headers,
json={
"name": "Test User 3",
"email": "validuser@poona.demo",
"password": "ValidPassword123",
"role": "biomedical",
},
)
assert res_ok.status_code == 201
user_id = res_ok.json()["id"]
# Reset password with leading space rejected
res_reset_bad = client.post(
f"/api/users/{user_id}/reset-password",
headers=headers,
json={"new_password": " LeadingSpace123"},
)
assert res_reset_bad.status_code == 422
assert "space" in res_reset_bad.json()["detail"]
# Reset password with valid password succeeds
res_reset_ok = client.post(
f"/api/users/{user_id}/reset-password",
headers=headers,
json={"new_password": "NewValidSecret456"},
)
assert res_reset_ok.status_code == 200
def test_api_change_password_validation(client, db):
# Log in as bio user
bio_headers = _auth_headers(client, "bio@poona.demo")
# Reject new == current
res_same = client.post(
"/api/auth/change-password",
headers=bio_headers,
json={"current_password": "Demo@123", "new_password": "Demo@123"},
)
assert res_same.status_code == 422
assert res_same.json()["detail"] == "New password must be different."
# Reject trailing space
res_space = client.post(
"/api/auth/change-password",
headers=bio_headers,
json={"current_password": "Demo@123", "new_password": "NewSecretPass1 "},
)
assert res_space.status_code == 422
assert "space" in res_space.json()["detail"]
# Reject blocklisted password
res_block = client.post(
"/api/auth/change-password",
headers=bio_headers,
json={"current_password": "Demo@123", "new_password": "password1"},
)
assert res_block.status_code == 422
# Accept valid change
res_ok = client.post(
"/api/auth/change-password",
headers=bio_headers,
json={"current_password": "Demo@123", "new_password": "BrandNewSecret789"},
)
assert res_ok.status_code == 200
assert res_ok.json()["message"] == "Password changed successfully."