From 48f0debd7b71ba4a55f8caa00ede3d9a1bc69c13 Mon Sep 17 00:00:00 2001 From: Automated Action Date: Fri, 27 Jun 2025 09:18:50 +0000 Subject: [PATCH] Implement user authentication flow with FastAPI - Set up FastAPI application with SQLite database - Create User model with email and password fields - Implement JWT token-based authentication - Add user registration and login endpoints - Create protected user profile endpoints - Configure Alembic for database migrations - Add password hashing with bcrypt - Include CORS middleware and health endpoint - Update README with setup and usage instructions Environment variables required: - SECRET_KEY: JWT secret key for token signing --- README.md | 79 +++++++++++++++++++- alembic.ini | 41 ++++++++++ alembic/env.py | 49 ++++++++++++ alembic/script.py.mako | 22 ++++++ alembic/versions/001_create_users_table.py | 33 ++++++++ app/__init__.py | 0 app/api/__init__.py | 0 app/api/routes/__init__.py | 0 app/api/routes/auth.py | 87 ++++++++++++++++++++++ app/api/routes/users.py | 15 ++++ app/core/__init__.py | 0 app/core/security.py | 30 ++++++++ app/db/__init__.py | 0 app/db/base.py | 3 + app/db/session.py | 22 ++++++ app/models/__init__.py | 0 app/models/user.py | 13 ++++ app/schemas/__init__.py | 0 app/schemas/user.py | 29 ++++++++ main.py | 41 ++++++++++ requirements.txt | 8 ++ 21 files changed, 470 insertions(+), 2 deletions(-) create mode 100644 alembic.ini create mode 100644 alembic/env.py create mode 100644 alembic/script.py.mako create mode 100644 alembic/versions/001_create_users_table.py create mode 100644 app/__init__.py create mode 100644 app/api/__init__.py create mode 100644 app/api/routes/__init__.py create mode 100644 app/api/routes/auth.py create mode 100644 app/api/routes/users.py create mode 100644 app/core/__init__.py create mode 100644 app/core/security.py create mode 100644 app/db/__init__.py create mode 100644 app/db/base.py create mode 100644 app/db/session.py create mode 100644 app/models/__init__.py create mode 100644 app/models/user.py create mode 100644 app/schemas/__init__.py create mode 100644 app/schemas/user.py create mode 100644 main.py create mode 100644 requirements.txt diff --git a/README.md b/README.md index e8acfba..ce488f4 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,78 @@ -# FastAPI Application +# User Authentication Service -This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform. +A FastAPI-based user authentication service with JWT token authentication and SQLite database. + +## Features + +- User registration and login +- JWT token-based authentication +- Password hashing with bcrypt +- SQLite database with SQLAlchemy ORM +- Database migrations with Alembic +- CORS enabled for all origins +- Health check endpoint +- Auto-generated API documentation + +## Environment Variables + +Set the following environment variables before running the application: + +- `SECRET_KEY`: JWT secret key for token signing (required for production) + +## Installation + +1. Install dependencies: +```bash +pip install -r requirements.txt +``` + +2. Run database migrations: +```bash +alembic upgrade head +``` + +3. Start the application: +```bash +uvicorn main:app --reload +``` + +## API Endpoints + +### Public Endpoints +- `GET /` - Service information +- `GET /health` - Health check +- `POST /api/v1/auth/register` - User registration +- `POST /api/v1/auth/login` - User login + +### Protected Endpoints (require Bearer token) +- `GET /api/v1/users/me` - Get current user info +- `GET /api/v1/users/profile` - Get user profile + +## API Documentation + +Once the application is running, visit: +- Swagger UI: http://localhost:8000/docs +- ReDoc: http://localhost:8000/redoc +- OpenAPI JSON: http://localhost:8000/openapi.json + +## Usage Example + +1. Register a new user: +```bash +curl -X POST "http://localhost:8000/api/v1/auth/register" \ + -H "Content-Type: application/json" \ + -d '{"email": "user@example.com", "password": "password123"}' +``` + +2. Login to get access token: +```bash +curl -X POST "http://localhost:8000/api/v1/auth/login" \ + -H "Content-Type: application/x-www-form-urlencoded" \ + -d "username=user@example.com&password=password123" +``` + +3. Access protected endpoint: +```bash +curl -X GET "http://localhost:8000/api/v1/users/me" \ + -H "Authorization: Bearer YOUR_ACCESS_TOKEN" +``` diff --git a/alembic.ini b/alembic.ini new file mode 100644 index 0000000..017f263 --- /dev/null +++ b/alembic.ini @@ -0,0 +1,41 @@ +[alembic] +script_location = alembic +prepend_sys_path = . +version_path_separator = os +sqlalchemy.url = sqlite:////app/storage/db/db.sqlite + +[post_write_hooks] + +[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 \ No newline at end of file diff --git a/alembic/env.py b/alembic/env.py new file mode 100644 index 0000000..9d0ba5d --- /dev/null +++ b/alembic/env.py @@ -0,0 +1,49 @@ +from logging.config import fileConfig +from sqlalchemy import engine_from_config +from sqlalchemy import pool +from alembic import context +import sys +import os + +sys.path.append(os.path.dirname(os.path.dirname(__file__))) + +from app.db.base import Base + +config = context.config + +if config.config_file_name is not None: + fileConfig(config.config_file_name) + +target_metadata = Base.metadata + +def run_migrations_offline() -> None: + 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: + connectable = engine_from_config( + config.get_section(config.config_ini_section), + prefix="sqlalchemy.", + poolclass=pool.NullPool, + ) + + with connectable.connect() as connection: + context.configure( + connection=connection, target_metadata=target_metadata + ) + + with context.begin_transaction(): + context.run_migrations() + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() \ No newline at end of file diff --git a/alembic/script.py.mako b/alembic/script.py.mako new file mode 100644 index 0000000..85784ed --- /dev/null +++ b/alembic/script.py.mako @@ -0,0 +1,22 @@ +"""${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"} \ No newline at end of file diff --git a/alembic/versions/001_create_users_table.py b/alembic/versions/001_create_users_table.py new file mode 100644 index 0000000..e92731c --- /dev/null +++ b/alembic/versions/001_create_users_table.py @@ -0,0 +1,33 @@ +"""create users table + +Revision ID: 001 +Revises: +Create Date: 2024-01-01 00:00:00.000000 + +""" +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('hashed_password', sa.String(), nullable=False), + sa.Column('is_active', sa.Boolean(), nullable=True), + sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True), + sa.Column('updated_at', sa.DateTime(timezone=True), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_users_email'), 'users', ['email'], unique=True) + op.create_index(op.f('ix_users_id'), 'users', ['id'], unique=False) + +def downgrade() -> None: + op.drop_index(op.f('ix_users_id'), table_name='users') + op.drop_index(op.f('ix_users_email'), table_name='users') + op.drop_table('users') \ No newline at end of file diff --git a/app/__init__.py b/app/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/api/__init__.py b/app/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/api/routes/__init__.py b/app/api/routes/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/api/routes/auth.py b/app/api/routes/auth.py new file mode 100644 index 0000000..abacee9 --- /dev/null +++ b/app/api/routes/auth.py @@ -0,0 +1,87 @@ +from datetime import timedelta +from fastapi import APIRouter, Depends, HTTPException, status +from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm +from sqlalchemy.orm import Session +from jose import JWTError, jwt + +from app.core.security import ( + ALGORITHM, + SECRET_KEY, + create_access_token, + get_password_hash, + verify_password, +) +from app.db.session import get_db +from app.models.user import User +from app.schemas.user import Token, TokenData, UserCreate, User as UserSchema + +router = APIRouter() +oauth2_scheme = OAuth2PasswordBearer(tokenUrl="api/v1/auth/login") + +def get_user_by_email(db: Session, email: str): + return db.query(User).filter(User.email == email).first() + +def authenticate_user(db: Session, email: str, password: str): + user = get_user_by_email(db, email) + if not user: + return False + if not verify_password(password, user.hashed_password): + return False + return user + +def create_user(db: Session, user: UserCreate): + hashed_password = get_password_hash(user.password) + db_user = User( + email=user.email, + hashed_password=hashed_password + ) + db.add(db_user) + db.commit() + db.refresh(db_user) + return db_user + +async def get_current_user(token: str = Depends(oauth2_scheme), db: Session = Depends(get_db)): + credentials_exception = HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Could not validate credentials", + headers={"WWW-Authenticate": "Bearer"}, + ) + try: + payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) + email: str = payload.get("sub") + if email is None: + raise credentials_exception + token_data = TokenData(email=email) + except JWTError: + raise credentials_exception + user = get_user_by_email(db, email=token_data.email) + if user is None: + raise credentials_exception + return user + +async def get_current_active_user(current_user: User = Depends(get_current_user)): + if not current_user.is_active: + raise HTTPException(status_code=400, detail="Inactive user") + return current_user + +@router.post("/register", response_model=UserSchema) +def register(user: UserCreate, db: Session = Depends(get_db)): + db_user = get_user_by_email(db, email=user.email) + if db_user: + raise HTTPException(status_code=400, detail="Email already registered") + return create_user(db=db, user=user) + +@router.post("/login", response_model=Token) +def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db)): + user = authenticate_user(db, form_data.username, form_data.password) + if not user: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Incorrect email or password", + headers={"WWW-Authenticate": "Bearer"}, + ) + access_token_expires = timedelta(minutes=30) + access_token = create_access_token( + subject=user.email, expires_delta=access_token_expires + ) + return {"access_token": access_token, "token_type": "bearer"} \ No newline at end of file diff --git a/app/api/routes/users.py b/app/api/routes/users.py new file mode 100644 index 0000000..0a85a8e --- /dev/null +++ b/app/api/routes/users.py @@ -0,0 +1,15 @@ +from fastapi import APIRouter, Depends + +from app.api.routes.auth import get_current_active_user +from app.models.user import User +from app.schemas.user import User as UserSchema + +router = APIRouter() + +@router.get("/me", response_model=UserSchema) +def read_users_me(current_user: User = Depends(get_current_active_user)): + return current_user + +@router.get("/profile", response_model=UserSchema) +def get_user_profile(current_user: User = Depends(get_current_active_user)): + return current_user \ No newline at end of file diff --git a/app/core/__init__.py b/app/core/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/core/security.py b/app/core/security.py new file mode 100644 index 0000000..12b3674 --- /dev/null +++ b/app/core/security.py @@ -0,0 +1,30 @@ +import os +from datetime import datetime, timedelta +from typing import Any, Union +from passlib.context import CryptContext +from jose import jwt + +pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") + +SECRET_KEY = os.getenv("SECRET_KEY", "your-secret-key-change-this-in-production") +ALGORITHM = "HS256" +ACCESS_TOKEN_EXPIRE_MINUTES = 30 + +def create_access_token( + subject: Union[str, Any], expires_delta: timedelta = None +) -> str: + if expires_delta: + expire = datetime.utcnow() + expires_delta + else: + expire = datetime.utcnow() + timedelta( + minutes=ACCESS_TOKEN_EXPIRE_MINUTES + ) + to_encode = {"exp": expire, "sub": str(subject)} + encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) + return encoded_jwt + +def verify_password(plain_password: str, hashed_password: str) -> bool: + return pwd_context.verify(plain_password, hashed_password) + +def get_password_hash(password: str) -> str: + return pwd_context.hash(password) \ No newline at end of file diff --git a/app/db/__init__.py b/app/db/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/db/base.py b/app/db/base.py new file mode 100644 index 0000000..7c2377a --- /dev/null +++ b/app/db/base.py @@ -0,0 +1,3 @@ +from sqlalchemy.ext.declarative import declarative_base + +Base = declarative_base() \ No newline at end of file diff --git a/app/db/session.py b/app/db/session.py new file mode 100644 index 0000000..3864851 --- /dev/null +++ b/app/db/session.py @@ -0,0 +1,22 @@ +from pathlib import Path +from sqlalchemy import create_engine +from sqlalchemy.orm import sessionmaker + +DB_DIR = Path("/app/storage/db") +DB_DIR.mkdir(parents=True, exist_ok=True) + +SQLALCHEMY_DATABASE_URL = f"sqlite:///{DB_DIR}/db.sqlite" + +engine = create_engine( + SQLALCHEMY_DATABASE_URL, + connect_args={"check_same_thread": False} +) + +SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) + +def get_db(): + db = SessionLocal() + try: + yield db + finally: + db.close() \ No newline at end of file diff --git a/app/models/__init__.py b/app/models/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/models/user.py b/app/models/user.py new file mode 100644 index 0000000..e72134f --- /dev/null +++ b/app/models/user.py @@ -0,0 +1,13 @@ +from sqlalchemy import Column, Integer, String, Boolean, DateTime +from sqlalchemy.sql import func +from app.db.base import Base + +class User(Base): + __tablename__ = "users" + + id = Column(Integer, primary_key=True, index=True) + email = 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), onupdate=func.now()) \ No newline at end of file diff --git a/app/schemas/__init__.py b/app/schemas/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/schemas/user.py b/app/schemas/user.py new file mode 100644 index 0000000..6f8bed0 --- /dev/null +++ b/app/schemas/user.py @@ -0,0 +1,29 @@ +from pydantic import BaseModel, EmailStr +from typing import Optional +from datetime import datetime + +class UserBase(BaseModel): + email: EmailStr + +class UserCreate(UserBase): + password: str + +class UserLogin(BaseModel): + email: EmailStr + password: str + +class User(UserBase): + id: int + is_active: bool + created_at: datetime + updated_at: Optional[datetime] = None + + class Config: + from_attributes = True + +class Token(BaseModel): + access_token: str + token_type: str + +class TokenData(BaseModel): + email: Optional[str] = None \ No newline at end of file diff --git a/main.py b/main.py new file mode 100644 index 0000000..c52222c --- /dev/null +++ b/main.py @@ -0,0 +1,41 @@ +from fastapi import FastAPI +from fastapi.middleware.cors import CORSMiddleware +from app.api.routes import auth, users +from app.db.session import engine +from app.db.base import Base + +Base.metadata.create_all(bind=engine) + +app = FastAPI( + title="User Authentication Service", + description="A FastAPI service for user authentication", + version="1.0.0", + openapi_url="/openapi.json" +) + +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +app.include_router(auth.router, prefix="/api/v1/auth", tags=["authentication"]) +app.include_router(users.router, prefix="/api/v1/users", tags=["users"]) + +@app.get("/") +async def root(): + return { + "title": "User Authentication Service", + "documentation": "/docs", + "health": "/health" + } + +@app.get("/health") +async def health_check(): + return { + "status": "healthy", + "service": "User Authentication Service", + "version": "1.0.0" + } \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..0d7c3f9 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,8 @@ +fastapi==0.104.1 +uvicorn==0.24.0 +sqlalchemy==2.0.23 +alembic==1.13.0 +python-jose[cryptography]==3.3.0 +passlib[bcrypt]==1.7.4 +python-multipart==0.0.6 +ruff==0.1.6 \ No newline at end of file