
Features: - User authentication with JWT - Client management with CRUD operations - Invoice generation and management - SQLite database with Alembic migrations - Detailed project documentation
64 lines
1.9 KiB
Python
64 lines
1.9 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.api.deps import get_current_user
|
|
from app.core.auth import authenticate_user, create_access_token
|
|
from app.core.config import settings
|
|
from app.core.logging import app_logger
|
|
from app.db.session import get_db
|
|
from app.models.user import User
|
|
from app.schemas.token import Token
|
|
from app.utils.activity import log_activity
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
@router.post("/login", response_model=Token)
|
|
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
|
|
"""
|
|
user = authenticate_user(db, form_data.username, form_data.password)
|
|
if not user:
|
|
app_logger.warning(f"Failed login attempt for user: {form_data.username}")
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Incorrect email or password",
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
)
|
|
|
|
access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
|
|
access_token = create_access_token(
|
|
subject=user.email, expires_delta=access_token_expires
|
|
)
|
|
|
|
# Log login activity
|
|
log_activity(
|
|
db=db,
|
|
user_id=user.id,
|
|
action="login",
|
|
entity_type="user",
|
|
entity_id=user.id,
|
|
details="User logged in successfully"
|
|
)
|
|
|
|
app_logger.info(f"User logged in: {user.email}")
|
|
return {"access_token": access_token, "token_type": "bearer"}
|
|
|
|
|
|
@router.post("/test-token", response_model=dict)
|
|
def test_token(current_user: User = Depends(get_current_user)) -> Any:
|
|
"""
|
|
Test access token
|
|
"""
|
|
return {
|
|
"email": current_user.email,
|
|
"message": "Token is valid",
|
|
} |