32 lines
1019 B
Python
32 lines
1019 B
Python
import bcrypt
|
|
from fastapi import HTTPException, status
|
|
|
|
PASSWORD_RULE = "密码至少 8 位,且同时包含字母和数字"
|
|
|
|
|
|
def validate_password(password: str) -> None:
|
|
if (
|
|
not isinstance(password, str)
|
|
or len(password) < 8
|
|
or not any(char.isalpha() for char in password)
|
|
or not any(char.isdigit() for char in password)
|
|
):
|
|
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=PASSWORD_RULE)
|
|
|
|
|
|
def hash_password(password: str) -> str:
|
|
try:
|
|
hashed = bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt())
|
|
except ValueError:
|
|
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="密码过长")
|
|
return hashed.decode("utf-8")
|
|
|
|
|
|
def verify_password(password: str, password_hash: str) -> bool:
|
|
if not password or not password_hash:
|
|
return False
|
|
try:
|
|
return bcrypt.checkpw(password.encode("utf-8"), password_hash.encode("utf-8"))
|
|
except (ValueError, TypeError):
|
|
return False
|