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
This commit is contained in:
parent
67e65a7726
commit
91405a6195
116
README.md
116
README.md
@ -1,3 +1,115 @@
|
||||
# FastAPI Application
|
||||
# Authentication Service
|
||||
|
||||
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform.
|
||||
A simple authentication service built with FastAPI and SQLite, providing JWT-based authentication for user signup, login, and logout functionality.
|
||||
|
||||
## Features
|
||||
|
||||
- User registration (signup)
|
||||
- User authentication (login)
|
||||
- User logout
|
||||
- JWT-based authentication
|
||||
- Protected routes
|
||||
- Health check endpoint
|
||||
- SQLite database with SQLAlchemy ORM
|
||||
- Database migrations with Alembic
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
.
|
||||
├── alembic.ini # Alembic configuration
|
||||
├── app # Application package
|
||||
│ ├── api # API endpoints
|
||||
│ │ └── endpoints.py # Auth endpoints
|
||||
│ ├── core # Core modules
|
||||
│ │ ├── auth.py # Auth utilities
|
||||
│ │ ├── config.py # App configuration
|
||||
│ │ └── security.py # Security utilities
|
||||
│ ├── db # Database
|
||||
│ │ ├── base.py # Base DB imports
|
||||
│ │ └── session.py # DB session
|
||||
│ ├── middleware # Middleware
|
||||
│ │ └── auth.py # JWT middleware
|
||||
│ ├── models # Database models
|
||||
│ │ └── user.py # User model
|
||||
│ └── schemas # Pydantic schemas
|
||||
│ ├── token.py # Token schemas
|
||||
│ └── user.py # User schemas
|
||||
├── init_db.py # DB initialization script
|
||||
├── main.py # Application entry point
|
||||
├── migrations # Alembic migrations
|
||||
│ ├── env.py # Migration env
|
||||
│ ├── script.py.mako # Migration template
|
||||
│ └── versions # Migration scripts
|
||||
│ └── 001_create_users_table.py
|
||||
└── requirements.txt # Project dependencies
|
||||
```
|
||||
|
||||
## Installation
|
||||
|
||||
1. Clone the repository
|
||||
2. Install dependencies:
|
||||
|
||||
```bash
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
3. Initialize the database:
|
||||
|
||||
```bash
|
||||
python init_db.py
|
||||
```
|
||||
|
||||
## Running the Application
|
||||
|
||||
```bash
|
||||
uvicorn main:app --reload
|
||||
```
|
||||
|
||||
The application will be available at http://localhost:8000
|
||||
|
||||
## API Documentation
|
||||
|
||||
Once the application is running, you can access:
|
||||
|
||||
- Swagger UI: http://localhost:8000/docs
|
||||
- ReDoc: http://localhost:8000/redoc
|
||||
|
||||
## API Endpoints
|
||||
|
||||
### Authentication
|
||||
|
||||
- `POST /api/v1/auth/signup` - Create a new user
|
||||
- `POST /api/v1/auth/login` - Login and get access token
|
||||
- `POST /api/v1/auth/logout` - Logout (client-side token invalidation)
|
||||
|
||||
### User
|
||||
|
||||
- `GET /api/v1/users/me` - Get current user information (protected)
|
||||
|
||||
### Health Check
|
||||
|
||||
- `GET /health` - Check application health and database connectivity
|
||||
|
||||
## Authentication Flow
|
||||
|
||||
1. **Signup**: Send a POST request to `/api/v1/auth/signup` with user information
|
||||
2. **Login**: Send a POST request to `/api/v1/auth/login` to get an access token
|
||||
3. **Authenticated Requests**: Include the token in the Authorization header as `Bearer <token>`
|
||||
4. **Logout**: Client should remove the token from storage
|
||||
|
||||
## Security
|
||||
|
||||
- Passwords are hashed using Bcrypt
|
||||
- JWT tokens are used for authentication
|
||||
- Token expiration is configurable in settings
|
||||
- Protected routes are secured with OAuth2PasswordBearer dependency
|
||||
|
||||
## Configuration
|
||||
|
||||
Configuration is handled through environment variables and the `app/core/config.py` file.
|
||||
|
||||
Important settings:
|
||||
- `SECRET_KEY`: Used for JWT token signing (change in production)
|
||||
- `ACCESS_TOKEN_EXPIRE_MINUTES`: Token expiration time
|
||||
- `SQLALCHEMY_DATABASE_URL`: Database connection string
|
85
alembic.ini
Normal file
85
alembic.ini
Normal file
@ -0,0 +1,85 @@
|
||||
# A generic, single database configuration.
|
||||
|
||||
[alembic]
|
||||
# path to migration scripts
|
||||
script_location = migrations
|
||||
|
||||
# template used to generate migration files
|
||||
# file_template = %%(rev)s_%%(slug)s
|
||||
|
||||
# timezone to use when rendering the date
|
||||
# within the migration file as well as the filename.
|
||||
# string value is passed to dateutil.tz.gettz()
|
||||
# leave blank for localtime
|
||||
# timezone =
|
||||
|
||||
# max length of characters to apply to the
|
||||
# "slug" field
|
||||
# truncate_slug_length = 40
|
||||
|
||||
# set to 'true' to run the environment during
|
||||
# the 'revision' command, regardless of autogenerate
|
||||
# revision_environment = false
|
||||
|
||||
# set to 'true' to allow .pyc and .pyo files without
|
||||
# a source .py file to be detected as revisions in the
|
||||
# versions/ directory
|
||||
# sourceless = false
|
||||
|
||||
# version location specification; this defaults
|
||||
# to migrations/versions. When using multiple version
|
||||
# directories, initial revisions must be specified with --version-path
|
||||
# version_locations = %(here)s/bar %(here)s/bat migrations/versions
|
||||
|
||||
# the output encoding used when revision files
|
||||
# are written from script.py.mako
|
||||
# output_encoding = utf-8
|
||||
|
||||
# SQLite URL - using absolute path
|
||||
sqlalchemy.url = sqlite:////app/storage/db/db.sqlite
|
||||
|
||||
[post_write_hooks]
|
||||
# post_write_hooks defines scripts or Python functions that are run
|
||||
# on newly generated revision scripts. See the documentation for further
|
||||
# detail and examples
|
||||
|
||||
# format using "black" - use the console_scripts runner, against the "black" entrypoint
|
||||
# hooks=black
|
||||
# black.type=console_scripts
|
||||
# black.entrypoint=black
|
||||
# black.options=-l 79
|
||||
|
||||
# Logging configuration
|
||||
[loggers]
|
||||
keys = root,sqlalchemy,alembic
|
||||
|
||||
[handlers]
|
||||
keys = console
|
||||
|
||||
[formatters]
|
||||
keys = generic
|
||||
|
||||
[logger_root]
|
||||
level = WARN
|
||||
handlers = console
|
||||
qualname =
|
||||
|
||||
[logger_sqlalchemy]
|
||||
level = WARN
|
||||
handlers =
|
||||
qualname = sqlalchemy.engine
|
||||
|
||||
[logger_alembic]
|
||||
level = INFO
|
||||
handlers =
|
||||
qualname = alembic
|
||||
|
||||
[handler_console]
|
||||
class = StreamHandler
|
||||
args = (sys.stderr,)
|
||||
level = NOTSET
|
||||
formatter = generic
|
||||
|
||||
[formatter_generic]
|
||||
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||
datefmt = %H:%M:%S
|
0
app/__init__.py
Normal file
0
app/__init__.py
Normal file
0
app/api/__init__.py
Normal file
0
app/api/__init__.py
Normal file
112
app/api/endpoints.py
Normal file
112
app/api/endpoints.py
Normal file
@ -0,0 +1,112 @@
|
||||
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.auth import get_current_user
|
||||
from app.core.config import settings
|
||||
from app.core.security import create_access_token, get_password_hash, verify_password
|
||||
from app.db.session import get_db
|
||||
from app.models.user import User
|
||||
from app.schemas.token import Token
|
||||
from app.schemas.user import User as UserSchema
|
||||
from app.schemas.user import UserCreate
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.post("/auth/signup", response_model=UserSchema)
|
||||
def create_user(
|
||||
user_in: UserCreate,
|
||||
db: Session = Depends(get_db)
|
||||
) -> Any:
|
||||
"""Create a new user
|
||||
"""
|
||||
# Check if user with this email or username already exists
|
||||
user = db.query(User).filter(
|
||||
(User.email == user_in.email) | (User.username == user_in.username)
|
||||
).first()
|
||||
if user:
|
||||
if user.email == user_in.email:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Email already registered"
|
||||
)
|
||||
else:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Username already taken"
|
||||
)
|
||||
|
||||
# Create new user
|
||||
user = User(
|
||||
email=user_in.email,
|
||||
username=user_in.username,
|
||||
hashed_password=get_password_hash(user_in.password),
|
||||
is_active=True
|
||||
)
|
||||
db.add(user)
|
||||
db.commit()
|
||||
db.refresh(user)
|
||||
|
||||
return user
|
||||
|
||||
|
||||
@router.post("/auth/login", response_model=Token)
|
||||
def login_access_token(
|
||||
form_data: OAuth2PasswordRequestForm = Depends(),
|
||||
db: Session = Depends(get_db)
|
||||
) -> Any:
|
||||
"""Get the JWT for a user with data from OAuth2 request form body
|
||||
"""
|
||||
# Try to authenticate with username
|
||||
user = db.query(User).filter(User.username == form_data.username).first()
|
||||
|
||||
# If user not found by username, try email
|
||||
if not user:
|
||||
user = db.query(User).filter(User.email == form_data.username).first()
|
||||
|
||||
if not user or not verify_password(form_data.password, user.hashed_password):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Incorrect username or password",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
# If user is not active
|
||||
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("/auth/logout", status_code=status.HTTP_204_NO_CONTENT, response_model=None)
|
||||
def logout(
|
||||
_: User = Depends(get_current_user),
|
||||
) -> None:
|
||||
"""Logout a user (JWT token should be invalidated client-side)
|
||||
"""
|
||||
# JWT is stateless, so nothing to do on server-side for logout
|
||||
# Client should remove the token
|
||||
return None
|
||||
|
||||
|
||||
@router.get("/users/me", response_model=UserSchema)
|
||||
def read_users_me(
|
||||
current_user: User = Depends(get_current_user),
|
||||
) -> Any:
|
||||
"""Get current user
|
||||
"""
|
||||
return current_user
|
0
app/core/__init__.py
Normal file
0
app/core/__init__.py
Normal file
59
app/core/auth.py
Normal file
59
app/core/auth.py
Normal file
@ -0,0 +1,59 @@
|
||||
|
||||
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
|
32
app/core/config.py
Normal file
32
app/core/config.py
Normal file
@ -0,0 +1,32 @@
|
||||
from pathlib import Path
|
||||
|
||||
from pydantic_settings import BaseSettings
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
"""Application settings class."""
|
||||
|
||||
API_V1_STR: str = "/api/v1"
|
||||
PROJECT_NAME: str = "Authentication Service"
|
||||
|
||||
# SECURITY
|
||||
SECRET_KEY: str = "your-secret-key-please-change-in-production"
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES: int = 30
|
||||
|
||||
# CORS
|
||||
BACKEND_CORS_ORIGINS: list[str] = ["*"]
|
||||
|
||||
# DATABASE
|
||||
DB_DIR: Path = Path("/app") / "storage" / "db"
|
||||
SQLALCHEMY_DATABASE_URL: str = f"sqlite:///{DB_DIR}/db.sqlite"
|
||||
|
||||
class Config:
|
||||
"""Configuration class for Settings."""
|
||||
|
||||
case_sensitive = True
|
||||
|
||||
|
||||
settings = Settings()
|
||||
|
||||
# Ensure DB directory exists
|
||||
settings.DB_DIR.mkdir(parents=True, exist_ok=True)
|
36
app/core/security.py
Normal file
36
app/core/security.py
Normal file
@ -0,0 +1,36 @@
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from jose import jwt
|
||||
from passlib.context import CryptContext
|
||||
|
||||
from app.core.config import settings
|
||||
|
||||
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||
|
||||
|
||||
def create_access_token(subject: str | Any, expires_delta: timedelta | None = None) -> str:
|
||||
"""Create a JWT access token
|
||||
"""
|
||||
if expires_delta:
|
||||
expire = datetime.utcnow() + expires_delta
|
||||
else:
|
||||
expire = datetime.utcnow() + timedelta(
|
||||
minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES
|
||||
)
|
||||
|
||||
to_encode = {"exp": expire, "sub": str(subject)}
|
||||
encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm="HS256")
|
||||
return encoded_jwt
|
||||
|
||||
|
||||
def verify_password(plain_password: str, hashed_password: str) -> bool:
|
||||
"""Verify a password against a hash
|
||||
"""
|
||||
return pwd_context.verify(plain_password, hashed_password)
|
||||
|
||||
|
||||
def get_password_hash(password: str) -> str:
|
||||
"""Hash a password
|
||||
"""
|
||||
return pwd_context.hash(password)
|
0
app/db/__init__.py
Normal file
0
app/db/__init__.py
Normal file
2
app/db/base.py
Normal file
2
app/db/base.py
Normal file
@ -0,0 +1,2 @@
|
||||
# Import all models here for Alembic to discover
|
||||
from app.models.user import User # noqa
|
24
app/db/session.py
Normal file
24
app/db/session.py
Normal file
@ -0,0 +1,24 @@
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from app.core.config import settings
|
||||
|
||||
engine = create_engine(
|
||||
settings.SQLALCHEMY_DATABASE_URL,
|
||||
connect_args={"check_same_thread": False} # only needed for SQLite
|
||||
)
|
||||
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
|
||||
Base = declarative_base()
|
||||
|
||||
|
||||
def get_db():
|
||||
"""Dependency function that yields db sessions
|
||||
"""
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
0
app/middleware/__init__.py
Normal file
0
app/middleware/__init__.py
Normal file
70
app/middleware/auth.py
Normal file
70
app/middleware/auth.py
Normal file
@ -0,0 +1,70 @@
|
||||
from collections.abc import Callable
|
||||
|
||||
from fastapi import Request, status
|
||||
from fastapi.responses import JSONResponse
|
||||
from jose import JWTError, jwt
|
||||
|
||||
from app.core.config import settings
|
||||
|
||||
|
||||
def jwt_middleware(
|
||||
excluded_paths: list[str] | None = None,
|
||||
) -> Callable:
|
||||
"""Middleware to check for a valid JWT token in protected routes.
|
||||
|
||||
Args:
|
||||
excluded_paths: List of paths to exclude from JWT verification
|
||||
|
||||
Returns:
|
||||
Middleware function
|
||||
|
||||
"""
|
||||
async def middleware(request: Request, call_next):
|
||||
# Default excluded paths - public API endpoints and health check
|
||||
if excluded_paths is None:
|
||||
_excluded_paths = [
|
||||
f"{settings.API_V1_STR}/auth/signup",
|
||||
f"{settings.API_V1_STR}/auth/login",
|
||||
"/health",
|
||||
"/docs",
|
||||
"/redoc",
|
||||
"/openapi.json",
|
||||
]
|
||||
else:
|
||||
_excluded_paths = excluded_paths
|
||||
|
||||
# Skip JWT verification for excluded paths
|
||||
if any(request.url.path.startswith(path) for path in _excluded_paths):
|
||||
return await call_next(request)
|
||||
|
||||
# Get token from Authorization header
|
||||
auth_header = request.headers.get('Authorization')
|
||||
if not auth_header or not auth_header.startswith('Bearer '):
|
||||
return JSONResponse(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
content={"detail": "Not authenticated"},
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
token = auth_header.split(' ')[1]
|
||||
|
||||
try:
|
||||
# Verify token
|
||||
payload = jwt.decode(
|
||||
token, settings.SECRET_KEY, algorithms=["HS256"]
|
||||
)
|
||||
|
||||
# Attach user_id to request state for future use
|
||||
request.state.user_id = int(payload.get("sub"))
|
||||
|
||||
except JWTError:
|
||||
return JSONResponse(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
content={"detail": "Invalid authentication credentials"},
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
# Continue processing the request
|
||||
return await call_next(request)
|
||||
|
||||
return middleware
|
0
app/models/__init__.py
Normal file
0
app/models/__init__.py
Normal file
18
app/models/user.py
Normal file
18
app/models/user.py
Normal file
@ -0,0 +1,18 @@
|
||||
from sqlalchemy import Boolean, Column, DateTime, Integer, String
|
||||
from sqlalchemy.sql import func
|
||||
|
||||
from app.db.session import Base
|
||||
|
||||
|
||||
class User(Base):
|
||||
"""User database model."""
|
||||
|
||||
__tablename__ = "users"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
email = Column(String, unique=True, index=True, nullable=False)
|
||||
username = Column(String, unique=True, index=True, nullable=False)
|
||||
hashed_password = Column(String, nullable=False)
|
||||
is_active = Column(Boolean, default=True)
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now())
|
||||
updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
|
0
app/schemas/__init__.py
Normal file
0
app/schemas/__init__.py
Normal file
15
app/schemas/token.py
Normal file
15
app/schemas/token.py
Normal file
@ -0,0 +1,15 @@
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class Token(BaseModel):
|
||||
"""Token schema for API responses."""
|
||||
|
||||
access_token: str
|
||||
token_type: str
|
||||
|
||||
|
||||
class TokenPayload(BaseModel):
|
||||
"""Token payload schema for JWT tokens."""
|
||||
|
||||
sub: int | None = None
|
55
app/schemas/user.py
Normal file
55
app/schemas/user.py
Normal file
@ -0,0 +1,55 @@
|
||||
from datetime import datetime
|
||||
|
||||
from pydantic import BaseModel, EmailStr, Field
|
||||
|
||||
|
||||
class UserBase(BaseModel):
|
||||
"""Base user schema."""
|
||||
|
||||
email: EmailStr
|
||||
username: str
|
||||
is_active: bool = True
|
||||
|
||||
|
||||
class UserCreate(BaseModel):
|
||||
"""User schema for creating new users."""
|
||||
|
||||
email: EmailStr
|
||||
username: str
|
||||
password: str = Field(..., min_length=8)
|
||||
|
||||
|
||||
class UserUpdate(BaseModel):
|
||||
"""User schema for updating users."""
|
||||
|
||||
email: EmailStr | None = None
|
||||
username: str | None = None
|
||||
password: str | None = Field(None, min_length=8)
|
||||
is_active: bool | None = None
|
||||
|
||||
|
||||
class UserInDBBase(UserBase):
|
||||
"""Base user schema with DB fields."""
|
||||
|
||||
id: int
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
class Config:
|
||||
"""Configuration for Pydantic model."""
|
||||
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class User(UserInDBBase):
|
||||
"""User model returned to the client
|
||||
"""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class UserInDB(UserInDBBase):
|
||||
"""User model with password stored in DB
|
||||
"""
|
||||
|
||||
hashed_password: str
|
18
init_db.py
Normal file
18
init_db.py
Normal file
@ -0,0 +1,18 @@
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
# Add the current directory to the Python path
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
from app.core.config import settings
|
||||
|
||||
# Ensure database directory exists
|
||||
settings.DB_DIR.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
print(f"Initializing database at {settings.SQLALCHEMY_DATABASE_URL}")
|
||||
|
||||
# Run Alembic migrations
|
||||
subprocess.run(["alembic", "upgrade", "head"], check=True)
|
||||
|
||||
print("Database initialization completed.")
|
54
main.py
Normal file
54
main.py
Normal file
@ -0,0 +1,54 @@
|
||||
from fastapi import Depends, FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.api.endpoints import router as api_router
|
||||
from app.core.config import settings
|
||||
from app.db.session import get_db
|
||||
|
||||
# Initialize FastAPI app
|
||||
app = FastAPI(
|
||||
title=settings.PROJECT_NAME,
|
||||
openapi_url=f"{settings.API_V1_STR}/openapi.json"
|
||||
)
|
||||
|
||||
# Set up CORS middleware
|
||||
if settings.BACKEND_CORS_ORIGINS:
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=[str(origin) for origin in settings.BACKEND_CORS_ORIGINS],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
# Add JWT authentication middleware
|
||||
# Note: This middleware is commented out because we're already using FastAPI's
|
||||
# dependency injection for authentication. Uncomment if you want to use middleware approach.
|
||||
# app.middleware("http")(jwt_middleware())
|
||||
|
||||
# Include API router
|
||||
app.include_router(api_router, prefix=settings.API_V1_STR)
|
||||
|
||||
|
||||
# Health check endpoint
|
||||
@app.get("/health", tags=["health"])
|
||||
def health_check(db: Session = Depends(get_db)):
|
||||
"""Health check endpoint to verify the service is running and database connection is working
|
||||
"""
|
||||
# Try to execute a simple query to verify database connection
|
||||
try:
|
||||
db.execute("SELECT 1")
|
||||
db_status = "healthy"
|
||||
except Exception as e:
|
||||
db_status = f"unhealthy: {str(e)}"
|
||||
|
||||
return {
|
||||
"status": "ok",
|
||||
"database": db_status
|
||||
}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
uvicorn.run(app, host="0.0.0.0", port=8000)
|
81
migrations/env.py
Normal file
81
migrations/env.py
Normal file
@ -0,0 +1,81 @@
|
||||
from logging.config import fileConfig
|
||||
|
||||
from alembic import context
|
||||
from sqlalchemy import engine_from_config, pool
|
||||
|
||||
# this is the Alembic Config object, which provides
|
||||
# access to the values within the .ini file in use.
|
||||
config = context.config
|
||||
|
||||
# Interpret the config file for Python logging.
|
||||
# This line sets up loggers basically.
|
||||
if config.config_file_name is not None:
|
||||
fileConfig(config.config_file_name)
|
||||
|
||||
# add your model's MetaData object here
|
||||
# for 'autogenerate' support
|
||||
# from myapp import mymodel
|
||||
# target_metadata = mymodel.Base.metadata
|
||||
from app.db.base import Base
|
||||
|
||||
target_metadata = Base.metadata
|
||||
|
||||
# other values from the config, defined by the needs of env.py,
|
||||
# can be acquired:
|
||||
# my_important_option = config.get_main_option("my_important_option")
|
||||
# ... etc.
|
||||
|
||||
|
||||
def run_migrations_offline() -> None:
|
||||
"""Run migrations in 'offline' mode.
|
||||
|
||||
This configures the context with just a URL
|
||||
and not an Engine, though an Engine is acceptable
|
||||
here as well. By skipping the Engine creation
|
||||
we don't even need a DBAPI to be available.
|
||||
|
||||
Calls to context.execute() here emit the given string to the
|
||||
script output.
|
||||
|
||||
"""
|
||||
url = config.get_main_option("sqlalchemy.url")
|
||||
context.configure(
|
||||
url=url,
|
||||
target_metadata=target_metadata,
|
||||
literal_binds=True,
|
||||
dialect_opts={"paramstyle": "named"},
|
||||
)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
def run_migrations_online() -> None:
|
||||
"""Run migrations in 'online' mode.
|
||||
|
||||
In this scenario we need to create an Engine
|
||||
and associate a connection with the context.
|
||||
|
||||
"""
|
||||
connectable = engine_from_config(
|
||||
config.get_section(config.config_ini_section),
|
||||
prefix="sqlalchemy.",
|
||||
poolclass=pool.NullPool,
|
||||
)
|
||||
|
||||
with connectable.connect() as connection:
|
||||
is_sqlite = connection.dialect.name == 'sqlite'
|
||||
context.configure(
|
||||
connection=connection,
|
||||
target_metadata=target_metadata,
|
||||
render_as_batch=is_sqlite # Key configuration for SQLite
|
||||
)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
if context.is_offline_mode():
|
||||
run_migrations_offline()
|
||||
else:
|
||||
run_migrations_online()
|
24
migrations/script.py.mako
Normal file
24
migrations/script.py.mako
Normal file
@ -0,0 +1,24 @@
|
||||
"""${message}
|
||||
|
||||
Revision ID: ${up_revision}
|
||||
Revises: ${down_revision | comma,n}
|
||||
Create Date: ${create_date}
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
${imports if imports else ""}
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = ${repr(up_revision)}
|
||||
down_revision = ${repr(down_revision)}
|
||||
branch_labels = ${repr(branch_labels)}
|
||||
depends_on = ${repr(depends_on)}
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
${upgrades if upgrades else "pass"}
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
${downgrades if downgrades else "pass"}
|
40
migrations/versions/001_create_users_table.py
Normal file
40
migrations/versions/001_create_users_table.py
Normal file
@ -0,0 +1,40 @@
|
||||
"""create users table
|
||||
|
||||
Revision ID: 001
|
||||
Revises:
|
||||
Create Date: 2023-10-15
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '001'
|
||||
down_revision = None
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
'users',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('email', sa.String(), nullable=False),
|
||||
sa.Column('username', sa.String(), nullable=False),
|
||||
sa.Column('hashed_password', sa.String(), nullable=False),
|
||||
sa.Column('is_active', sa.Boolean(), default=True),
|
||||
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('CURRENT_TIMESTAMP')),
|
||||
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('CURRENT_TIMESTAMP'), onupdate=sa.text('CURRENT_TIMESTAMP')),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
op.create_index(op.f('ix_users_id'), 'users', ['id'], unique=False)
|
||||
op.create_index(op.f('ix_users_email'), 'users', ['email'], unique=True)
|
||||
op.create_index(op.f('ix_users_username'), 'users', ['username'], unique=True)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_index(op.f('ix_users_username'), table_name='users')
|
||||
op.drop_index(op.f('ix_users_email'), table_name='users')
|
||||
op.drop_index(op.f('ix_users_id'), table_name='users')
|
||||
op.drop_table('users')
|
44
pyproject.toml
Normal file
44
pyproject.toml
Normal file
@ -0,0 +1,44 @@
|
||||
[tool.ruff]
|
||||
line-length = 100
|
||||
target-version = "py310"
|
||||
|
||||
# Exclude directories and files from linting
|
||||
exclude = [
|
||||
".git",
|
||||
".github",
|
||||
".mypy_cache",
|
||||
".ruff_cache",
|
||||
".venv",
|
||||
"venv",
|
||||
"__pycache__",
|
||||
"migrations/versions",
|
||||
]
|
||||
|
||||
[tool.ruff.lint]
|
||||
# Enable Pyflakes (`F`) and a subset of the pycodestyle (`E`)
|
||||
select = ["E", "F", "I", "W", "N", "D", "UP", "B", "C4", "SIM", "ERA"]
|
||||
ignore = [
|
||||
"E501", # Line length is already enforced by the formatter
|
||||
"D100", # Missing docstring in public module
|
||||
"D104", # Missing docstring in public package
|
||||
"D200", # One-line docstring should fit on one line
|
||||
"D400", # First line should end with a period
|
||||
"D415", # First line should end with a period, question mark, or exclamation point
|
||||
"ERA001", # Found commented-out code
|
||||
"E402", # Module level import not at top of file
|
||||
"B008", # Do not perform function call in argument defaults
|
||||
]
|
||||
|
||||
# Allow fix for all enabled rules (when `--fix`) is provided.
|
||||
fixable = ["ALL"]
|
||||
unfixable = []
|
||||
|
||||
# Allow unused variables when underscore-prefixed.
|
||||
dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$"
|
||||
|
||||
[tool.ruff.lint.mccabe]
|
||||
# Flag any methods with a complexity higher than 10.
|
||||
max-complexity = 10
|
||||
|
||||
[tool.ruff.lint.isort]
|
||||
known-third-party = ["fastapi", "pydantic", "sqlalchemy", "jose", "passlib", "alembic"]
|
10
requirements.txt
Normal file
10
requirements.txt
Normal file
@ -0,0 +1,10 @@
|
||||
fastapi>=0.100.0
|
||||
uvicorn>=0.23.0
|
||||
sqlalchemy>=2.0.0
|
||||
alembic>=1.11.0
|
||||
python-jose[cryptography]>=3.3.0
|
||||
passlib[bcrypt]>=1.7.4
|
||||
pydantic>=2.0.0
|
||||
pydantic-settings>=2.0.0
|
||||
python-multipart>=0.0.6
|
||||
ruff>=0.1.0
|
Loading…
x
Reference in New Issue
Block a user