Exception handling enhancement
This commit is contained in:
@@ -7,7 +7,7 @@ This module provides classes and functions for:
|
||||
- ....
|
||||
"""
|
||||
|
||||
from fastapi import Depends, HTTPException
|
||||
from fastapi import Depends
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
@@ -16,6 +16,7 @@ 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)
|
||||
@@ -30,11 +31,13 @@ def get_current_user(
|
||||
"""Get current authenticated user."""
|
||||
# Check if credentials are provided
|
||||
if not credentials:
|
||||
raise HTTPException(status_code=401, detail="Authorization header required")
|
||||
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)
|
||||
@@ -48,9 +51,10 @@ def get_user_shop(
|
||||
"""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")
|
||||
raise ShopNotFoundException(shop_code)
|
||||
|
||||
if current_user.role != "admin" and shop.owner_id != current_user.id:
|
||||
raise HTTPException(status_code=403, detail="Access denied to this shop")
|
||||
raise UnauthorizedShopAccessException(shop_code, current_user.id)
|
||||
|
||||
return shop
|
||||
|
||||
|
||||
Reference in New Issue
Block a user