Automated Action 91405a6195 Implement authentication service with FastAPI and SQLite
- Setup project structure and dependencies
- Create SQLite database with SQLAlchemy models
- Initialize Alembic for database migrations
- Implement JWT-based authentication utilities
- Create API endpoints for signup, login, and logout
- Add health check endpoint
- Implement authentication middleware for protected routes
- Update README with setup and usage instructions
- Add linting with Ruff
2025-05-17 17:33:29 +00:00

60 lines
1.7 KiB
Python

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.core.security import verify_password
from app.db.session import get_db
from app.models.user import User
from app.schemas.token import TokenPayload
oauth2_scheme = OAuth2PasswordBearer(
tokenUrl=f"{settings.API_V1_STR}/auth/login"
)
def authenticate_user(db: Session, username: str, password: str) -> User | None:
"""Authenticate a user by username and password
"""
user = db.query(User).filter(User.username == username).first()
if not user:
return None
if not verify_password(password, user.hashed_password):
return None
return user
def get_current_user(
db: Session = Depends(get_db), token: str = Depends(oauth2_scheme)
) -> User:
"""Get the current user from the token
"""
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid authentication credentials",
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = jwt.decode(
token, settings.SECRET_KEY, algorithms=["HS256"]
)
token_data = TokenPayload(**payload)
if token_data.sub is None:
raise credentials_exception
except JWTError as e:
raise credentials_exception from e
user = db.query(User).filter(User.id == token_data.sub).first()
if user is None:
raise credentials_exception
if not user.is_active:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Inactive user"
)
return user