61 lines
1.8 KiB
Python
61 lines
1.8 KiB
Python
# app/api/deps.py
|
|
"""Summary description ....
|
|
|
|
This module provides classes and functions for:
|
|
- ....
|
|
- ....
|
|
- ....
|
|
"""
|
|
|
|
from fastapi import Depends
|
|
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.core.database import get_db
|
|
from middleware.auth import AuthManager
|
|
from middleware.rate_limiter import RateLimiter
|
|
from models.database.shop import Shop
|
|
from models.database.user import User
|
|
from app.exceptions import (AdminRequiredException,ShopNotFoundException, UnauthorizedShopAccessException)
|
|
|
|
# Set auto_error=False to prevent automatic 403 responses
|
|
security = HTTPBearer(auto_error=False)
|
|
auth_manager = AuthManager()
|
|
rate_limiter = RateLimiter()
|
|
|
|
|
|
def get_current_user(
|
|
credentials: HTTPAuthorizationCredentials = Depends(security),
|
|
db: Session = Depends(get_db),
|
|
):
|
|
"""Get current authenticated user."""
|
|
# Check if credentials are provided
|
|
if not credentials:
|
|
from app.exceptions.auth import InvalidTokenException
|
|
raise InvalidTokenException("Authorization header required")
|
|
|
|
return auth_manager.get_current_user(db, credentials)
|
|
|
|
|
|
|
|
def get_current_admin_user(current_user: User = Depends(get_current_user)):
|
|
"""Require admin user."""
|
|
return auth_manager.require_admin(current_user)
|
|
|
|
|
|
def get_user_shop(
|
|
shop_code: str,
|
|
current_user: User = Depends(get_current_user),
|
|
db: Session = Depends(get_db),
|
|
):
|
|
"""Get shop and verify user ownership."""
|
|
shop = db.query(Shop).filter(Shop.shop_code == shop_code.upper()).first()
|
|
if not shop:
|
|
raise ShopNotFoundException(shop_code)
|
|
|
|
if current_user.role != "admin" and shop.owner_id != current_user.id:
|
|
raise UnauthorizedShopAccessException(shop_code, current_user.id)
|
|
|
|
return shop
|
|
|