fix(task4): enforce unified password validation rule
This commit is contained in:
@@ -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,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."}
|
||||
|
||||
@@ -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."}
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user