37 lines
1.2 KiB
Python
37 lines
1.2 KiB
Python
import jwt
|
|
from fastapi import Depends, HTTPException, Security
|
|
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.application.users_repository import UsersRepository
|
|
from app.database.dependencies import get_db
|
|
from app.settings import get_auth_data
|
|
|
|
security = HTTPBearer()
|
|
|
|
|
|
def get_current_user(
|
|
credentials: HTTPAuthorizationCredentials = Security(security),
|
|
db: Session = Depends(get_db)
|
|
):
|
|
token = credentials.credentials
|
|
auth_data = get_auth_data()
|
|
|
|
try:
|
|
payload = jwt.decode(token, auth_data["secret_key"], algorithms=[auth_data["algorithm"]])
|
|
user_id = payload.get("user_id")
|
|
|
|
if user_id is None:
|
|
raise HTTPException(status_code=401, detail="Invalid token")
|
|
|
|
user = UsersRepository(db).get_by_id(user_id)
|
|
if user is None:
|
|
raise HTTPException(status_code=401, detail="User not found")
|
|
|
|
return user
|
|
|
|
except jwt.ExpiredSignatureError:
|
|
raise HTTPException(status_code=401, detail="Token expired")
|
|
except jwt.InvalidTokenError:
|
|
raise HTTPException(status_code=401, detail="Invalid token")
|