
- Set up project structure with FastAPI and dependency files - Configure SQLAlchemy with SQLite database - Implement user authentication using JWT tokens - Create comprehensive API routes for user management - Add health check endpoint for application monitoring - Set up Alembic for database migrations - Add detailed documentation in README.md
62 lines
1.8 KiB
Python
62 lines
1.8 KiB
Python
from datetime import timedelta
|
|
from typing import Any
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException, status
|
|
from fastapi.security import OAuth2PasswordRequestForm
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.core.config import settings
|
|
from app.core.security import create_access_token, verify_password
|
|
from app.db.session import get_db
|
|
from app.models.user import User
|
|
from app.schemas.token import Token
|
|
from app.api.deps import get_current_user
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
@router.post("/login", response_model=Token)
|
|
async def login_access_token(
|
|
db: Session = Depends(get_db),
|
|
form_data: OAuth2PasswordRequestForm = Depends(),
|
|
) -> Any:
|
|
"""
|
|
OAuth2 compatible token login, get an access token for future requests.
|
|
"""
|
|
# Try to authenticate the user
|
|
user = db.query(User).filter(User.email == form_data.username).first()
|
|
|
|
if not user:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Incorrect email or password",
|
|
)
|
|
|
|
if not verify_password(form_data.password, user.hashed_password):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Incorrect email or password",
|
|
)
|
|
|
|
if not user.is_active:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST, detail="Inactive user"
|
|
)
|
|
|
|
access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
|
|
|
|
return {
|
|
"access_token": create_access_token(
|
|
user.id, expires_delta=access_token_expires
|
|
),
|
|
"token_type": "bearer",
|
|
}
|
|
|
|
|
|
@router.post("/test-token", response_model=dict)
|
|
async def test_token(current_user: User = Depends(get_current_user)) -> Any:
|
|
"""
|
|
Test access token endpoint.
|
|
"""
|
|
return {"msg": "Token is valid", "user_id": current_user.id}
|