feat: add JWT and password security module

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Claude
2026-03-24 14:56:15 +08:00
parent d65f8b2c39
commit 7dbf9cf22c
2 changed files with 51 additions and 1 deletions
+32 -1
View File
@@ -1 +1,32 @@
"""Security utilities placeholder.""" from datetime import datetime, timedelta
from typing import Optional, Any
from types import SimpleNamespace
from jose import JWTError, jwt
from passlib.context import CryptContext
from app.config import settings
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
def hash_password(password: str) -> str:
return pwd_context.hash(password)
def verify_password(plain_password: str, hashed_password: str) -> bool:
return pwd_context.verify(plain_password, hashed_password)
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[SimpleNamespace]:
try:
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
return SimpleNamespace(**payload)
except JWTError:
return None
@@ -0,0 +1,19 @@
import pytest
from app.core.security import verify_password, hash_password, create_access_token, decode_access_token
def test_password_hash_and_verify():
password = "testpassword123"
hashed = hash_password(password)
assert hashed != password
assert verify_password(password, hashed) is True
assert verify_password("wrongpassword", hashed) is False
def test_access_token_creation_and_decode():
token = create_access_token({"sub": "testuser"})
assert token is not None
payload = decode_access_token(token)
assert payload is not None
assert payload.sub == "testuser"