
- Set up project structure and FastAPI application - Create database models with SQLAlchemy - Implement authentication with JWT - Add CRUD operations for products, inventory, categories - Implement purchase order and sales functionality - Create reporting endpoints - Set up Alembic for database migrations - Add comprehensive documentation in README.md
64 lines
1.7 KiB
Python
64 lines
1.7 KiB
Python
from typing import Generator, Optional
|
|
|
|
from fastapi import Depends, HTTPException, status
|
|
from fastapi.security import OAuth2PasswordBearer
|
|
from jose import jwt
|
|
from pydantic import ValidationError
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.core.config import settings
|
|
from app.core.security.jwt import ALGORITHM, decode_token
|
|
from app.db.session import get_db
|
|
from app.models.user import User
|
|
from app.schemas.token import TokenPayload
|
|
from app.crud.crud_user import user
|
|
|
|
|
|
oauth2_scheme = OAuth2PasswordBearer(
|
|
tokenUrl=f"{settings.API_V1_STR}/login/access-token"
|
|
)
|
|
|
|
|
|
def get_current_user(
|
|
db: Session = Depends(get_db), token: str = Depends(oauth2_scheme)
|
|
) -> User:
|
|
"""
|
|
Get current user based on JWT token
|
|
"""
|
|
token_data = decode_token(token)
|
|
if not token_data:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Could not validate credentials",
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
)
|
|
|
|
db_user = user.get(db, id=token_data.sub)
|
|
if not db_user:
|
|
raise HTTPException(status_code=404, detail="User not found")
|
|
return db_user
|
|
|
|
|
|
def get_current_active_user(
|
|
current_user: User = Depends(get_current_user),
|
|
) -> User:
|
|
"""
|
|
Get current active user
|
|
"""
|
|
if not current_user.is_active:
|
|
raise HTTPException(status_code=400, detail="Inactive user")
|
|
return current_user
|
|
|
|
|
|
def get_current_admin_user(
|
|
current_user: User = Depends(get_current_user),
|
|
) -> User:
|
|
"""
|
|
Get current admin user
|
|
"""
|
|
if not current_user.is_admin:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
detail="The user doesn't have enough privileges"
|
|
)
|
|
return current_user |