42 lines
1.3 KiB
Python
42 lines
1.3 KiB
Python
"""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
|