diff --git a/backend/src/utils/__init__.py b/backend/src/utils/__init__.py new file mode 100644 index 00000000..c8209695 --- /dev/null +++ b/backend/src/utils/__init__.py @@ -0,0 +1,9 @@ +from .password import hash_password, verify_password +from .jwt import create_access_token, decode_access_token + +__all__ = [ + "hash_password", + "verify_password", + "create_access_token", + "decode_access_token", +] diff --git a/backend/src/utils/__pycache__/__init__.cpython-310.pyc b/backend/src/utils/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 00000000..a7d5f6b8 Binary files /dev/null and b/backend/src/utils/__pycache__/__init__.cpython-310.pyc differ diff --git a/backend/src/utils/__pycache__/jwt.cpython-310.pyc b/backend/src/utils/__pycache__/jwt.cpython-310.pyc new file mode 100644 index 00000000..8317d975 Binary files /dev/null and b/backend/src/utils/__pycache__/jwt.cpython-310.pyc differ diff --git a/backend/src/utils/__pycache__/password.cpython-310.pyc b/backend/src/utils/__pycache__/password.cpython-310.pyc new file mode 100644 index 00000000..d4a3fba5 Binary files /dev/null and b/backend/src/utils/__pycache__/password.cpython-310.pyc differ diff --git a/backend/src/utils/jwt.py b/backend/src/utils/jwt.py new file mode 100644 index 00000000..6e04a66d --- /dev/null +++ b/backend/src/utils/jwt.py @@ -0,0 +1,33 @@ +from datetime import datetime, timedelta +from typing import Optional +from jose import JWTError, jwt +from config.settings import get_settings + +settings = get_settings() + + +def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str: + """创建访问令牌""" + to_encode = data.copy() + if expires_delta: + expire = datetime.utcnow() + expires_delta + else: + expire = datetime.utcnow() + timedelta( + minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES + ) + to_encode.update({"exp": expire}) + encoded_jwt = jwt.encode( + to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM + ) + return encoded_jwt + + +def decode_access_token(token: str) -> Optional[dict]: + """解码访问令牌""" + try: + payload = jwt.decode( + token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM] + ) + return payload + except JWTError: + return None diff --git a/backend/src/utils/password.py b/backend/src/utils/password.py new file mode 100644 index 00000000..0e5b77a4 --- /dev/null +++ b/backend/src/utils/password.py @@ -0,0 +1,15 @@ +import bcrypt + + +def hash_password(password: str) -> str: + """哈希密码""" + salt = bcrypt.gensalt(rounds=12) + hashed = bcrypt.hashpw(password.encode("utf-8"), salt) + return hashed.decode("utf-8") + + +def verify_password(password: str, hashed_password: str) -> bool: + """验证密码""" + return bcrypt.checkpw( + password.encode("utf-8"), hashed_password.encode("utf-8") + )