Introduces schemas for user management, token handling, and password hashing. Implements routes for user registration, login, token refresh, and user info retrieval. Sets up authentication dependencies and integrates the API router with the application.
45 lines
1.3 KiB
Python
45 lines
1.3 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 auth.security import SECRET_KEY, ALGORITHM
|
|
from app.core.database import get_db
|
|
from models.user import User
|
|
from app.schemas.token import TokenData
|
|
|
|
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="auth/token")
|
|
|
|
async def get_current_user(
|
|
token: str = Depends(oauth2_scheme),
|
|
db: AsyncSession = Depends(get_db)
|
|
):
|
|
credentials_exception = HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Could not validate credentials",
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
)
|
|
|
|
try:
|
|
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|
|
user_id: str = payload.get("sub")
|
|
token_type: str = payload.get("type")
|
|
|
|
if user_id is None or token_type != "access":
|
|
raise credentials_exception
|
|
|
|
except JWTError:
|
|
raise credentials_exception
|
|
|
|
user = await db.get(User, user_id)
|
|
if user is None:
|
|
raise credentials_exception
|
|
|
|
return user
|
|
|
|
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 |