From 3110039fdd59cbad2367894943679334534eb3d7 Mon Sep 17 00:00:00 2001 From: Automated Action Date: Mon, 2 Jun 2025 12:23:42 +0000 Subject: [PATCH] Implement user authentication flow with FastAPI and SQLite --- README.md | 134 +++++++++++++++++- alembic.ini | 106 ++++++++++++++ app/__init__.py | 1 + app/api/__init__.py | 1 + app/api/deps.py | 60 ++++++++ app/api/endpoints/__init__.py | 1 + app/api/endpoints/auth.py | 71 ++++++++++ app/api/endpoints/health.py | 30 ++++ app/api/endpoints/users.py | 61 ++++++++ app/api/routes.py | 17 +++ app/core/__init__.py | 1 + app/core/config.py | 37 +++++ app/core/security.py | 31 ++++ app/crud/__init__.py | 1 + app/crud/base.py | 66 +++++++++ app/crud/user.py | 58 ++++++++ app/db/__init__.py | 1 + app/db/base.py | 4 + app/db/base_class.py | 13 ++ app/db/session.py | 22 +++ app/models/__init__.py | 1 + app/models/user.py | 15 ++ app/schemas/__init__.py | 1 + app/schemas/token.py | 12 ++ app/schemas/user.py | 46 ++++++ app/utils/__init__.py | 1 + main.py | 23 +++ migrations/README | 4 + migrations/env.py | 81 +++++++++++ migrations/script.py.mako | 24 ++++ .../versions/0001_create_users_table.py | 41 ++++++ requirements.txt | 10 ++ 32 files changed, 973 insertions(+), 2 deletions(-) create mode 100644 alembic.ini create mode 100644 app/__init__.py create mode 100644 app/api/__init__.py create mode 100644 app/api/deps.py create mode 100644 app/api/endpoints/__init__.py create mode 100644 app/api/endpoints/auth.py create mode 100644 app/api/endpoints/health.py create mode 100644 app/api/endpoints/users.py create mode 100644 app/api/routes.py create mode 100644 app/core/__init__.py create mode 100644 app/core/config.py create mode 100644 app/core/security.py create mode 100644 app/crud/__init__.py create mode 100644 app/crud/base.py create mode 100644 app/crud/user.py create mode 100644 app/db/__init__.py create mode 100644 app/db/base.py create mode 100644 app/db/base_class.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/token.py create mode 100644 app/schemas/user.py create mode 100644 app/utils/__init__.py create mode 100644 main.py create mode 100644 migrations/README create mode 100644 migrations/env.py create mode 100644 migrations/script.py.mako create mode 100644 migrations/versions/0001_create_users_table.py create mode 100644 requirements.txt diff --git a/README.md b/README.md index e8acfba..2c70b96 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,133 @@ -# 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. + +## Features + +- User registration and login +- JWT-based authentication +- Password hashing with bcrypt +- SQLite database with SQLAlchemy ORM +- Alembic migrations +- Protected routes with OAuth2 dependencies +- Health check endpoint + +## Project Structure + +``` +. +├── alembic.ini +├── app +│ ├── api +│ │ ├── deps.py +│ │ ├── endpoints +│ │ │ ├── auth.py +│ │ │ ├── health.py +│ │ │ └── users.py +│ │ └── routes.py +│ ├── core +│ │ ├── config.py +│ │ └── security.py +│ ├── crud +│ │ ├── base.py +│ │ └── user.py +│ ├── db +│ │ ├── base.py +│ │ ├── base_class.py +│ │ └── session.py +│ ├── models +│ │ └── user.py +│ ├── schemas +│ │ ├── token.py +│ │ └── user.py +│ └── utils +├── main.py +├── migrations +│ ├── env.py +│ └── versions +│ └── 0001_create_users_table.py +└── requirements.txt +``` + +## Setup + +1. Clone the repository: + +```bash +git clone +cd userauthenticationservice +``` + +2. Create a virtual environment and install dependencies: + +```bash +python -m venv venv +source venv/bin/activate # On Windows: venv\Scripts\activate +pip install -r requirements.txt +``` + +3. Set up environment variables: + +Create a `.env` file in the root directory with the following content: + +``` +SECRET_KEY=your-secret-key +ACCESS_TOKEN_EXPIRE_MINUTES=10080 # 7 days +``` + +4. Run database migrations: + +```bash +alembic upgrade head +``` + +5. Run the application: + +```bash +uvicorn main:app --reload +``` + +## API Endpoints + +### Authentication + +- **POST /auth/register**: Register a new user + - Request: `{ "email": "user@example.com", "username": "username", "password": "password" }` + - Response: User object + +- **POST /auth/login**: Login and get access token + - Request: Form data with `username` (email) and `password` + - Response: `{ "access_token": "token", "token_type": "bearer" }` + +### Users + +- **GET /users/me**: Get current user details (requires authentication) + - Response: User object + +- **PUT /users/me**: Update current user details (requires authentication) + - Request: `{ "email": "new-email@example.com", "username": "new-username", "password": "new-password" }` + - Response: Updated user object + +### Health Check + +- **GET /health**: Check API health + - Response: `{ "status": "healthy", "database": "healthy" }` + +## Authentication + +The API uses JWT tokens for authentication. To access protected endpoints, include the token in the Authorization header: + +``` +Authorization: Bearer +``` + +## Database + +The application uses SQLite as the database, with the file stored at `/app/storage/db/db.sqlite`. +SQLAlchemy is used as the ORM, and Alembic for database migrations. + +## Environment Variables + +- `SECRET_KEY`: Secret key used for JWT token generation +- `ACCESS_TOKEN_EXPIRE_MINUTES`: Token expiration time in minutes (default: 10080 - 7 days) +- `BACKEND_CORS_ORIGINS`: List of allowed CORS origins (default: "*") \ No newline at end of file diff --git a/alembic.ini b/alembic.ini new file mode 100644 index 0000000..0f85975 --- /dev/null +++ b/alembic.ini @@ -0,0 +1,106 @@ +# A generic, single database configuration. + +[alembic] +# path to migration scripts +script_location = migrations + +# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s +# Uncomment the line below if you want the files to be prepended with date and time +# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file +# for all available tokens +# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s + +# sys.path path, will be prepended to sys.path if present. +# defaults to the current working directory. +prepend_sys_path = . + +# timezone to use when rendering the date within the migration file +# as well as the filename. +# If specified, requires the python-dateutil library that can be +# installed by adding `alembic[tz]` to the pip requirements +# 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. +# The path separator used here should be the separator specified by "version_path_separator" below. +# version_locations = %(here)s/bar:%(here)s/bat:migrations/versions + +# version path separator; As mentioned above, this is the character used to split +# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep. +# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas. +# Valid values for version_path_separator are: +# +# version_path_separator = : +# version_path_separator = ; +# version_path_separator = space +version_path_separator = os # Use os.pathsep. Default configuration used for new projects. + +# the output encoding used when revision files +# are written from script.py.mako +# output_encoding = utf-8 + +# SQLite URL +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 REVISION_SCRIPT_FILENAME + +# 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 \ No newline at end of file diff --git a/app/__init__.py b/app/__init__.py new file mode 100644 index 0000000..628b15f --- /dev/null +++ b/app/__init__.py @@ -0,0 +1 @@ +# Initialize app package \ No newline at end of file diff --git a/app/api/__init__.py b/app/api/__init__.py new file mode 100644 index 0000000..9759f8c --- /dev/null +++ b/app/api/__init__.py @@ -0,0 +1 @@ +# Initialize api package \ No newline at end of file diff --git a/app/api/deps.py b/app/api/deps.py new file mode 100644 index 0000000..5c9fde0 --- /dev/null +++ b/app/api/deps.py @@ -0,0 +1,60 @@ +from typing import Generator + +from fastapi import Depends, HTTPException, status +from fastapi.security import OAuth2PasswordBearer +from jose import jwt +from pydantic import ValidationError +from sqlalchemy.orm import Session + +from app import crud, models, schemas +from app.core.config import settings +from app.db.session import SessionLocal + +reusable_oauth2 = OAuth2PasswordBearer( + tokenUrl="/auth/login" +) + + +def get_db() -> Generator: + try: + db = SessionLocal() + yield db + finally: + db.close() + + +def get_current_user( + db: Session = Depends(get_db), token: str = Depends(reusable_oauth2) +) -> models.User: + try: + payload = jwt.decode( + token, settings.SECRET_KEY, algorithms=["HS256"] + ) + token_data = schemas.TokenPayload(**payload) + except (jwt.JWTError, ValidationError): + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Could not validate credentials", + ) + user = crud.user.get(db, id=token_data.sub) + if not user: + raise HTTPException(status_code=404, detail="User not found") + return user + + +def get_current_active_user( + current_user: models.User = Depends(get_current_user), +) -> models.User: + if not crud.user.is_active(current_user): + raise HTTPException(status_code=400, detail="Inactive user") + return current_user + + +def get_current_active_superuser( + current_user: models.User = Depends(get_current_user), +) -> models.User: + if not crud.user.is_superuser(current_user): + raise HTTPException( + status_code=400, detail="The user doesn't have enough privileges" + ) + return current_user \ No newline at end of file diff --git a/app/api/endpoints/__init__.py b/app/api/endpoints/__init__.py new file mode 100644 index 0000000..7d6e9dd --- /dev/null +++ b/app/api/endpoints/__init__.py @@ -0,0 +1 @@ +# Initialize endpoints package \ No newline at end of file diff --git a/app/api/endpoints/auth.py b/app/api/endpoints/auth.py new file mode 100644 index 0000000..ab4c2b6 --- /dev/null +++ b/app/api/endpoints/auth.py @@ -0,0 +1,71 @@ +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 import crud, schemas +from app.api import deps +from app.core import security +from app.core.config import settings + +router = APIRouter() + + +@router.post("/login", response_model=schemas.Token) +def login_access_token( + db: Session = Depends(deps.get_db), + form_data: OAuth2PasswordRequestForm = Depends(), +) -> Any: + """ + OAuth2 compatible token login, get an access token for future requests + """ + user = crud.user.authenticate( + db, email=form_data.username, password=form_data.password + ) + if not user: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Incorrect email or password", + ) + elif not crud.user.is_active(user): + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Inactive user" + ) + access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES) + return { + "access_token": security.create_access_token( + user.id, expires_delta=access_token_expires + ), + "token_type": "bearer", + } + + +@router.post("/register", response_model=schemas.User, status_code=status.HTTP_201_CREATED) +def register_user( + *, + db: Session = Depends(deps.get_db), + user_in: schemas.UserCreate, +) -> Any: + """ + Register a new user. + """ + user = crud.user.get_by_email(db, email=user_in.email) + if user: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="The user with this email already exists in the system.", + ) + + user = crud.user.get_by_username(db, username=user_in.username) + if user: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="The user with this username already exists in the system.", + ) + + user = crud.user.create(db, obj_in=user_in) + + return user \ No newline at end of file diff --git a/app/api/endpoints/health.py b/app/api/endpoints/health.py new file mode 100644 index 0000000..1a895f5 --- /dev/null +++ b/app/api/endpoints/health.py @@ -0,0 +1,30 @@ +from typing import Dict + +from fastapi import APIRouter, Depends +from sqlalchemy.orm import Session + +from app.api import deps +from app.db.session import engine + +router = APIRouter() + + +@router.get("/health", response_model=Dict[str, str]) +def health_check(db: Session = Depends(deps.get_db)) -> Dict[str, str]: + """ + Health check endpoint. + + Checks database connection and returns service status. + """ + try: + # Try to execute a simple query to verify db connection + with engine.connect() as connection: + connection.execute("SELECT 1") + db_status = "healthy" + except Exception: + db_status = "unhealthy" + + return { + "status": "healthy", + "database": db_status + } \ No newline at end of file diff --git a/app/api/endpoints/users.py b/app/api/endpoints/users.py new file mode 100644 index 0000000..b2804be --- /dev/null +++ b/app/api/endpoints/users.py @@ -0,0 +1,61 @@ +from typing import Any + +from fastapi import APIRouter, Depends, HTTPException, status +from sqlalchemy.orm import Session + +from app import crud, models, schemas +from app.api import deps + +router = APIRouter() + + +@router.post("/", response_model=schemas.User, status_code=status.HTTP_201_CREATED) +def create_user( + *, + db: Session = Depends(deps.get_db), + user_in: schemas.UserCreate, +) -> Any: + """ + Create new user. + """ + user = crud.user.get_by_email(db, email=user_in.email) + if user: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="The user with this email already exists in the system.", + ) + + user = crud.user.get_by_username(db, username=user_in.username) + if user: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="The user with this username already exists in the system.", + ) + + user = crud.user.create(db, obj_in=user_in) + + return user + + +@router.get("/me", response_model=schemas.User) +def read_user_me( + current_user: models.User = Depends(deps.get_current_user), +) -> Any: + """ + Get current user. + """ + return current_user + + +@router.put("/me", response_model=schemas.User) +def update_user_me( + *, + db: Session = Depends(deps.get_db), + user_in: schemas.UserUpdate, + current_user: models.User = Depends(deps.get_current_user), +) -> Any: + """ + Update own user. + """ + user = crud.user.update(db, db_obj=current_user, obj_in=user_in) + return user \ No newline at end of file diff --git a/app/api/routes.py b/app/api/routes.py new file mode 100644 index 0000000..bcf9aa5 --- /dev/null +++ b/app/api/routes.py @@ -0,0 +1,17 @@ +from fastapi import APIRouter, status +from fastapi.responses import JSONResponse + +from app.api.endpoints import auth, users, health + +api_router = APIRouter() + +api_router.include_router(auth.router, prefix="/auth", tags=["authentication"]) +api_router.include_router(users.router, prefix="/users", tags=["users"]) +api_router.include_router(health.router, tags=["health"]) + +@api_router.get("/", include_in_schema=False) +def root(): + return JSONResponse( + status_code=status.HTTP_200_OK, + content={"message": "Welcome to User Authentication Service API"} + ) \ No newline at end of file diff --git a/app/core/__init__.py b/app/core/__init__.py new file mode 100644 index 0000000..74590e1 --- /dev/null +++ b/app/core/__init__.py @@ -0,0 +1 @@ +# Initialize core package \ No newline at end of file diff --git a/app/core/config.py b/app/core/config.py new file mode 100644 index 0000000..6d8d7da --- /dev/null +++ b/app/core/config.py @@ -0,0 +1,37 @@ +import secrets +from pathlib import Path +from typing import List, Union + +from pydantic import AnyHttpUrl, validator +from pydantic_settings import BaseSettings + + +class Settings(BaseSettings): + API_V1_STR: str = "/api/v1" + SECRET_KEY: str = secrets.token_urlsafe(32) + # 60 minutes * 24 hours * 8 days = 8 days + ACCESS_TOKEN_EXPIRE_MINUTES: int = 60 * 24 * 8 + + # CORS + BACKEND_CORS_ORIGINS: List[AnyHttpUrl] = [] + + @validator("BACKEND_CORS_ORIGINS", pre=True) + def assemble_cors_origins(cls, v: Union[str, List[str]]) -> Union[List[str], str]: + if isinstance(v, str) and not v.startswith("["): + return [i.strip() for i in v.split(",")] + elif isinstance(v, (list, str)): + return v + raise ValueError(v) + + PROJECT_NAME: str = "User Authentication Service" + + # Database + DB_DIR: Path = Path("/app") / "storage" / "db" + SQLALCHEMY_DATABASE_URL: str = f"sqlite:///{DB_DIR}/db.sqlite" + + class Config: + case_sensitive = True + env_file = ".env" + + +settings = Settings() \ No newline at end of file diff --git a/app/core/security.py b/app/core/security.py new file mode 100644 index 0000000..6693013 --- /dev/null +++ b/app/core/security.py @@ -0,0 +1,31 @@ +from datetime import datetime, timedelta +from typing import Any, Union + +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: Union[str, Any], expires_delta: timedelta = None +) -> str: + 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: + 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/crud/__init__.py b/app/crud/__init__.py new file mode 100644 index 0000000..c8d5f19 --- /dev/null +++ b/app/crud/__init__.py @@ -0,0 +1 @@ +# Initialize crud package \ No newline at end of file diff --git a/app/crud/base.py b/app/crud/base.py new file mode 100644 index 0000000..d6e21a4 --- /dev/null +++ b/app/crud/base.py @@ -0,0 +1,66 @@ +from typing import Any, Dict, Generic, List, Optional, Type, TypeVar, Union + +from fastapi.encoders import jsonable_encoder +from pydantic import BaseModel +from sqlalchemy.orm import Session + +from app.db.base_class import Base + +ModelType = TypeVar("ModelType", bound=Base) +CreateSchemaType = TypeVar("CreateSchemaType", bound=BaseModel) +UpdateSchemaType = TypeVar("UpdateSchemaType", bound=BaseModel) + + +class CRUDBase(Generic[ModelType, CreateSchemaType, UpdateSchemaType]): + def __init__(self, model: Type[ModelType]): + """ + CRUD object with default methods to Create, Read, Update, Delete (CRUD). + + **Parameters** + + * `model`: A SQLAlchemy model class + * `schema`: A Pydantic model (schema) class + """ + self.model = model + + def get(self, db: Session, id: Any) -> Optional[ModelType]: + return db.query(self.model).filter(self.model.id == id).first() + + def get_multi( + self, db: Session, *, skip: int = 0, limit: int = 100 + ) -> List[ModelType]: + return db.query(self.model).offset(skip).limit(limit).all() + + def create(self, db: Session, *, obj_in: CreateSchemaType) -> ModelType: + obj_in_data = jsonable_encoder(obj_in) + db_obj = self.model(**obj_in_data) # type: ignore + db.add(db_obj) + db.commit() + db.refresh(db_obj) + return db_obj + + def update( + self, + db: Session, + *, + db_obj: ModelType, + obj_in: Union[UpdateSchemaType, Dict[str, Any]] + ) -> ModelType: + obj_data = jsonable_encoder(db_obj) + if isinstance(obj_in, dict): + update_data = obj_in + else: + update_data = obj_in.dict(exclude_unset=True) + for field in obj_data: + if field in update_data: + setattr(db_obj, field, update_data[field]) + db.add(db_obj) + db.commit() + db.refresh(db_obj) + return db_obj + + def remove(self, db: Session, *, id: int) -> ModelType: + obj = db.query(self.model).get(id) + db.delete(obj) + db.commit() + return obj \ No newline at end of file diff --git a/app/crud/user.py b/app/crud/user.py new file mode 100644 index 0000000..f7e75d5 --- /dev/null +++ b/app/crud/user.py @@ -0,0 +1,58 @@ +from typing import Any, Dict, Optional, Union + +from sqlalchemy.orm import Session + +from app.core.security import get_password_hash, verify_password +from app.crud.base import CRUDBase +from app.models.user import User +from app.schemas.user import UserCreate, UserUpdate + + +class CRUDUser(CRUDBase[User, UserCreate, UserUpdate]): + def get_by_email(self, db: Session, *, email: str) -> Optional[User]: + return db.query(User).filter(User.email == email).first() + + def get_by_username(self, db: Session, *, username: str) -> Optional[User]: + return db.query(User).filter(User.username == username).first() + + def create(self, db: Session, *, obj_in: UserCreate) -> User: + db_obj = User( + email=obj_in.email, + username=obj_in.username, + hashed_password=get_password_hash(obj_in.password), + is_superuser=obj_in.is_superuser, + ) + db.add(db_obj) + db.commit() + db.refresh(db_obj) + return db_obj + + def update( + self, db: Session, *, db_obj: User, obj_in: Union[UserUpdate, Dict[str, Any]] + ) -> User: + if isinstance(obj_in, dict): + update_data = obj_in + else: + update_data = obj_in.dict(exclude_unset=True) + if update_data.get("password"): + hashed_password = get_password_hash(update_data["password"]) + del update_data["password"] + update_data["hashed_password"] = hashed_password + return super().update(db, db_obj=db_obj, obj_in=update_data) + + def authenticate(self, db: Session, *, email: str, password: str) -> Optional[User]: + user = self.get_by_email(db, email=email) + if not user: + return None + if not verify_password(password, user.hashed_password): + return None + return user + + def is_active(self, user: User) -> bool: + return user.is_active + + def is_superuser(self, user: User) -> bool: + return user.is_superuser + + +user = CRUDUser(User) \ No newline at end of file diff --git a/app/db/__init__.py b/app/db/__init__.py new file mode 100644 index 0000000..211657e --- /dev/null +++ b/app/db/__init__.py @@ -0,0 +1 @@ +# Initialize db package \ No newline at end of file diff --git a/app/db/base.py b/app/db/base.py new file mode 100644 index 0000000..f002e1b --- /dev/null +++ b/app/db/base.py @@ -0,0 +1,4 @@ +# Import all the models, so that Base has them before being +# imported by Alembic +from app.db.base_class import Base # noqa +from app.models.user import User # noqa \ No newline at end of file diff --git a/app/db/base_class.py b/app/db/base_class.py new file mode 100644 index 0000000..d692f60 --- /dev/null +++ b/app/db/base_class.py @@ -0,0 +1,13 @@ +from typing import Any + +from sqlalchemy.ext.declarative import as_declarative, declared_attr + + +@as_declarative() +class Base: + id: Any + __name__: str + # Generate __tablename__ automatically + @declared_attr + def __tablename__(cls) -> str: + return cls.__name__.lower() \ No newline at end of file diff --git a/app/db/session.py b/app/db/session.py new file mode 100644 index 0000000..ae40cbf --- /dev/null +++ b/app/db/session.py @@ -0,0 +1,22 @@ +from sqlalchemy import create_engine +from sqlalchemy.orm import sessionmaker + +from app.core.config import settings + +# Create the database directory if it doesn't exist +settings.DB_DIR.mkdir(parents=True, exist_ok=True) + +engine = create_engine( + settings.SQLALCHEMY_DATABASE_URL, + connect_args={"check_same_thread": False} +) +SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) + + +# Dependency +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..5387322 --- /dev/null +++ b/app/models/__init__.py @@ -0,0 +1 @@ +# Initialize models package \ No newline at end of file diff --git a/app/models/user.py b/app/models/user.py new file mode 100644 index 0000000..141ac4d --- /dev/null +++ b/app/models/user.py @@ -0,0 +1,15 @@ +from datetime import datetime +from sqlalchemy import Boolean, Column, Integer, String, DateTime + +from app.db.base_class import Base + + +class User(Base): + 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) + is_superuser = Column(Boolean(), default=False) + created_at = Column(DateTime, default=datetime.utcnow) + updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow) \ No newline at end of file diff --git a/app/schemas/__init__.py b/app/schemas/__init__.py new file mode 100644 index 0000000..2bad002 --- /dev/null +++ b/app/schemas/__init__.py @@ -0,0 +1 @@ +# Initialize schemas package \ No newline at end of file diff --git a/app/schemas/token.py b/app/schemas/token.py new file mode 100644 index 0000000..69541e2 --- /dev/null +++ b/app/schemas/token.py @@ -0,0 +1,12 @@ +from typing import Optional + +from pydantic import BaseModel + + +class Token(BaseModel): + access_token: str + token_type: str + + +class TokenPayload(BaseModel): + sub: Optional[int] = None \ No newline at end of file diff --git a/app/schemas/user.py b/app/schemas/user.py new file mode 100644 index 0000000..1ae14a9 --- /dev/null +++ b/app/schemas/user.py @@ -0,0 +1,46 @@ +from datetime import datetime +from typing import Optional + +from pydantic import BaseModel, EmailStr, Field + + +# Shared properties +class UserBase(BaseModel): + email: Optional[EmailStr] = None + username: Optional[str] = None + is_active: Optional[bool] = True + is_superuser: bool = False + + +# Properties to receive via API on creation +class UserCreate(UserBase): + email: EmailStr + username: str + password: str = Field(..., min_length=8) + + +# Properties to receive via API on update +class UserUpdate(UserBase): + password: Optional[str] = Field(None, min_length=8) + + +# Properties shared by models stored in DB +class UserInDBBase(UserBase): + id: int + email: EmailStr + username: str + created_at: datetime + updated_at: datetime + + class Config: + from_attributes = True + + +# Additional properties to return via API +class User(UserInDBBase): + pass + + +# Additional properties stored in DB +class UserInDB(UserInDBBase): + hashed_password: str \ No newline at end of file diff --git a/app/utils/__init__.py b/app/utils/__init__.py new file mode 100644 index 0000000..b014dde --- /dev/null +++ b/app/utils/__init__.py @@ -0,0 +1 @@ +# Initialize utils package \ No newline at end of file diff --git a/main.py b/main.py new file mode 100644 index 0000000..8b87c2c --- /dev/null +++ b/main.py @@ -0,0 +1,23 @@ +from fastapi import FastAPI +from fastapi.middleware.cors import CORSMiddleware + +from app.core.config import settings +from app.api.routes import api_router + +app = FastAPI( + title=settings.PROJECT_NAME, + openapi_url="/openapi.json", + docs_url="/docs", + redoc_url="/redoc", +) + +# Set all CORS enabled origins +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +app.include_router(api_router) \ No newline at end of file diff --git a/migrations/README b/migrations/README new file mode 100644 index 0000000..6a094a2 --- /dev/null +++ b/migrations/README @@ -0,0 +1,4 @@ +Generic single-database configuration with SQLite. + +For more information on Alembic, please see: +https://alembic.sqlalchemy.org/en/latest/ \ No newline at end of file diff --git a/migrations/env.py b/migrations/env.py new file mode 100644 index 0000000..f062099 --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,81 @@ +from logging.config import fileConfig + +from sqlalchemy import engine_from_config +from sqlalchemy import pool + +from alembic import context +from app.db.base import Base + +# 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 +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(): + """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"}, + render_as_batch=True, + ) + + with context.begin_transaction(): + context.run_migrations() + + +def run_migrations_online(): + """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, + ) + + 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/migrations/script.py.mako b/migrations/script.py.mako new file mode 100644 index 0000000..1e4564e --- /dev/null +++ b/migrations/script.py.mako @@ -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(): + ${upgrades if upgrades else "pass"} + + +def downgrade(): + ${downgrades if downgrades else "pass"} \ No newline at end of file diff --git a/migrations/versions/0001_create_users_table.py b/migrations/versions/0001_create_users_table.py new file mode 100644 index 0000000..cb336de --- /dev/null +++ b/migrations/versions/0001_create_users_table.py @@ -0,0 +1,41 @@ +"""Create users table + +Revision ID: 0001 +Revises: +Create Date: 2023-09-12 12:00:00.000000 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '0001' +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade(): + op.create_table( + 'user', + 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(), nullable=True, default=True), + sa.Column('is_superuser', sa.Boolean(), nullable=True, default=False), + sa.Column('created_at', sa.DateTime(), nullable=True), + sa.Column('updated_at', sa.DateTime(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_user_email'), 'user', ['email'], unique=True) + op.create_index(op.f('ix_user_id'), 'user', ['id'], unique=False) + op.create_index(op.f('ix_user_username'), 'user', ['username'], unique=True) + + +def downgrade(): + op.drop_index(op.f('ix_user_username'), table_name='user') + op.drop_index(op.f('ix_user_id'), table_name='user') + op.drop_index(op.f('ix_user_email'), table_name='user') + op.drop_table('user') \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..7731bb5 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,10 @@ +fastapi>=0.95.0,<0.96.0 +uvicorn>=0.22.0,<0.23.0 +sqlalchemy>=2.0.0,<2.1.0 +alembic>=1.10.0,<1.11.0 +pydantic>=2.0.0,<3.0.0 +pydantic-settings>=2.0.0,<3.0.0 +python-jose[cryptography]>=3.3.0,<3.4.0 +passlib[bcrypt]>=1.7.4,<1.8.0 +python-multipart>=0.0.5,<0.1.0 +ruff>=0.0.262,<0.1.0 \ No newline at end of file