From f57e68d64e2e47fa75ce834d7fab75b97917181a Mon Sep 17 00:00:00 2001 From: Automated Action Date: Mon, 2 Jun 2025 19:17:05 +0000 Subject: [PATCH] Implement Task Manager API with FastAPI and SQLite --- README.md | 139 +++++++++++++- alembic.ini | 111 +++++++++++ app/__init__.py | 0 app/api/__init__.py | 0 app/api/deps.py | 59 ++++++ app/api/endpoints/__init__.py | 0 app/api/endpoints/health.py | 32 ++++ app/api/endpoints/login.py | 42 +++++ app/api/endpoints/tasks.py | 186 +++++++++++++++++++ app/api/endpoints/users.py | 159 ++++++++++++++++ app/api/routes.py | 9 + app/core/__init__.py | 0 app/core/config.py | 44 +++++ app/core/security.py | 33 ++++ app/crud/__init__.py | 4 + app/crud/base.py | 66 +++++++ app/crud/crud_task.py | 104 +++++++++++ app/crud/crud_user.py | 58 ++++++ app/db/__init__.py | 0 app/db/init_db.py | 28 +++ app/db/session.py | 28 +++ app/models/__init__.py | 4 + app/models/task.py | 38 ++++ app/models/user.py | 21 +++ app/schemas/__init__.py | 9 + app/schemas/task.py | 51 +++++ app/schemas/token.py | 12 ++ app/schemas/user.py | 42 +++++ app/utils/__init__.py | 0 app/utils/init_db.py | 39 ++++ main.py | 42 +++++ migrations/__init__.py | 0 migrations/env.py | 84 +++++++++ migrations/script.py.mako | 26 +++ migrations/versions/001_initial_migration.py | 70 +++++++ requirements.txt | 12 ++ 36 files changed, 1550 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/health.py create mode 100644 app/api/endpoints/login.py create mode 100644 app/api/endpoints/tasks.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/crud_task.py create mode 100644 app/crud/crud_user.py create mode 100644 app/db/__init__.py create mode 100644 app/db/init_db.py create mode 100644 app/db/session.py create mode 100644 app/models/__init__.py create mode 100644 app/models/task.py create mode 100644 app/models/user.py create mode 100644 app/schemas/__init__.py create mode 100644 app/schemas/task.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 app/utils/init_db.py create mode 100644 main.py create mode 100644 migrations/__init__.py create mode 100644 migrations/env.py create mode 100644 migrations/script.py.mako create mode 100644 migrations/versions/001_initial_migration.py create mode 100644 requirements.txt diff --git a/README.md b/README.md index e8acfba..079411d 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,138 @@ -# FastAPI Application +# Task Manager API -This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform. +A RESTful API for managing tasks and user accounts. Built with FastAPI, SQLAlchemy, and SQLite. + +## Features + +- **User Management**: Registration, authentication, and profile management +- **Task Management**: Create, read, update, and delete tasks +- **Task Status Tracking**: Track tasks as todo, in-progress, or done +- **Task Prioritization**: Set task priorities as low, medium, or high +- **API Documentation**: Interactive API documentation with Swagger UI and ReDoc + +## Technology Stack + +- **FastAPI**: High-performance web framework for building APIs +- **SQLAlchemy**: SQL toolkit and Object-Relational Mapping (ORM) +- **SQLite**: File-based database +- **Alembic**: Database migration tool +- **Pydantic**: Data validation and settings management +- **JWT**: JSON Web Tokens for authentication +- **Uvicorn**: ASGI server for running the application + +## Project Structure + +``` +task-manager-api/ +├── app/ +│ ├── api/ +│ │ ├── endpoints/ # API endpoint modules +│ │ │ ├── health.py # Health check endpoint +│ │ │ ├── login.py # Login endpoints +│ │ │ ├── tasks.py # Task management endpoints +│ │ │ └── users.py # User management endpoints +│ │ ├── deps.py # Dependency injection functions +│ │ └── routes.py # API router configuration +│ ├── core/ +│ │ ├── config.py # Application configuration +│ │ └── security.py # Security utilities +│ ├── crud/ # CRUD operations +│ │ ├── base.py # Base CRUD class +│ │ ├── crud_task.py # Task CRUD operations +│ │ └── crud_user.py # User CRUD operations +│ ├── db/ +│ │ └── session.py # Database session setup +│ ├── models/ # SQLAlchemy models +│ │ ├── task.py # Task model +│ │ └── user.py # User model +│ └── schemas/ # Pydantic schemas +│ ├── task.py # Task schemas +│ ├── token.py # Token schemas +│ └── user.py # User schemas +├── migrations/ # Alembic migrations +│ ├── versions/ # Migration versions +│ ├── env.py # Migration environment +│ └── script.py.mako # Migration script template +├── alembic.ini # Alembic configuration +├── main.py # Application entry point +└── requirements.txt # Project dependencies +``` + +## Getting Started + +### Prerequisites + +- Python 3.8+ +- pip (Python package installer) + +### Installation + +1. Clone the repository +```bash +git clone +cd task-manager-api +``` + +2. Install dependencies +```bash +pip install -r requirements.txt +``` + +3. Set up environment variables +```bash +# Create a .env file in the project root +touch .env + +# Add the following variables to the .env file +SECRET_KEY=your-secret-key +``` + +4. Run database migrations +```bash +alembic upgrade head +``` + +5. Start the server +```bash +uvicorn main:app --reload +``` + +The API will be available at http://localhost:8000. + +## API Documentation + +Once the server is running, you can access the API documentation at: + +- Swagger UI: http://localhost:8000/docs +- ReDoc: http://localhost:8000/redoc + +## API Endpoints + +### Authentication + +- `POST /api/v1/login/access-token` - Get JWT access token + +### Users + +- `POST /api/v1/users/open` - Register a new user +- `GET /api/v1/users/me` - Get current user +- `PUT /api/v1/users/me` - Update current user + +### Tasks + +- `GET /api/v1/tasks` - List all tasks for the current user +- `POST /api/v1/tasks` - Create a new task +- `GET /api/v1/tasks/{task_id}` - Get task by ID +- `PUT /api/v1/tasks/{task_id}` - Update task +- `DELETE /api/v1/tasks/{task_id}` - Delete task +- `POST /api/v1/tasks/{task_id}/complete` - Mark task as complete +- `POST /api/v1/tasks/{task_id}/incomplete` - Mark task as incomplete +- `POST /api/v1/tasks/{task_id}/status/{status}` - Update task status + +### Health Check + +- `GET /health` - API health check + +## License + +This project is licensed under the MIT License - see the LICENSE file for details. \ No newline at end of file diff --git a/alembic.ini b/alembic.ini new file mode 100644 index 0000000..d7e2b52 --- /dev/null +++ b/alembic.ini @@ -0,0 +1,111 @@ +# 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. + +# set to 'true' to search source files recursively +# in each "version_locations" directory +# new in Alembic version 1.10 +# recursive_version_locations = false + +# the output encoding used when revision files +# are written from script.py.mako +# output_encoding = utf-8 + +# SQLite URL - This uses absolute path as required +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..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/deps.py b/app/api/deps.py new file mode 100644 index 0000000..49ffd3c --- /dev/null +++ b/app/api/deps.py @@ -0,0 +1,59 @@ + +from fastapi import Depends, HTTPException, status +from fastapi.security import OAuth2PasswordBearer +from jose import jwt, JWTError +from pydantic import ValidationError +from sqlalchemy.orm import Session + +from app import models, schemas, crud +from app.core import security +from app.core.config import settings +from app.db.session import get_db + +oauth2_scheme = OAuth2PasswordBearer( + tokenUrl=f"{settings.API_V1_STR}/login/access-token" +) + + +def get_current_user( + db: Session = Depends(get_db), token: str = Depends(oauth2_scheme) +) -> models.User: + try: + payload = jwt.decode( + token, settings.SECRET_KEY, algorithms=[security.ALGORITHM] + ) + token_data = schemas.TokenPayload(**payload) + except (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=status.HTTP_404_NOT_FOUND, + detail="User not found" + ) + return user + + +def get_current_active_user( + current_user: models.User = Depends(get_current_user), +) -> models.User: + if not current_user.is_active: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="Inactive user" + ) + return current_user + + +def get_current_active_superuser( + current_user: models.User = Depends(get_current_user), +) -> models.User: + if not current_user.is_superuser: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + 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..e69de29 diff --git a/app/api/endpoints/health.py b/app/api/endpoints/health.py new file mode 100644 index 0000000..28b1095 --- /dev/null +++ b/app/api/endpoints/health.py @@ -0,0 +1,32 @@ +from typing import Dict, Any +from fastapi import APIRouter + +from app.db.session import engine + +router = APIRouter() + + +@router.get("/health", response_model=Dict[str, Any]) +def health_check() -> Dict[str, Any]: + """ + Health check endpoint to verify the API is running correctly. + """ + health_status = { + "status": "ok", + "api_version": "0.1.0", + "db_connection": check_db_connection(), + } + return health_status + + +def check_db_connection() -> bool: + """ + Check if the database connection is working. + """ + try: + # Try to connect to the database + with engine.connect() as conn: + result = conn.execute("SELECT 1").fetchone() + return result is not None + except Exception: + return False \ No newline at end of file diff --git a/app/api/endpoints/login.py b/app/api/endpoints/login.py new file mode 100644 index 0000000..7c0e374 --- /dev/null +++ b/app/api/endpoints/login.py @@ -0,0 +1,42 @@ +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/access-token", 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", + ) + if 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", + } \ No newline at end of file diff --git a/app/api/endpoints/tasks.py b/app/api/endpoints/tasks.py new file mode 100644 index 0000000..19c1465 --- /dev/null +++ b/app/api/endpoints/tasks.py @@ -0,0 +1,186 @@ +from typing import Any, List, Optional + +from fastapi import APIRouter, Depends, HTTPException, status +from sqlalchemy.orm import Session + +from app import crud, models, schemas +from app.api import deps +from app.models.task import TaskStatus + +router = APIRouter() + + +@router.get("/", response_model=List[schemas.Task]) +def read_tasks( + db: Session = Depends(deps.get_db), + skip: int = 0, + limit: int = 100, + status: Optional[TaskStatus] = None, + completed: Optional[bool] = None, + current_user: models.User = Depends(deps.get_current_active_user), +) -> Any: + """ + Retrieve tasks. + """ + if status: + tasks = crud.task.get_multi_by_status( + db=db, owner_id=current_user.id, status=status, skip=skip, limit=limit + ) + elif completed is not None: + tasks = crud.task.get_multi_by_completion( + db=db, owner_id=current_user.id, is_completed=completed, skip=skip, limit=limit + ) + else: + tasks = crud.task.get_multi_by_owner( + db=db, owner_id=current_user.id, skip=skip, limit=limit + ) + return tasks + + +@router.post("/", response_model=schemas.Task) +def create_task( + *, + db: Session = Depends(deps.get_db), + task_in: schemas.TaskCreate, + current_user: models.User = Depends(deps.get_current_active_user), +) -> Any: + """ + Create new task. + """ + task = crud.task.create_with_owner(db=db, obj_in=task_in, owner_id=current_user.id) + return task + + +@router.get("/{task_id}", response_model=schemas.Task) +def read_task( + *, + db: Session = Depends(deps.get_db), + task_id: int, + current_user: models.User = Depends(deps.get_current_active_user), +) -> Any: + """ + Get task by ID. + """ + task = crud.task.get(db=db, id=task_id) + if not task: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Task not found" + ) + if task.owner_id != current_user.id: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Not enough permissions" + ) + return task + + +@router.put("/{task_id}", response_model=schemas.Task) +def update_task( + *, + db: Session = Depends(deps.get_db), + task_id: int, + task_in: schemas.TaskUpdate, + current_user: models.User = Depends(deps.get_current_active_user), +) -> Any: + """ + Update a task. + """ + task = crud.task.get(db=db, id=task_id) + if not task: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Task not found" + ) + if task.owner_id != current_user.id: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Not enough permissions" + ) + task = crud.task.update(db=db, db_obj=task, obj_in=task_in) + return task + + +@router.delete("/{task_id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None) +def delete_task( + *, + db: Session = Depends(deps.get_db), + task_id: int, + current_user: models.User = Depends(deps.get_current_active_user), +) -> None: + """ + Delete a task. + """ + task = crud.task.get(db=db, id=task_id) + if not task: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Task not found" + ) + if task.owner_id != current_user.id: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Not enough permissions" + ) + crud.task.remove(db=db, id=task_id) + return None + + +@router.post("/{task_id}/complete", response_model=schemas.Task) +def mark_task_complete( + *, + db: Session = Depends(deps.get_db), + task_id: int, + current_user: models.User = Depends(deps.get_current_active_user), +) -> Any: + """ + Mark a task as complete. + """ + task = crud.task.mark_as_complete(db=db, task_id=task_id, user=current_user) + if not task: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Task not found" + ) + return task + + +@router.post("/{task_id}/incomplete", response_model=schemas.Task) +def mark_task_incomplete( + *, + db: Session = Depends(deps.get_db), + task_id: int, + current_user: models.User = Depends(deps.get_current_active_user), +) -> Any: + """ + Mark a task as incomplete. + """ + task = crud.task.mark_as_incomplete(db=db, task_id=task_id, user=current_user) + if not task: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Task not found" + ) + return task + + +@router.post("/{task_id}/status/{status}", response_model=schemas.Task) +def update_task_status( + *, + db: Session = Depends(deps.get_db), + task_id: int, + status: TaskStatus, + current_user: models.User = Depends(deps.get_current_active_user), +) -> Any: + """ + Update task status. + """ + task = crud.task.update_task_status( + db=db, task_id=task_id, user=current_user, status=status + ) + if not task: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Task not found" + ) + return task \ 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..97705d8 --- /dev/null +++ b/app/api/endpoints/users.py @@ -0,0 +1,159 @@ +from typing import Any, List + +from fastapi import APIRouter, Depends, HTTPException, status +from sqlalchemy.orm import Session + +from app import crud, models, schemas +from app.api import deps +from app.core.config import settings + +router = APIRouter() + + +@router.get("/", response_model=List[schemas.User]) +def read_users( + db: Session = Depends(deps.get_db), + skip: int = 0, + limit: int = 100, + current_user: models.User = Depends(deps.get_current_active_superuser), +) -> Any: + """ + Retrieve users. Only accessible to superusers. + """ + users = crud.user.get_multi(db, skip=skip, limit=limit) + return users + + +@router.post("/", response_model=schemas.User) +def create_user( + *, + db: Session = Depends(deps.get_db), + user_in: schemas.UserCreate, + current_user: models.User = Depends(deps.get_current_active_superuser), +) -> Any: + """ + Create new user. Only accessible to superusers. + """ + user = crud.user.get_by_email(db, email=user_in.email) + if user: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="A 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="A user with this username already exists in the system.", + ) + user = crud.user.create(db, obj_in=user_in) + return user + + +@router.post("/open", response_model=schemas.User) +def create_user_open( + *, + db: Session = Depends(deps.get_db), + user_in: schemas.UserCreate, +) -> Any: + """ + Create new user without the need to be logged in. + """ + if not settings.USERS_OPEN_REGISTRATION: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Open user registration is forbidden on this server", + ) + user = crud.user.get_by_email(db, email=user_in.email) + if user: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="A 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="A 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_active_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_active_user), +) -> Any: + """ + Update own user information. + """ + if user_in.email and user_in.email != current_user.email: + user = crud.user.get_by_email(db, email=user_in.email) + if user: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="A user with this email already exists in the system", + ) + if user_in.username and user_in.username != current_user.username: + user = crud.user.get_by_username(db, username=user_in.username) + if user: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="A user with this username already exists in the system", + ) + user = crud.user.update(db, db_obj=current_user, obj_in=user_in) + return user + + +@router.get("/{user_id}", response_model=schemas.User) +def read_user_by_id( + user_id: int, + current_user: models.User = Depends(deps.get_current_active_user), + db: Session = Depends(deps.get_db), +) -> Any: + """ + Get a specific user by id. + """ + user = crud.user.get(db, id=user_id) + if user == current_user: + return user + if not crud.user.is_superuser(current_user): + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="The user doesn't have enough privileges", + ) + return user + + +@router.put("/{user_id}", response_model=schemas.User) +def update_user( + *, + db: Session = Depends(deps.get_db), + user_id: int, + user_in: schemas.UserUpdate, + current_user: models.User = Depends(deps.get_current_active_superuser), +) -> Any: + """ + Update a user. Only accessible to superusers. + """ + user = crud.user.get(db, id=user_id) + if not user: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="The user with this id does not exist in the system", + ) + user = crud.user.update(db, db_obj=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..38ff306 --- /dev/null +++ b/app/api/routes.py @@ -0,0 +1,9 @@ +from fastapi import APIRouter + +from app.api.endpoints import tasks, users, login, health + +api_router = APIRouter() +api_router.include_router(login.router, tags=["login"]) +api_router.include_router(users.router, prefix="/users", tags=["users"]) +api_router.include_router(tasks.router, prefix="/tasks", tags=["tasks"]) +api_router.include_router(health.router, tags=["health"]) \ 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/config.py b/app/core/config.py new file mode 100644 index 0000000..75ec669 --- /dev/null +++ b/app/core/config.py @@ -0,0 +1,44 @@ +import secrets +from pathlib import Path +from typing import List, Union + +from pydantic import EmailStr, validator +from pydantic_settings import BaseSettings + + +class Settings(BaseSettings): + PROJECT_NAME: str = "Task Manager API" + 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 Configuration + BACKEND_CORS_ORIGINS: List[str] = ["*"] + + @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) + + # Database Configuration + DB_DIR: Path = Path("/app") / "storage" / "db" + SQLALCHEMY_DATABASE_URL: str = f"sqlite:///{DB_DIR}/db.sqlite" + + # Users + USERS_OPEN_REGISTRATION: bool = True + + # First Superuser + FIRST_SUPERUSER_EMAIL: EmailStr = "admin@example.com" + FIRST_SUPERUSER_USERNAME: str = "admin" + FIRST_SUPERUSER_PASSWORD: str = "admin123" + + 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..53ed719 --- /dev/null +++ b/app/core/security.py @@ -0,0 +1,33 @@ +from datetime import datetime, timedelta +from typing import Any, Union, Optional + +from jose import jwt +from passlib.context import CryptContext + +from app.core.config import settings + +pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") + +ALGORITHM = "HS256" + + +def create_access_token( + subject: Union[str, Any], expires_delta: Optional[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=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/crud/__init__.py b/app/crud/__init__.py new file mode 100644 index 0000000..bac4a51 --- /dev/null +++ b/app/crud/__init__.py @@ -0,0 +1,4 @@ +from app.crud.crud_user import user +from app.crud.crud_task import task + +__all__ = ["user", "task"] \ No newline at end of file diff --git a/app/crud/base.py b/app/crud/base.py new file mode 100644 index 0000000..1ceea82 --- /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.session 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) + 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.model_dump(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/crud_task.py b/app/crud/crud_task.py new file mode 100644 index 0000000..e9f21b0 --- /dev/null +++ b/app/crud/crud_task.py @@ -0,0 +1,104 @@ +from typing import List, Optional +from sqlalchemy.orm import Session + +from app.crud.base import CRUDBase +from app.models.task import Task, TaskStatus +from app.models.user import User +from app.schemas.task import TaskCreate, TaskUpdate + + +class CRUDTask(CRUDBase[Task, TaskCreate, TaskUpdate]): + def create_with_owner( + self, db: Session, *, obj_in: TaskCreate, owner_id: int + ) -> Task: + obj_in_data = obj_in.model_dump() + db_obj = Task(**obj_in_data, owner_id=owner_id) + db.add(db_obj) + db.commit() + db.refresh(db_obj) + return db_obj + + def get_multi_by_owner( + self, db: Session, *, owner_id: int, skip: int = 0, limit: int = 100 + ) -> List[Task]: + return ( + db.query(self.model) + .filter(Task.owner_id == owner_id) + .offset(skip) + .limit(limit) + .all() + ) + + def get_multi_by_status( + self, db: Session, *, owner_id: int, status: TaskStatus, skip: int = 0, limit: int = 100 + ) -> List[Task]: + return ( + db.query(self.model) + .filter(Task.owner_id == owner_id, Task.status == status) + .offset(skip) + .limit(limit) + .all() + ) + + def get_multi_by_completion( + self, db: Session, *, owner_id: int, is_completed: bool, skip: int = 0, limit: int = 100 + ) -> List[Task]: + return ( + db.query(self.model) + .filter(Task.owner_id == owner_id, Task.is_completed == is_completed) + .offset(skip) + .limit(limit) + .all() + ) + + def mark_as_complete( + self, db: Session, *, task_id: int, user: User + ) -> Optional[Task]: + task = db.query(self.model).filter( + Task.id == task_id, Task.owner_id == user.id + ).first() + if not task: + return None + task.is_completed = True + task.status = TaskStatus.DONE + db.add(task) + db.commit() + db.refresh(task) + return task + + def mark_as_incomplete( + self, db: Session, *, task_id: int, user: User + ) -> Optional[Task]: + task = db.query(self.model).filter( + Task.id == task_id, Task.owner_id == user.id + ).first() + if not task: + return None + task.is_completed = False + if task.status == TaskStatus.DONE: + task.status = TaskStatus.IN_PROGRESS + db.add(task) + db.commit() + db.refresh(task) + return task + + def update_task_status( + self, db: Session, *, task_id: int, user: User, status: TaskStatus + ) -> Optional[Task]: + task = db.query(self.model).filter( + Task.id == task_id, Task.owner_id == user.id + ).first() + if not task: + return None + task.status = status + if status == TaskStatus.DONE: + task.is_completed = True + else: + task.is_completed = False + db.add(task) + db.commit() + db.refresh(task) + return task + + +task = CRUDTask(Task) \ No newline at end of file diff --git a/app/crud/crud_user.py b/app/crud/crud_user.py new file mode 100644 index 0000000..92e4d5b --- /dev/null +++ b/app/crud/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.model_dump(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..e69de29 diff --git a/app/db/init_db.py b/app/db/init_db.py new file mode 100644 index 0000000..97ee8f5 --- /dev/null +++ b/app/db/init_db.py @@ -0,0 +1,28 @@ +import logging +from sqlalchemy.orm import Session + +from app import crud, schemas +from app.core.config import settings +from app.db.session import Base, engine + +logger = logging.getLogger(__name__) + + +def init_db(db: Session) -> None: + """Initialize the database, creating tables and initial data.""" + # Create tables if they don't exist + Base.metadata.create_all(bind=engine) + + # Create initial superuser if needed + user = crud.user.get_by_email(db, email=settings.FIRST_SUPERUSER_EMAIL) + if not user: + user_in = schemas.UserCreate( + email=settings.FIRST_SUPERUSER_EMAIL, + username=settings.FIRST_SUPERUSER_USERNAME, + password=settings.FIRST_SUPERUSER_PASSWORD, + is_superuser=True, + ) + user = crud.user.create(db, obj_in=user_in) + logger.info(f"Superuser {user.email} created successfully") + else: + logger.info("Superuser already exists, skipping creation") \ No newline at end of file diff --git a/app/db/session.py b/app/db/session.py new file mode 100644 index 0000000..229aca0 --- /dev/null +++ b/app/db/session.py @@ -0,0 +1,28 @@ +from sqlalchemy import create_engine +from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy.orm import sessionmaker + +from app.core.config import settings + +# Ensure DB directory exists +settings.DB_DIR.mkdir(parents=True, exist_ok=True) + +# Create SQLAlchemy engine +engine = create_engine( + settings.SQLALCHEMY_DATABASE_URL, + connect_args={"check_same_thread": False} # Only needed for SQLite +) + +# Create session factory +SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) + +# Create base class for models +Base = declarative_base() + +# Dependency to get DB session +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..c15974f --- /dev/null +++ b/app/models/__init__.py @@ -0,0 +1,4 @@ +from app.models.user import User +from app.models.task import Task, TaskStatus, TaskPriority + +__all__ = ["User", "Task", "TaskStatus", "TaskPriority"] \ No newline at end of file diff --git a/app/models/task.py b/app/models/task.py new file mode 100644 index 0000000..fc8eb99 --- /dev/null +++ b/app/models/task.py @@ -0,0 +1,38 @@ +from datetime import datetime +from sqlalchemy import Boolean, Column, ForeignKey, Integer, String, Text, DateTime, Enum +from sqlalchemy.orm import relationship +import enum + +from app.db.session import Base + + +class TaskStatus(str, enum.Enum): + TODO = "todo" + IN_PROGRESS = "in_progress" + DONE = "done" + + +class TaskPriority(str, enum.Enum): + LOW = "low" + MEDIUM = "medium" + HIGH = "high" + + +class Task(Base): + __tablename__ = "tasks" + + id = Column(Integer, primary_key=True, index=True) + title = Column(String(255), nullable=False, index=True) + description = Column(Text, nullable=True) + status = Column(Enum(TaskStatus), default=TaskStatus.TODO, nullable=False) + priority = Column(Enum(TaskPriority), default=TaskPriority.MEDIUM, nullable=False) + due_date = Column(DateTime, nullable=True) + is_completed = Column(Boolean, default=False) + created_at = Column(DateTime, default=datetime.utcnow) + updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow) + + # Foreign key to user + owner_id = Column(Integer, ForeignKey("users.id"), nullable=False) + + # Relationship with User model + owner = relationship("User", back_populates="tasks") \ No newline at end of file diff --git a/app/models/user.py b/app/models/user.py new file mode 100644 index 0000000..340779e --- /dev/null +++ b/app/models/user.py @@ -0,0 +1,21 @@ +from datetime import datetime +from sqlalchemy import Boolean, Column, Integer, String, DateTime +from sqlalchemy.orm import relationship + +from app.db.session import Base + + +class User(Base): + __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) + is_superuser = Column(Boolean, default=False) + created_at = Column(DateTime, default=datetime.utcnow) + updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow) + + # Relationship with Task model + tasks = relationship("Task", back_populates="owner", cascade="all, delete-orphan") \ No newline at end of file diff --git a/app/schemas/__init__.py b/app/schemas/__init__.py new file mode 100644 index 0000000..aef1239 --- /dev/null +++ b/app/schemas/__init__.py @@ -0,0 +1,9 @@ +from app.schemas.token import Token, TokenPayload +from app.schemas.user import User, UserCreate, UserInDB, UserUpdate +from app.schemas.task import Task, TaskCreate, TaskUpdate, TaskInDBBase + +__all__ = [ + "Token", "TokenPayload", + "User", "UserCreate", "UserInDB", "UserUpdate", + "Task", "TaskCreate", "TaskUpdate", "TaskInDBBase" +] \ No newline at end of file diff --git a/app/schemas/task.py b/app/schemas/task.py new file mode 100644 index 0000000..6126790 --- /dev/null +++ b/app/schemas/task.py @@ -0,0 +1,51 @@ +from typing import Optional +from datetime import datetime +from pydantic import BaseModel + +from app.models.task import TaskStatus, TaskPriority + + +# Shared properties +class TaskBase(BaseModel): + title: Optional[str] = None + description: Optional[str] = None + status: Optional[TaskStatus] = None + priority: Optional[TaskPriority] = None + due_date: Optional[datetime] = None + is_completed: Optional[bool] = None + + +# Properties to receive on task creation +class TaskCreate(TaskBase): + title: str + status: TaskStatus = TaskStatus.TODO + priority: TaskPriority = TaskPriority.MEDIUM + + +# Properties to receive on task update +class TaskUpdate(TaskBase): + pass + + +class TaskInDBBase(TaskBase): + id: int + title: str + status: TaskStatus + priority: TaskPriority + is_completed: bool + owner_id: int + created_at: datetime + updated_at: datetime + + class Config: + from_attributes = True + + +# Additional properties to return via API +class Task(TaskInDBBase): + pass + + +# Additional properties stored in DB +class TaskInDB(TaskInDBBase): + pass \ 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..3c2bb64 --- /dev/null +++ b/app/schemas/user.py @@ -0,0 +1,42 @@ +from typing import Optional +from datetime import datetime +from pydantic import BaseModel, EmailStr + + +# 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 + + +# Properties to receive via API on update +class UserUpdate(UserBase): + password: Optional[str] = None + + +class UserInDBBase(UserBase): + id: Optional[int] = None + created_at: Optional[datetime] = None + updated_at: Optional[datetime] = None + + 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..e69de29 diff --git a/app/utils/init_db.py b/app/utils/init_db.py new file mode 100644 index 0000000..2a1086e --- /dev/null +++ b/app/utils/init_db.py @@ -0,0 +1,39 @@ +from typing import Optional +import logging + +from sqlalchemy.orm import Session + +from app import crud, schemas +from app.core.config import settings +from app.db.session import Base, engine + +logger = logging.getLogger(__name__) + +# Create tables if they don't exist +def init_db(db: Session) -> None: + # Create tables + Base.metadata.create_all(bind=engine) + + # Create initial superuser if needed + create_first_superuser(db) + +def create_first_superuser(db: Session) -> Optional[schemas.User]: + """ + Create a superuser if no users exist in the database. + + This should be used for initial setup only. + """ + user = crud.user.get_by_email(db, email=settings.FIRST_SUPERUSER_EMAIL) + if user: + logger.info("Superuser already exists, skipping creation.") + return None + + user_in = schemas.UserCreate( + email=settings.FIRST_SUPERUSER_EMAIL, + username=settings.FIRST_SUPERUSER_USERNAME, + password=settings.FIRST_SUPERUSER_PASSWORD, + is_superuser=True, + ) + user = crud.user.create(db, obj_in=user_in) + logger.info(f"Superuser {user.email} created successfully.") + return user \ No newline at end of file diff --git a/main.py b/main.py new file mode 100644 index 0000000..6bede9a --- /dev/null +++ b/main.py @@ -0,0 +1,42 @@ +import logging +import uvicorn +from fastapi import FastAPI +from fastapi.middleware.cors import CORSMiddleware + +from app.api.routes import api_router +from app.core.config import settings +from app.db.session import get_db +from app.db.init_db import init_db + +logging.basicConfig(level=logging.INFO) + +app = FastAPI( + title=settings.PROJECT_NAME, + description="Task Manager API allows users to create, manage and track tasks", + version="0.1.0", + 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) + + +@app.on_event("startup") +async def startup_db_client(): + """Initialize the database on startup.""" + db = next(get_db()) + init_db(db) + + +if __name__ == "__main__": + uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True) \ No newline at end of file diff --git a/migrations/__init__.py b/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/migrations/env.py b/migrations/env.py new file mode 100644 index 0000000..5731a41 --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,84 @@ +from logging.config import fileConfig + +from sqlalchemy import engine_from_config +from sqlalchemy import pool + +from alembic import context + +# Import models for autogenerate support +from app.db.session import Base +from app.models import user, task # noqa + +# 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() -> 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"}, + render_as_batch=True, # Important for SQLite + ) + + 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, # Important for 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..3cf5352 --- /dev/null +++ b/migrations/script.py.mako @@ -0,0 +1,26 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +# revision identifiers, used by Alembic. +revision: str = ${repr(up_revision)} +down_revision: Union[str, None] = ${repr(down_revision)} +branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)} +depends_on: Union[str, Sequence[str], None] = ${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/migrations/versions/001_initial_migration.py b/migrations/versions/001_initial_migration.py new file mode 100644 index 0000000..9c6de36 --- /dev/null +++ b/migrations/versions/001_initial_migration.py @@ -0,0 +1,70 @@ +"""Initial migration + +Revision ID: 001_initial_migration +Revises: +Create Date: 2023-10-01 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = '001_initial_migration' +down_revision: Union[str, None] = None +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + # Create users table + 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(), nullable=True), + sa.Column('is_superuser', sa.Boolean(), nullable=True), + 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_users_email'), 'users', ['email'], unique=True) + op.create_index(op.f('ix_users_id'), 'users', ['id'], unique=False) + op.create_index(op.f('ix_users_username'), 'users', ['username'], unique=True) + + # Create tasks table with task_status and task_priority enum types + # SQLite doesn't support ENUMs directly, so we use string with a check constraint + op.create_table( + 'tasks', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('title', sa.String(length=255), nullable=False), + sa.Column('description', sa.Text(), nullable=True), + sa.Column('status', sa.String(), nullable=False), + sa.Column('priority', sa.String(), nullable=False), + sa.Column('due_date', sa.DateTime(), nullable=True), + sa.Column('is_completed', sa.Boolean(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=True), + sa.Column('updated_at', sa.DateTime(), nullable=True), + sa.Column('owner_id', sa.Integer(), nullable=False), + sa.ForeignKeyConstraint(['owner_id'], ['users.id'], ), + sa.PrimaryKeyConstraint('id'), + sa.CheckConstraint("status IN ('todo', 'in_progress', 'done')"), + sa.CheckConstraint("priority IN ('low', 'medium', 'high')"), + ) + op.create_index(op.f('ix_tasks_id'), 'tasks', ['id'], unique=False) + op.create_index(op.f('ix_tasks_title'), 'tasks', ['title'], unique=False) + + +def downgrade() -> None: + op.drop_index(op.f('ix_tasks_title'), table_name='tasks') + op.drop_index(op.f('ix_tasks_id'), table_name='tasks') + op.drop_table('tasks') + + op.drop_index(op.f('ix_users_username'), table_name='users') + 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/requirements.txt b/requirements.txt new file mode 100644 index 0000000..09857d9 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,12 @@ +fastapi>=0.103.1 +uvicorn>=0.23.2 +sqlalchemy>=2.0.21 +alembic>=1.12.0 +pydantic>=2.4.2 +pydantic-settings>=2.0.3 +python-jose[cryptography]>=3.3.0 +passlib[bcrypt]>=1.7.4 +python-multipart>=0.0.6 +email-validator>=2.0.0 +ruff>=0.0.292 +python-dotenv>=1.0.0 \ No newline at end of file