hxf/backend/th_agenter/services/auth.py

141 lines
5.0 KiB
Python
Raw Normal View History

2025-12-04 14:48:38 +08:00
"""Authentication service."""
from typing import Optional
2025-12-17 19:26:36 +08:00
from datetime import datetime, timedelta
2025-12-04 14:48:38 +08:00
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from sqlalchemy.orm import Session
2025-12-16 13:55:16 +08:00
import jwt
2025-12-17 19:26:36 +08:00
import bcrypt
2025-12-04 14:48:38 +08:00
from ..core.config import settings
2025-12-17 19:26:36 +08:00
from ..db.database import get_db
2025-12-04 14:48:38 +08:00
from ..models.user import User
2025-12-17 19:26:36 +08:00
2025-12-04 14:48:38 +08:00
security = HTTPBearer()
2025-12-17 19:26:36 +08:00
2025-12-04 14:48:38 +08:00
class AuthService:
"""Authentication service."""
2025-12-17 19:26:36 +08:00
@staticmethod
def verify_password(plain_password: str, hashed_password: str) -> bool:
"""Verify a password against its hash."""
# Bcrypt has a maximum password length of 72 bytes
plain_password = plain_password[:72]
return bcrypt.checkpw(plain_password.encode('utf-8'), hashed_password.encode('utf-8'))
@staticmethod
def get_password_hash(password: str) -> str:
"""Generate password hash."""
# Bcrypt has a maximum password length of 72 bytes
password = password[:72]
salt = bcrypt.gensalt()
hashed = bcrypt.hashpw(password.encode('utf-8'), salt)
return hashed.decode('utf-8')
@staticmethod
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str:
"""Create JWT access token."""
to_encode = data.copy()
if expires_delta:
expire = datetime.utcnow() + expires_delta
else:
expire = datetime.utcnow() + timedelta(minutes=settings.security.access_token_expire_minutes)
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(
to_encode,
settings.security.secret_key,
algorithm=settings.security.algorithm
)
return encoded_jwt
2025-12-04 14:48:38 +08:00
@staticmethod
2025-12-17 19:26:36 +08:00
def verify_token(token: str) -> Optional[dict]:
"""Verify JWT token."""
try:
payload = jwt.decode(
token,
settings.security.secret_key,
algorithms=[settings.security.algorithm]
)
return payload
except jwt.PyJWTError as e:
import logging
logging.error(f"Token verification failed: {e}")
logging.error(f"Token: {token[:50]}...")
logging.error(f"Secret key: {settings.security.secret_key[:20]}...")
logging.error(f"Algorithm: {settings.security.algorithm}")
return None
@staticmethod
def authenticate_user(db: Session, username: str, password: str) -> Optional[User]:
"""Authenticate user with username and password."""
user = db.query(User).filter(User.username == username).first()
if not user:
return None
if not AuthService.verify_password(password, user.hashed_password):
return None
return user
@staticmethod
def authenticate_user_by_email(db: Session, email: str, password: str) -> Optional[User]:
"""Authenticate user with email and password."""
user = db.query(User).filter(User.email == email).first()
if not user:
return None
if not AuthService.verify_password(password, user.hashed_password):
return None
return user
@staticmethod
def get_current_user(
2025-12-04 14:48:38 +08:00
credentials: HTTPAuthorizationCredentials = Depends(security),
2025-12-17 19:26:36 +08:00
db: Session = Depends(get_db)
2025-12-04 14:48:38 +08:00
) -> User:
"""Get current authenticated user."""
2025-12-17 19:26:36 +08:00
import logging
2025-12-04 14:48:38 +08:00
from ..core.context import UserContext
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
token = credentials.credentials
2025-12-17 19:26:36 +08:00
logging.info(f"Received token: {token[:50]}...")
2025-12-04 14:48:38 +08:00
payload = AuthService.verify_token(token)
if payload is None:
2025-12-17 19:26:36 +08:00
logging.error("Token verification failed")
2025-12-04 14:48:38 +08:00
raise credentials_exception
2025-12-17 19:26:36 +08:00
logging.info(f"Token payload: {payload}")
2025-12-04 14:48:38 +08:00
username: str = payload.get("sub")
if username is None:
2025-12-17 19:26:36 +08:00
logging.error("No username in token payload")
2025-12-04 14:48:38 +08:00
raise credentials_exception
2025-12-17 19:26:36 +08:00
logging.info(f"Looking for user with username: {username}")
user = db.query(User).filter(User.username == username).first()
2025-12-04 14:48:38 +08:00
if user is None:
2025-12-17 19:26:36 +08:00
logging.error(f"User not found with username: {username}")
2025-12-04 14:48:38 +08:00
raise credentials_exception
# Set user in context for global access
UserContext.set_current_user(user)
2025-12-17 19:26:36 +08:00
logging.info(f"User {user.username} (ID: {user.id}) set in UserContext")
2025-12-04 14:48:38 +08:00
return user
2025-12-17 19:26:36 +08:00
2025-12-04 14:48:38 +08:00
@staticmethod
def get_current_active_user(current_user: User = Depends(get_current_user)) -> User:
"""Get current active user."""
if not current_user.is_active:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Inactive user"
)
2025-12-17 19:26:36 +08:00
return current_user