
- Created FastAPI application with SQLite database - Implemented models for inventory items, categories, suppliers, and transactions - Added authentication system with JWT tokens - Implemented CRUD operations for all models - Set up Alembic for database migrations - Added comprehensive API documentation - Configured Ruff for code linting
52 lines
1.4 KiB
Python
52 lines
1.4 KiB
Python
from typing import Generator
|
|
|
|
from fastapi import Depends, HTTPException, status
|
|
from fastapi.security import OAuth2PasswordBearer
|
|
from jose import JWTError, jwt
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.core.config import settings
|
|
from app.db.session import SessionLocal
|
|
from app.models.user import User
|
|
from app.schemas.token import TokenPayload
|
|
|
|
oauth2_scheme = OAuth2PasswordBearer(tokenUrl=f"{settings.API_V1_STR}/auth/login")
|
|
|
|
|
|
def get_db() -> Generator:
|
|
"""
|
|
Get a database session as a dependency for routes.
|
|
"""
|
|
db = SessionLocal()
|
|
try:
|
|
yield db
|
|
finally:
|
|
db.close()
|
|
|
|
|
|
def get_current_user(
|
|
db: Session = Depends(get_db), token: str = Depends(oauth2_scheme)
|
|
) -> User:
|
|
"""
|
|
Get the current user based on the JWT token.
|
|
"""
|
|
credentials_exception = HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Could not validate credentials",
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
)
|
|
try:
|
|
payload = jwt.decode(
|
|
token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM]
|
|
)
|
|
username: str = payload.get("sub")
|
|
if username is None:
|
|
raise credentials_exception
|
|
token_data = TokenPayload(username=username)
|
|
except JWTError:
|
|
raise credentials_exception
|
|
|
|
user = db.query(User).filter(User.username == token_data.username).first()
|
|
if user is None:
|
|
raise credentials_exception
|
|
return user |