Improved the `decode_token` function to clarify and extend error handling for token validation and decoding. Enhanced error messages for invalid tokens, added checks for missing claims, and ensured clear differentiation of failure scenarios. Updated imports and added a `scope` field to token response for completeness.
41 lines
1.2 KiB
Python
41 lines
1.2 KiB
Python
from fastapi import Depends, HTTPException, status
|
|
from fastapi.security import OAuth2PasswordBearer
|
|
from jose import JWTError, jwt
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from app.core.database import get_db
|
|
from app.auth.security import decode_token
|
|
from app.models.user import User
|
|
|
|
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="auth/token")
|
|
|
|
|
|
async def get_current_user(
|
|
token: str = Depends(oauth2_scheme),
|
|
db: AsyncSession = Depends(get_db)
|
|
):
|
|
try:
|
|
payload = await decode_token(token) # Use updated decode_token.
|
|
user_id: str = payload.sub
|
|
token_type: str = payload.type
|
|
|
|
if user_id is None or token_type != "access":
|
|
raise HTTPException(status_code=401, detail="Invalid token type.")
|
|
|
|
user = await db.get(User, user_id)
|
|
if user is None:
|
|
raise HTTPException(status_code=401, detail="User not found.")
|
|
|
|
return user
|
|
except JWTError as e:
|
|
raise HTTPException(status_code=401, detail=str(e))
|
|
|
|
|
|
|
|
async def get_current_active_user(
|
|
current_user: User = Depends(get_current_user),
|
|
):
|
|
if not current_user.is_active:
|
|
raise HTTPException(status_code=400, detail="Inactive user")
|
|
return current_user
|