Jul 2nd - Optimized code 2
This commit is contained in:
@@ -13,7 +13,7 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
# ─── Password Validation ──────────────────────────────────────────────────────
|
||||
|
||||
def validate_password(password: str, confirm: str) -> str | None:
|
||||
def validate_password(password: str, confirm: str, current_hash: str | None = None) -> str | None:
|
||||
"""Validate a new password and its confirmation field.
|
||||
|
||||
Returns an error message string if validation fails, or None if the
|
||||
@@ -27,11 +27,17 @@ def validate_password(password: str, confirm: str) -> str | None:
|
||||
- Must contain at least one uppercase letter (A-Z).
|
||||
- Must contain at least one digit (0-9).
|
||||
- Must contain at least one special character (!@#$%^&* etc.).
|
||||
- If current_hash is given, the new password must differ from it.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
password : str – the candidate password (plain text)
|
||||
confirm : str – the confirmation field value
|
||||
password : str – the candidate password (plain text)
|
||||
confirm : str – the confirmation field value
|
||||
current_hash : str|None – the user's existing password_hash, if this is
|
||||
a password *change* (profile, admin edit,
|
||||
reset) rather than new-account creation.
|
||||
When given, re-using the current password is
|
||||
rejected.
|
||||
"""
|
||||
import re
|
||||
if password != confirm:
|
||||
@@ -48,6 +54,12 @@ def validate_password(password: str, confirm: str) -> str | None:
|
||||
return 'Password must contain at least one number.'
|
||||
if not re.search(r'[!@#$%^&*()\-_=+\[\]{};:\'",.<>?/\\|`~]', password):
|
||||
return 'Password must contain at least one special character.'
|
||||
# Hash comparison is the most expensive check, so it runs last —
|
||||
# only after every cheap format check has already passed.
|
||||
if current_hash:
|
||||
from werkzeug.security import check_password_hash
|
||||
if check_password_hash(current_hash, password):
|
||||
return 'New password must be different from your current password.'
|
||||
return None
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user