dy-dashboard/services/passwords.py
2026-10-28 11:14:17 +08:00

42 lines
1.3 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""Password hashing and policy helpers for dashboard accounts."""
import re
from werkzeug.security import check_password_hash, generate_password_hash
PASSWORD_POLICY_MESSAGE = "密码至少10位,且必须包含字母、数字和特殊字符"
def validate_password(password):
"""Validate the platform password policy."""
value = str(password or "")
if len(value) < 10:
return False, PASSWORD_POLICY_MESSAGE
if not re.search(r"[A-Za-z]", value):
return False, PASSWORD_POLICY_MESSAGE
if not re.search(r"[0-9]", value):
return False, PASSWORD_POLICY_MESSAGE
if not re.search(r"[^A-Za-z0-9]", value):
return False, PASSWORD_POLICY_MESSAGE
return True, ""
def hash_password(password):
"""Create a salted, one-way scrypt hash."""
return generate_password_hash(str(password), method="scrypt")
def is_password_hash(value):
"""Return whether the stored value uses a supported Werkzeug hash."""
return isinstance(value, str) and value.startswith(("scrypt:", "pbkdf2:"))
def verify_password(stored_hash, password):
"""Verify a password without supporting legacy plaintext values."""
if not is_password_hash(stored_hash):
return False
try:
return check_password_hash(stored_hash, str(password))
except (TypeError, ValueError):
return False