46 lines
1.5 KiB
Python
46 lines
1.5 KiB
Python
from fastapi import Depends, HTTPException
|
|
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
|
from sqlalchemy.orm import Session
|
|
from app.core.database import get_db
|
|
from models.database_models import User, Shop
|
|
from middleware.auth import AuthManager
|
|
from middleware.rate_limiter import RateLimiter
|
|
|
|
# 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:
|
|
raise HTTPException(status_code=401, detail="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 HTTPException(status_code=404, detail="Shop not found")
|
|
|
|
if current_user.role != "admin" and shop.owner_id != current_user.id:
|
|
raise HTTPException(status_code=403, detail="Access denied to this shop")
|
|
|
|
return shop
|