init
This commit is contained in:
49
new-planet-backend/app/middleware/auth.py
Normal file
49
new-planet-backend/app/middleware/auth.py
Normal file
@@ -0,0 +1,49 @@
|
||||
from fastapi import Request, HTTPException, status
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
from app.core.security import decode_token
|
||||
from app.api.deps import oauth2_scheme
|
||||
|
||||
|
||||
class AuthMiddleware(BaseHTTPMiddleware):
|
||||
"""Middleware для проверки аутентификации на защищенных маршрутах"""
|
||||
|
||||
# Пути, которые не требуют аутентификации
|
||||
PUBLIC_PATHS = [
|
||||
"/api/v1/auth/login",
|
||||
"/api/v1/auth/register",
|
||||
"/docs",
|
||||
"/openapi.json",
|
||||
"/redoc"
|
||||
]
|
||||
|
||||
async def dispatch(self, request: Request, call_next):
|
||||
# Пропускаем публичные пути
|
||||
if any(request.url.path.startswith(path) for path in self.PUBLIC_PATHS):
|
||||
return await call_next(request)
|
||||
|
||||
# Проверяем токен для защищенных путей
|
||||
authorization = request.headers.get("Authorization")
|
||||
if not authorization:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Not authenticated",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
try:
|
||||
token = authorization.replace("Bearer ", "")
|
||||
payload = decode_token(token)
|
||||
if not payload:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid token"
|
||||
)
|
||||
except Exception:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid token"
|
||||
)
|
||||
|
||||
response = await call_next(request)
|
||||
return response
|
||||
|
||||
Reference in New Issue
Block a user