import bcrypt from fastapi import HTTPException, status PASSWORD_RULE = "密码至少 8 位,且同时包含字母和数字" MEMBER_PASSWORD_LIMIT = 10 DEFAULT_MEMBER_PASSWORD = "123456" MEMBER_PASSWORD_RULE = "密码为 1 至 10 位,内容不限" def validate_member_password(password: str) -> None: text = password.strip() if isinstance(password, str) else "" if not text or len(text) > MEMBER_PASSWORD_LIMIT: raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=MEMBER_PASSWORD_RULE) 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