From 2c5a9c26c25509c3699da5bd6bad8e4a1513a0b4 Mon Sep 17 00:00:00 2001 From: LadyKerr Date: Thu, 6 Feb 2025 15:19:42 -0600 Subject: [PATCH 01/20] Set up Planventure API with Docker and Flask --- .devcontainer/devcontainer.json | 40 ------------------- .../python-api-server/devcontainer.json | 35 ++++++++++++++++ .gitignore | 4 +- docker-compose.yml | 12 ++++++ index.html | 0 planventure-api/.gitignore | 4 ++ planventure-api/.sample.env | 4 ++ planventure-api/Dockerfile | 19 +++++++++ planventure-api/app.py | 16 ++++++++ planventure-api/requirements.txt | 24 +++++++++++ 10 files changed, 117 insertions(+), 41 deletions(-) delete mode 100644 .devcontainer/devcontainer.json create mode 100644 .devcontainer/python-api-server/devcontainer.json create mode 100644 docker-compose.yml delete mode 100644 index.html create mode 100644 planventure-api/.gitignore create mode 100644 planventure-api/.sample.env create mode 100644 planventure-api/Dockerfile create mode 100644 planventure-api/app.py create mode 100644 planventure-api/requirements.txt diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json deleted file mode 100644 index 292c1c7..0000000 --- a/.devcontainer/devcontainer.json +++ /dev/null @@ -1,40 +0,0 @@ -// For format details, see https://aka.ms/devcontainer.json. For config options, see the -// README at: https://github.com/devcontainers/templates/tree/main/src/go -{ - "name": "Game of Life Walkthrough", - // Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile - "image": "mcr.microsoft.com/devcontainers/universal:latest", - - // Use 'forwardPorts' to make a list of ports inside the container available locally. - "forwardPorts": [ - 3000 - ], - - // Use 'postCreateCommand' to run commands after the container is created. - // "postCreateCommand": "" - - // Configure tool-specific properties. - "customizations": { - "codespaces": { - "openFiles": [ - "index.html", - "README.md" - ] - }, - "vscode": { - "extensions": [ - "GitHub.codespaces", - "GitHub.copilot", - "GitHub.copilot-chat", - "github.copilot-workspace", - "GitHub.remotehub", - "github.vscode-github-actions", - "GitHub.vscode-pull-request-github", - "ms-vscode.live-server" - ] - } - } - - // Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root. - // "remoteUser": "root" - } diff --git a/.devcontainer/python-api-server/devcontainer.json b/.devcontainer/python-api-server/devcontainer.json new file mode 100644 index 0000000..a7588c0 --- /dev/null +++ b/.devcontainer/python-api-server/devcontainer.json @@ -0,0 +1,35 @@ +{ + "name": "Planventure Backend", + "dockerComposeFile": ["../../docker-compose.yml"], + "service": "backend", + "shutdownAction": "none", + "workspaceFolder": "/app", + "customizations": { + "codespaces": { + "openFiles": [ + "/planventure-api/app.py" + ] + }, + "vscode": { + "extensions": [ + "ms-python.python", + "esbenp.prettier-vscode", + "qwtel.sqlite-viewer", + "GitHub.copilot", + "GitHub.codespaces", + "GitHub.copilot-chat" + ], + "settings": { + "python.pythonPath": "/usr/local/bin/python", + "editor.formatOnSave": true, + "workbench.colorCustomizations": { + "activityBar.background": "#2b0935", + "titleBar.activeBackground": "#3d0d4a", + "titleBar.activeForeground": "#F3FDF6" + } + } + } + }, + "postCreateCommand": "pip install -r requirements.txt", + "forwardPorts": [5000] +} diff --git a/.gitignore b/.gitignore index 51e4ddf..6cd11a8 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,3 @@ -# Replace the .gitignore with the appropriate one from https://github.com/github/gitignore \ No newline at end of file +.vscode +# Bruno adds a dir to your vscode workspace +Planventure \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..3e3aa9c --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,12 @@ +version: '3.8' + +services: + backend: + build: + context: ./planventure-api + dockerfile: Dockerfile + ports: + - "5000:5000" + environment: + - FLASK_ENV=development + - DATABASE_URL=sqlite:///planventure.db diff --git a/index.html b/index.html deleted file mode 100644 index e69de29..0000000 diff --git a/planventure-api/.gitignore b/planventure-api/.gitignore new file mode 100644 index 0000000..4936acf --- /dev/null +++ b/planventure-api/.gitignore @@ -0,0 +1,4 @@ +venv/ +.env +__pycache__/ +*.pyc diff --git a/planventure-api/.sample.env b/planventure-api/.sample.env new file mode 100644 index 0000000..53df029 --- /dev/null +++ b/planventure-api/.sample.env @@ -0,0 +1,4 @@ +SECRET_KEY=your-secret-key-here +JWT_SECRET_KEY=your-jwt-secret-key-here +DATABASE_URL=your-sqldatabase-url-here +CORS_ORIGINS=your-cors-origins-here-host-hopefully-localhost:3000 \ No newline at end of file diff --git a/planventure-api/Dockerfile b/planventure-api/Dockerfile new file mode 100644 index 0000000..594d67f --- /dev/null +++ b/planventure-api/Dockerfile @@ -0,0 +1,19 @@ +# Use official Python image +FROM python:3.10-slim + +# Set working directory +WORKDIR /app + +# Install dependencies +COPY requirements.txt . +RUN pip install --upgrade pip +RUN pip install -r requirements.txt + +# Copy the rest of the application code +COPY . . + +# Expose port (e.g., 5000 for Flask) +EXPOSE 5000 + +# Command to run the Flask app +CMD ["flask", "run", "--host=0.0.0.0"] diff --git a/planventure-api/app.py b/planventure-api/app.py new file mode 100644 index 0000000..4f1b103 --- /dev/null +++ b/planventure-api/app.py @@ -0,0 +1,16 @@ +from flask import Flask, jsonify +from flask_cors import CORS + +app = Flask(__name__) +CORS(app) + +@app.route('/') +def home(): + return jsonify({"message": "Welcome to PlanVenture API"}) + +@app.route('/health') +def health_check(): + return jsonify({"status": "healthy"}) + +if __name__ == '__main__': + app.run(debug=True) \ No newline at end of file diff --git a/planventure-api/requirements.txt b/planventure-api/requirements.txt new file mode 100644 index 0000000..f28534d --- /dev/null +++ b/planventure-api/requirements.txt @@ -0,0 +1,24 @@ +# Core dependencies +flask==2.3.3 +flask-sqlalchemy==3.1.1 +flask-cors==4.0.0 +python-dotenv==1.0.0 + +# Authentication +flask-jwt-extended==4.5.2 +flask-bcrypt==1.0.1 + +# Validation and serialization +marshmallow-sqlalchemy==0.29.0 +email-validator==2.0.0 + +# Testing +pytest==7.4.2 +pytest-cov==4.1.0 + +# Production +gunicorn==21.2.0 + +# Development +black==23.9.1 +flake8==6.1.0 \ No newline at end of file From ad04f34d79b1c9fbc808ef317160c048033355b2 Mon Sep 17 00:00:00 2001 From: LadyKerr Date: Thu, 6 Feb 2025 15:46:12 -0600 Subject: [PATCH 02/20] Add Docker setup and API documentation for Planventure project --- DockerSetup.md | 154 ++++++++++++++++++++++++++++++++++++++ planventure-api/README.md | 62 +++++++++++++++ 2 files changed, 216 insertions(+) create mode 100644 DockerSetup.md create mode 100644 planventure-api/README.md diff --git a/DockerSetup.md b/DockerSetup.md new file mode 100644 index 0000000..eb6b40f --- /dev/null +++ b/DockerSetup.md @@ -0,0 +1,154 @@ +# Planventure + +# Development Environment Setup using Dev Containers + +This guide will help you set up your development environment using **Dev Containers** for both the **Frontend** and **Backend** applications. Utilizing Dev Containers ensures a consistent and isolated environment, making it easier for new contributors to get started without worrying about system-specific configurations. + +## Table of Contents + +- [Prerequisites](#prerequisites) +- [Getting Started](#getting-started) +- [Setting Up Dev Containers](#setting-up-dev-containers) + - [Frontend Dev Container](#frontend-dev-container) + - [Backend Dev Container](#backend-dev-container) +- [Running the Applications](#running-the-applications) +- [Accessing the Applications](#accessing-the-applications) +- [Troubleshooting](#troubleshooting) + +--- + +## Prerequisites + +Before you begin, ensure you have the following installed on your machine: + +1. **Docker Desktop** + - [Download Docker Desktop](https://www.docker.com/products/docker-desktop/) + - Ensure Docker is running. + +2. **Visual Studio Code (VS Code)** + - [Download VS Code](https://code.visualstudio.com/) + +3. **VS Code Extensions** + - **Remote - Containers** + Install from the [VS Code Marketplace](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers). + +4. **Git** + - [Download Git](https://git-scm.com/downloads) + - Ensure Git is available in your system's PATH. + +--- +## Getting Started + +1. **Clone the Repository** + + Open your terminal and run: + + ```bash + git clone https://github.com/github-samples/planventure.git + + cd planventure + + code . + ``` + +2. **Setting Up Dev Containers** + + There are 2 separate Dev Containers for the Frontend and Backend applications for this project. Each container will run in its own VS Code window with distinct color themes to differentiate between them. + + **Frontend Dev Container** + + Color Theme: Blue + + 1. From the VS Code window open to the root of this project repo, run `Dev Containers: Reopen in Container` from the Command Palette (F1) and select `Planventure Frontend`. + + 2. VS Code will then start up both containers, reload the current window and connect to the selected container. + + **Backend Dev Container + + Color Theme: Purple + + 1. From the open VS Code instance for the Frontend app, open a new window using File > New Window. + + 2. Open this project at root level in the current window. (This should be the same folder you opened when you first cloned the repo) + + 3. Run `Dev Containers: Reopen in Container` from the Command Palette (F1) and select `Planventure Backend`. + + 4. VS Code will then start up both containers, reload the current window and connect to the selected container. + + You can now interact with both containers from separate windows. + +--- + +## Running the Applications + +With both Dev Containers set up, your development environment is ready. Here's how to run and interact with both the frontend and backend applications. + +### Frontend +1. Development Server + - The frontend Dev Container automatically runs the development server using npm run dev. + - Port: 5173 (forwarded to your host machine). + +2. Accessing the Frontend + + - Open your browser and navigate to: +http://localhost:5173 + +3. Hot Reloading + - Any changes made to the frontend code within the Dev Container will automatically reflect in the browser without needing a manual refresh. + +### Backend +1. Development Server + - The backend Dev Container automatically runs the Flask development server. + - Port: 5000 (forwarded to your host machine). + +2. Accessing the Backend API + - Open your browser or API client (e.g., Bruno) and navigate to: +http://localhost:5000 + +3. Hot Reloading + - Any changes made to the frontend code within the Dev Container will automatically reflect in the browser without needing a manual refresh. + +--- + +## Troubleshooting + +If you encounter issues while setting up or running the Dev Containers, consider the following steps: + +1. Docker Not Running + - Ensure Docker Desktop is installed and running. + - Verify Docker's status by running docker info in your terminal. + +2. Port Conflicts + - Ensure that ports 5173, 5000, and 5432 are not being used by other applications. + - If conflicts exist, adjust the docker-compose.yml and devcontainer.json to use different ports. + +3. Dependency Issues + - Check the postCreateCommand in each devcontainer.json to ensure dependencies are installing correctly. + - View the integrated terminal in VS Code for any installation errors. + +4. Environment Variables + - Verify that all necessary environment variables are correctly set in docker-compose.yml. + Ensure that the frontend's `BASE_API_URL` points to the correct backend service (http://localhost:5000). + +5. File Permissions + - Ensure that your user has the necessary permissions to read and write to the project directories. + - On Unix-based systems, you might need to adjust permissions using chmod or chown. + +6. Rebuilding Containers + - If changes are made to `Dockerfile` or `docker-compose.yml`, rebuild the containers: + ```sh + docker-compose up --build + ``` + +7. Clearing Docker Cache + Sometimes, cached layers can cause issues. To rebuild without cache: + ```sh + docker-compose build --no-cache + ``` + +8. Check Logs + - Use Docker logs to identify issues: + ```sh + docker logs planventure-frontend-1 + docker logs planventure-backend-1 + ``` \ No newline at end of file diff --git a/planventure-api/README.md b/planventure-api/README.md new file mode 100644 index 0000000..9913eb5 --- /dev/null +++ b/planventure-api/README.md @@ -0,0 +1,62 @@ +# Planventure API 🚁 + +[![Open in GitHub Codespaces](https://github.com/codespaces/badge.svg)](https://codespaces.new/github-samples/planventure) + +A Flask-based REST API backend for the Planventure application. + +## Prerequisites +Before you begin, ensure you have the following: + +- A GitHub account +- Access to GitHub Copilot - [sign up for FREE](https://gh.io/gfb-copilot)! +- A Code Editor +- API Client (like [Bruno](https://github.com/usebruno/bruno)) +- Git - [Download & Install Git](https://git-scm.com/downloads) + +## πŸš€ Getting Started + +## Build along in a Codespace + +1. Click the "Open in GitHub Codespaces" button above to start developing in a GitHub Codespace. + +### Local Development Setup + +If you prefer to develop locally, follow the steps below: + +1. Clone the repository and navigate to the [planventue-api](/planventure-api/) directory: +```sh +cd planventure-api +``` + +2. Create a virtual environment and activate it: +```sh +python -m venv venv +source venv/bin/activate # On Windows: venv\Scripts\activate +``` + +3. Install the required dependencies: +```sh +pip install -r requirements.txt +``` + +4. Create an `.env` file based on [.sample.env](.sample.env): +```sh +cp .sample.env .env +``` + +5. Start the Flask development server: +```sh +flask run +``` + +## Docker Setup + +If bulding locally, follow the Docker setup steps in the [DockerSetup](DockerSetup) file. + +## πŸ“š API Endpoints +- GET / - Welcome message +- GET /health - Health check endpoint + +## πŸ“ License + +This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. From e220d1369f2117773c55355c17d9b25c90964a81 Mon Sep 17 00:00:00 2001 From: LadyKerr Date: Thu, 6 Feb 2025 15:57:48 -0600 Subject: [PATCH 03/20] =?UTF-8?q?Update=20README.md=20=E2=9C=88=EF=B8=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 69 +++++++++++++++++++++++++++++++++------ planventure-api/README.md | 62 ----------------------------------- 2 files changed, 59 insertions(+), 72 deletions(-) delete mode 100644 planventure-api/README.md diff --git a/README.md b/README.md index 404aa9f..7c97131 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,62 @@ -# Walkthrough Template +# Planventure API 🚁 -This repository serves as a template for creating a walkthrough. Follow the steps below to get started. +[![Open in GitHub Codespaces](https://github.com/codespaces/badge.svg)](https://codespaces.new/github-samples/planventure) -## Getting Started +A Flask-based REST API backend for the Planventure application. -1. Clone this repository. -2. Update the documentation in the `docs` folder (including the `README.md` folder). -3. Customize the code and other content as needed. -4. Update the `SUPPORT.md` file with the appropriate information. -5. Review the default LICENSE (MIT), CODE_OF_CONDUCT, and CONTRIBUTING files to ensure they meet your needs. These use the samples provided as part of the OSPO release process. -6. Update the `README.md` file in the repository root with the appropriate information. You can find an example at [github-samples/game-of-life-walkthrough](https://github.com/github-samples/game-of-life-walkthrough). -7. When you are ready to publish the repository, please make sure that the Git history is clean. Then, raise an issue for a 'sample release' at [https://github.com/github/open-source-releases](https://github.com/github/open-source-releases). +## Prerequisites +Before you begin, ensure you have the following: + +- A GitHub account +- Access to GitHub Copilot - [sign up for FREE](https://gh.io/gfb-copilot)! +- A Code Editor +- API Client (like [Bruno](https://github.com/usebruno/bruno)) +- Git - [Download & Install Git](https://git-scm.com/downloads) + +## πŸš€ Getting Started + +## Build along in a Codespace + +1. Click the "Open in GitHub Codespaces" button above to start developing in a GitHub Codespace. + +### Local Development Setup + +If you prefer to develop locally, follow the steps below: + +1. Clone the repository and navigate to the [planventue-api](/planventure-api/) directory: +```sh +cd planventure-api +``` + +2. Create a virtual environment and activate it: +```sh +python -m venv venv +source venv/bin/activate # On Windows: venv\Scripts\activate +``` + +3. Install the required dependencies: +```sh +pip install -r requirements.txt +``` + +4. Create an `.env` file based on [.sample.env](/planventure-api/.sample.env): +```sh +cp .sample.env .env +``` + +5. Start the Flask development server: +```sh +flask run +``` + +## Docker Setup + +If bulding locally, follow the Docker setup steps in the [DockerSetup](DockerSetup) file. + +## πŸ“š API Endpoints +- GET / - Welcome message +- GET /health - Health check endpoint + +## πŸ“ License + +This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. diff --git a/planventure-api/README.md b/planventure-api/README.md deleted file mode 100644 index 9913eb5..0000000 --- a/planventure-api/README.md +++ /dev/null @@ -1,62 +0,0 @@ -# Planventure API 🚁 - -[![Open in GitHub Codespaces](https://github.com/codespaces/badge.svg)](https://codespaces.new/github-samples/planventure) - -A Flask-based REST API backend for the Planventure application. - -## Prerequisites -Before you begin, ensure you have the following: - -- A GitHub account -- Access to GitHub Copilot - [sign up for FREE](https://gh.io/gfb-copilot)! -- A Code Editor -- API Client (like [Bruno](https://github.com/usebruno/bruno)) -- Git - [Download & Install Git](https://git-scm.com/downloads) - -## πŸš€ Getting Started - -## Build along in a Codespace - -1. Click the "Open in GitHub Codespaces" button above to start developing in a GitHub Codespace. - -### Local Development Setup - -If you prefer to develop locally, follow the steps below: - -1. Clone the repository and navigate to the [planventue-api](/planventure-api/) directory: -```sh -cd planventure-api -``` - -2. Create a virtual environment and activate it: -```sh -python -m venv venv -source venv/bin/activate # On Windows: venv\Scripts\activate -``` - -3. Install the required dependencies: -```sh -pip install -r requirements.txt -``` - -4. Create an `.env` file based on [.sample.env](.sample.env): -```sh -cp .sample.env .env -``` - -5. Start the Flask development server: -```sh -flask run -``` - -## Docker Setup - -If bulding locally, follow the Docker setup steps in the [DockerSetup](DockerSetup) file. - -## πŸ“š API Endpoints -- GET / - Welcome message -- GET /health - Health check endpoint - -## πŸ“ License - -This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. From df0c7d164d4a2f3d948d8f475f2c6a11ff83e2d3 Mon Sep 17 00:00:00 2001 From: LadyKerr Date: Thu, 6 Feb 2025 17:47:36 -0600 Subject: [PATCH 04/20] Enhance development environment with updated devcontainer configuration and Docker setup --- .devcontainer/python-api-server/devcontainer.json | 10 ++++++++-- docker-compose.yml | 3 +++ 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/.devcontainer/python-api-server/devcontainer.json b/.devcontainer/python-api-server/devcontainer.json index a7588c0..8a4c872 100644 --- a/.devcontainer/python-api-server/devcontainer.json +++ b/.devcontainer/python-api-server/devcontainer.json @@ -7,7 +7,7 @@ "customizations": { "codespaces": { "openFiles": [ - "/planventure-api/app.py" + "app.py" ] }, "vscode": { @@ -31,5 +31,11 @@ } }, "postCreateCommand": "pip install -r requirements.txt", - "forwardPorts": [5000] + "forwardPorts": [5000], + "portsAttributes": { + "5000": { + "label": "Flask API", + "onAutoForward": "notify" + } + } } diff --git a/docker-compose.yml b/docker-compose.yml index 3e3aa9c..b02d400 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -2,11 +2,14 @@ version: '3.8' services: backend: + volumes: + - ./planventure-api:/app build: context: ./planventure-api dockerfile: Dockerfile ports: - "5000:5000" environment: + - FLASK_APP=app.py - FLASK_ENV=development - DATABASE_URL=sqlite:///planventure.db From 6c87b9586f8e8a0353d56d6cf91904c4fbc3dfc8 Mon Sep 17 00:00:00 2001 From: LadyKerr Date: Mon, 10 Feb 2025 17:57:30 -0600 Subject: [PATCH 05/20] setting up --- .../python-api-server/devcontainer.json | 41 ----- DockerSetup.md | 154 ------------------ docker-compose.yml | 15 -- planventure-api/Dockerfile | 19 --- 4 files changed, 229 deletions(-) delete mode 100644 .devcontainer/python-api-server/devcontainer.json delete mode 100644 DockerSetup.md delete mode 100644 docker-compose.yml delete mode 100644 planventure-api/Dockerfile diff --git a/.devcontainer/python-api-server/devcontainer.json b/.devcontainer/python-api-server/devcontainer.json deleted file mode 100644 index 8a4c872..0000000 --- a/.devcontainer/python-api-server/devcontainer.json +++ /dev/null @@ -1,41 +0,0 @@ -{ - "name": "Planventure Backend", - "dockerComposeFile": ["../../docker-compose.yml"], - "service": "backend", - "shutdownAction": "none", - "workspaceFolder": "/app", - "customizations": { - "codespaces": { - "openFiles": [ - "app.py" - ] - }, - "vscode": { - "extensions": [ - "ms-python.python", - "esbenp.prettier-vscode", - "qwtel.sqlite-viewer", - "GitHub.copilot", - "GitHub.codespaces", - "GitHub.copilot-chat" - ], - "settings": { - "python.pythonPath": "/usr/local/bin/python", - "editor.formatOnSave": true, - "workbench.colorCustomizations": { - "activityBar.background": "#2b0935", - "titleBar.activeBackground": "#3d0d4a", - "titleBar.activeForeground": "#F3FDF6" - } - } - } - }, - "postCreateCommand": "pip install -r requirements.txt", - "forwardPorts": [5000], - "portsAttributes": { - "5000": { - "label": "Flask API", - "onAutoForward": "notify" - } - } -} diff --git a/DockerSetup.md b/DockerSetup.md deleted file mode 100644 index eb6b40f..0000000 --- a/DockerSetup.md +++ /dev/null @@ -1,154 +0,0 @@ -# Planventure - -# Development Environment Setup using Dev Containers - -This guide will help you set up your development environment using **Dev Containers** for both the **Frontend** and **Backend** applications. Utilizing Dev Containers ensures a consistent and isolated environment, making it easier for new contributors to get started without worrying about system-specific configurations. - -## Table of Contents - -- [Prerequisites](#prerequisites) -- [Getting Started](#getting-started) -- [Setting Up Dev Containers](#setting-up-dev-containers) - - [Frontend Dev Container](#frontend-dev-container) - - [Backend Dev Container](#backend-dev-container) -- [Running the Applications](#running-the-applications) -- [Accessing the Applications](#accessing-the-applications) -- [Troubleshooting](#troubleshooting) - ---- - -## Prerequisites - -Before you begin, ensure you have the following installed on your machine: - -1. **Docker Desktop** - - [Download Docker Desktop](https://www.docker.com/products/docker-desktop/) - - Ensure Docker is running. - -2. **Visual Studio Code (VS Code)** - - [Download VS Code](https://code.visualstudio.com/) - -3. **VS Code Extensions** - - **Remote - Containers** - Install from the [VS Code Marketplace](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers). - -4. **Git** - - [Download Git](https://git-scm.com/downloads) - - Ensure Git is available in your system's PATH. - ---- -## Getting Started - -1. **Clone the Repository** - - Open your terminal and run: - - ```bash - git clone https://github.com/github-samples/planventure.git - - cd planventure - - code . - ``` - -2. **Setting Up Dev Containers** - - There are 2 separate Dev Containers for the Frontend and Backend applications for this project. Each container will run in its own VS Code window with distinct color themes to differentiate between them. - - **Frontend Dev Container** - - Color Theme: Blue - - 1. From the VS Code window open to the root of this project repo, run `Dev Containers: Reopen in Container` from the Command Palette (F1) and select `Planventure Frontend`. - - 2. VS Code will then start up both containers, reload the current window and connect to the selected container. - - **Backend Dev Container - - Color Theme: Purple - - 1. From the open VS Code instance for the Frontend app, open a new window using File > New Window. - - 2. Open this project at root level in the current window. (This should be the same folder you opened when you first cloned the repo) - - 3. Run `Dev Containers: Reopen in Container` from the Command Palette (F1) and select `Planventure Backend`. - - 4. VS Code will then start up both containers, reload the current window and connect to the selected container. - - You can now interact with both containers from separate windows. - ---- - -## Running the Applications - -With both Dev Containers set up, your development environment is ready. Here's how to run and interact with both the frontend and backend applications. - -### Frontend -1. Development Server - - The frontend Dev Container automatically runs the development server using npm run dev. - - Port: 5173 (forwarded to your host machine). - -2. Accessing the Frontend - - - Open your browser and navigate to: -http://localhost:5173 - -3. Hot Reloading - - Any changes made to the frontend code within the Dev Container will automatically reflect in the browser without needing a manual refresh. - -### Backend -1. Development Server - - The backend Dev Container automatically runs the Flask development server. - - Port: 5000 (forwarded to your host machine). - -2. Accessing the Backend API - - Open your browser or API client (e.g., Bruno) and navigate to: -http://localhost:5000 - -3. Hot Reloading - - Any changes made to the frontend code within the Dev Container will automatically reflect in the browser without needing a manual refresh. - ---- - -## Troubleshooting - -If you encounter issues while setting up or running the Dev Containers, consider the following steps: - -1. Docker Not Running - - Ensure Docker Desktop is installed and running. - - Verify Docker's status by running docker info in your terminal. - -2. Port Conflicts - - Ensure that ports 5173, 5000, and 5432 are not being used by other applications. - - If conflicts exist, adjust the docker-compose.yml and devcontainer.json to use different ports. - -3. Dependency Issues - - Check the postCreateCommand in each devcontainer.json to ensure dependencies are installing correctly. - - View the integrated terminal in VS Code for any installation errors. - -4. Environment Variables - - Verify that all necessary environment variables are correctly set in docker-compose.yml. - Ensure that the frontend's `BASE_API_URL` points to the correct backend service (http://localhost:5000). - -5. File Permissions - - Ensure that your user has the necessary permissions to read and write to the project directories. - - On Unix-based systems, you might need to adjust permissions using chmod or chown. - -6. Rebuilding Containers - - If changes are made to `Dockerfile` or `docker-compose.yml`, rebuild the containers: - ```sh - docker-compose up --build - ``` - -7. Clearing Docker Cache - Sometimes, cached layers can cause issues. To rebuild without cache: - ```sh - docker-compose build --no-cache - ``` - -8. Check Logs - - Use Docker logs to identify issues: - ```sh - docker logs planventure-frontend-1 - docker logs planventure-backend-1 - ``` \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml deleted file mode 100644 index b02d400..0000000 --- a/docker-compose.yml +++ /dev/null @@ -1,15 +0,0 @@ -version: '3.8' - -services: - backend: - volumes: - - ./planventure-api:/app - build: - context: ./planventure-api - dockerfile: Dockerfile - ports: - - "5000:5000" - environment: - - FLASK_APP=app.py - - FLASK_ENV=development - - DATABASE_URL=sqlite:///planventure.db diff --git a/planventure-api/Dockerfile b/planventure-api/Dockerfile deleted file mode 100644 index 594d67f..0000000 --- a/planventure-api/Dockerfile +++ /dev/null @@ -1,19 +0,0 @@ -# Use official Python image -FROM python:3.10-slim - -# Set working directory -WORKDIR /app - -# Install dependencies -COPY requirements.txt . -RUN pip install --upgrade pip -RUN pip install -r requirements.txt - -# Copy the rest of the application code -COPY . . - -# Expose port (e.g., 5000 for Flask) -EXPOSE 5000 - -# Command to run the Flask app -CMD ["flask", "run", "--host=0.0.0.0"] From f1f68ad85bdb128b96b2ab5ce5e51b575f76a2f6 Mon Sep 17 00:00:00 2001 From: LadyKerr Date: Tue, 11 Feb 2025 18:31:19 -0600 Subject: [PATCH 06/20] Remove sample environment configuration file from planventure-api --- planventure-api/.sample.env | 4 ---- 1 file changed, 4 deletions(-) delete mode 100644 planventure-api/.sample.env diff --git a/planventure-api/.sample.env b/planventure-api/.sample.env deleted file mode 100644 index 53df029..0000000 --- a/planventure-api/.sample.env +++ /dev/null @@ -1,4 +0,0 @@ -SECRET_KEY=your-secret-key-here -JWT_SECRET_KEY=your-jwt-secret-key-here -DATABASE_URL=your-sqldatabase-url-here -CORS_ORIGINS=your-cors-origins-here-host-hopefully-localhost:3000 \ No newline at end of file From ad90069d07c266f4538ec38fbadcbba5dd79b6de Mon Sep 17 00:00:00 2001 From: LadyKerr Date: Tue, 11 Feb 2025 18:49:39 -0600 Subject: [PATCH 07/20] starter reqs txt --- planventure-api/requirements.txt | 21 +-------------------- 1 file changed, 1 insertion(+), 20 deletions(-) diff --git a/planventure-api/requirements.txt b/planventure-api/requirements.txt index f28534d..11babe5 100644 --- a/planventure-api/requirements.txt +++ b/planventure-api/requirements.txt @@ -2,23 +2,4 @@ flask==2.3.3 flask-sqlalchemy==3.1.1 flask-cors==4.0.0 -python-dotenv==1.0.0 - -# Authentication -flask-jwt-extended==4.5.2 -flask-bcrypt==1.0.1 - -# Validation and serialization -marshmallow-sqlalchemy==0.29.0 -email-validator==2.0.0 - -# Testing -pytest==7.4.2 -pytest-cov==4.1.0 - -# Production -gunicorn==21.2.0 - -# Development -black==23.9.1 -flake8==6.1.0 \ No newline at end of file +python-dotenv==1.0.0 \ No newline at end of file From 24c09b514dca3ae95ec9615c24d8f138cd90b724 Mon Sep 17 00:00:00 2001 From: LadyKerr Date: Wed, 12 Feb 2025 14:33:39 -0600 Subject: [PATCH 08/20] Refactor Planventure API to integrate SQLAlchemy for database management, add user and trip models, and implement database initialization script. --- .gitignore | 3 +- planventure-api/app.py | 37 +++++++++++++++++++----- planventure-api/init_db.py | 12 ++++++++ planventure-api/instance/planventure.db | Bin 0 -> 16384 bytes planventure-api/models/__init__.py | 4 +++ planventure-api/models/trip.py | 22 ++++++++++++++ planventure-api/models/user.py | 17 +++++++++++ planventure-api/requirements.txt | 12 +++++++- 8 files changed, 97 insertions(+), 10 deletions(-) create mode 100644 planventure-api/init_db.py create mode 100644 planventure-api/instance/planventure.db create mode 100644 planventure-api/models/__init__.py create mode 100644 planventure-api/models/trip.py create mode 100644 planventure-api/models/user.py diff --git a/.gitignore b/.gitignore index 6cd11a8..4d0cc89 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ .vscode # Bruno adds a dir to your vscode workspace -Planventure \ No newline at end of file +Planventure +venv/ \ No newline at end of file diff --git a/planventure-api/app.py b/planventure-api/app.py index 4f1b103..49a7277 100644 --- a/planventure-api/app.py +++ b/planventure-api/app.py @@ -1,16 +1,37 @@ from flask import Flask, jsonify from flask_cors import CORS +from flask_sqlalchemy import SQLAlchemy +from os import environ +from dotenv import load_dotenv -app = Flask(__name__) -CORS(app) +# Load environment variables +load_dotenv() -@app.route('/') -def home(): - return jsonify({"message": "Welcome to PlanVenture API"}) +# Initialize SQLAlchemy +db = SQLAlchemy() -@app.route('/health') -def health_check(): - return jsonify({"status": "healthy"}) +def create_app(): + app = Flask(__name__) + CORS(app) + + # Database configuration + app.config['SQLALCHEMY_DATABASE_URI'] = environ.get('DATABASE_URL', 'sqlite:///planventure.db') + app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False + + # Initialize extensions + db.init_app(app) + + # Register routes + @app.route('/') + def home(): + return jsonify({"message": "Welcome to PlanVenture API"}) + + @app.route('/health') + def health_check(): + return jsonify({"status": "healthy"}) + + return app if __name__ == '__main__': + app = create_app() app.run(debug=True) \ No newline at end of file diff --git a/planventure-api/init_db.py b/planventure-api/init_db.py new file mode 100644 index 0000000..1aa9518 --- /dev/null +++ b/planventure-api/init_db.py @@ -0,0 +1,12 @@ +from app import create_app, db +from models import User + +def init_db(): + app = create_app() + with app.app_context(): + # Create all database tables + db.create_all() + print("Database tables created successfully!") + +if __name__ == '__main__': + init_db() diff --git a/planventure-api/instance/planventure.db b/planventure-api/instance/planventure.db new file mode 100644 index 0000000000000000000000000000000000000000..a7d15279c0f522bdfa4f8d69db44961a7e0bb013 GIT binary patch literal 16384 zcmeI%L2uJA6bEppoq$Cu+b!33Or#06ap8hQDDDVkDN9qNNl1|)hDOSglDLBH2Gc$s zUxhPAY->fdXuEJLe@n5I_uSa;*XCe#auSzH(ubx!6N(`x2E!+CN zvrODF_Sl1q`C#WK>kls3{U1Bu^?(Ke2tWV=5P$##AOHafK;VBB_%`d`^*qnHdZ@&^ zN~*S;cedLaraa6zW#O}!lMRvYZkGi`Nyd+OO365*WE#hN4%1V5#ZSpEi@;1BjZ+>SB_`%y z8w8Z{5l?wCn+`&=wkWAAfYReoTHzJA&6 znHO$gx?R(uK>z{}fB*y_009U<00Izz00bbgsRFJk4Cnt%{d!Rs1Rwwb2tWV=5P$## lAOHafK)?#%|9|`tAOHafKmY;|fB*y_009U<00NsY@CzSVz_kDX literal 0 HcmV?d00001 diff --git a/planventure-api/models/__init__.py b/planventure-api/models/__init__.py new file mode 100644 index 0000000..34a38f3 --- /dev/null +++ b/planventure-api/models/__init__.py @@ -0,0 +1,4 @@ +from .user import User +from .trip import Trip + +__all__ = ['User', 'Trip'] \ No newline at end of file diff --git a/planventure-api/models/trip.py b/planventure-api/models/trip.py new file mode 100644 index 0000000..d82b832 --- /dev/null +++ b/planventure-api/models/trip.py @@ -0,0 +1,22 @@ +from datetime import datetime, timezone +from app import db + +class Trip(db.Model): + __tablename__ = 'trips' + + id = db.Column(db.Integer, primary_key=True) + user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False) + destination = db.Column(db.String(200), nullable=False) + start_date = db.Column(db.DateTime, nullable=False) + end_date = db.Column(db.DateTime, nullable=False) + latitude = db.Column(db.Float) + longitude = db.Column(db.Float) + itinerary = db.Column(db.JSON) + created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc)) + updated_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc)) + + # Relationship + user = db.relationship('User', back_populates='trips') + + def __repr__(self): + return f'' diff --git a/planventure-api/models/user.py b/planventure-api/models/user.py new file mode 100644 index 0000000..68e14d8 --- /dev/null +++ b/planventure-api/models/user.py @@ -0,0 +1,17 @@ +from datetime import datetime, timezone +from app import db + +class User(db.Model): + __tablename__ = 'users' + + id = db.Column(db.Integer, primary_key=True) + email = db.Column(db.String(120), unique=True, nullable=False) + password_hash = db.Column(db.String(128), nullable=False) + created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc)) + updated_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc)) + + # Add relationship + trips = db.relationship('Trip', back_populates='user', cascade='all, delete-orphan') + + def __repr__(self): + return f'' diff --git a/planventure-api/requirements.txt b/planventure-api/requirements.txt index 11babe5..20cf188 100644 --- a/planventure-api/requirements.txt +++ b/planventure-api/requirements.txt @@ -2,4 +2,14 @@ flask==2.3.3 flask-sqlalchemy==3.1.1 flask-cors==4.0.0 -python-dotenv==1.0.0 \ No newline at end of file +python-dotenv==1.0.0 + +# Authentication +flask-jwt-extended==4.5.3 +werkzeug==2.3.7 + +# Password hashing +bcrypt==4.0.1 + +# Database migrations +Flask-Migrate==4.0.5 \ No newline at end of file From e23b91724a82c93600c51145b7abe97100c63a20 Mon Sep 17 00:00:00 2001 From: LadyKerr Date: Wed, 12 Feb 2025 18:47:52 -0600 Subject: [PATCH 09/20] Implement JWT authentication and user registration/login endpoints in Planventure API --- planventure-api/app.py | 34 ++++++++++++ planventure-api/instance/planventure.db | Bin 16384 -> 16384 bytes planventure-api/middleware/auth.py | 21 +++++++ planventure-api/models/user.py | 22 ++++++++ planventure-api/routes/__init__.py | 3 + planventure-api/routes/auth.py | 70 ++++++++++++++++++++++++ planventure-api/routes/trips.py | 10 ++++ planventure-api/utils/__init__.py | 4 ++ planventure-api/utils/auth.py | 16 ++++++ planventure-api/utils/password.py | 13 +++++ planventure-api/utils/validators.py | 6 ++ 11 files changed, 199 insertions(+) create mode 100644 planventure-api/middleware/auth.py create mode 100644 planventure-api/routes/__init__.py create mode 100644 planventure-api/routes/auth.py create mode 100644 planventure-api/routes/trips.py create mode 100644 planventure-api/utils/__init__.py create mode 100644 planventure-api/utils/auth.py create mode 100644 planventure-api/utils/password.py create mode 100644 planventure-api/utils/validators.py diff --git a/planventure-api/app.py b/planventure-api/app.py index 49a7277..3c325f3 100644 --- a/planventure-api/app.py +++ b/planventure-api/app.py @@ -1,8 +1,10 @@ from flask import Flask, jsonify from flask_cors import CORS from flask_sqlalchemy import SQLAlchemy +from flask_jwt_extended import JWTManager from os import environ from dotenv import load_dotenv +from datetime import timedelta # Load environment variables load_dotenv() @@ -14,12 +16,44 @@ def create_app(): app = Flask(__name__) CORS(app) + # JWT Configuration + app.config['JWT_SECRET_KEY'] = environ.get('JWT_SECRET_KEY', 'your-secret-key') + app.config['JWT_ACCESS_TOKEN_EXPIRES'] = timedelta(hours=1) + jwt = JWTManager(app) + + @jwt.expired_token_loader + def expired_token_callback(jwt_header, jwt_data): + return jsonify({ + 'error': 'Token has expired', + 'code': 'token_expired' + }), 401 + + @jwt.invalid_token_loader + def invalid_token_callback(error): + return jsonify({ + 'error': 'Invalid token', + 'code': 'invalid_token' + }), 401 + + @jwt.unauthorized_loader + def missing_token_callback(error): + return jsonify({ + 'error': 'Authorization token is missing', + 'code': 'authorization_required' + }), 401 + # Database configuration app.config['SQLALCHEMY_DATABASE_URI'] = environ.get('DATABASE_URL', 'sqlite:///planventure.db') app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False # Initialize extensions db.init_app(app) + + # Register blueprints + from routes.auth import auth_bp + from routes.trips import trips_bp + app.register_blueprint(auth_bp, url_prefix='/auth') + app.register_blueprint(trips_bp, url_prefix='/api') # Register routes @app.route('/') diff --git a/planventure-api/instance/planventure.db b/planventure-api/instance/planventure.db index a7d15279c0f522bdfa4f8d69db44961a7e0bb013..7bc439dd00daa31e2727126dfe629661da197024 100644 GIT binary patch delta 530 zcmZ{hOHRU207Y9GATnqn4t2nQ2_cmBz5YkGREU7`|8*pvg3uNU6htS`9q1N}8!%2> z0gG@Ex&!UeQ$!dp0*XQ{)xzSB?d|<+XoO~|p zEgF{k_meEk300$!x8OoC>h`Uzl$Qpd;`>Hf);LvF8&;uPB=`D&L<=Mk7|63fWVMsr zA%Swes2_=LH*xftb0EUZ_yNo`n^lwRBx~bB`*N65=3;7*nkwAbEIMYoy;u&01x=ad zNz>BINq)W)0bu|oNK33p@*IeXkogCR3(7mg$ZMHX> NCxk_h{^~ykgI~XFkFx*( delta 34 qcmZo@U~Fh$oFL7}G*QNxk!fSX68_CB27mY&xi&Kz{O4a}AOHZdU' diff --git a/planventure-api/routes/__init__.py b/planventure-api/routes/__init__.py new file mode 100644 index 0000000..8a50c0e --- /dev/null +++ b/planventure-api/routes/__init__.py @@ -0,0 +1,3 @@ +from .auth import auth_bp + +__all__ = ['auth_bp'] diff --git a/planventure-api/routes/auth.py b/planventure-api/routes/auth.py new file mode 100644 index 0000000..025c446 --- /dev/null +++ b/planventure-api/routes/auth.py @@ -0,0 +1,70 @@ +from flask import Blueprint, request, jsonify +from app import db +from models import User +from utils.validators import validate_email + +auth_bp = Blueprint('auth', __name__) + +# Error responses +INVALID_CREDENTIALS = {"error": "Invalid email or password"}, 401 +MISSING_FIELDS = {"error": "Missing required fields"}, 400 +INVALID_EMAIL = {"error": "Invalid email format"}, 400 +EMAIL_EXISTS = {"error": "Email already registered"}, 409 + +@auth_bp.route('/register', methods=['POST']) +def register(): + data = request.get_json() + + # Validate required fields + if not all(k in data for k in ['email', 'password']): + return jsonify(MISSING_FIELDS) + + # Validate email format + if not validate_email(data['email']): + return jsonify(INVALID_EMAIL) + + # Check if user already exists + if User.query.filter_by(email=data['email']).first(): + return jsonify(EMAIL_EXISTS) + + # Create new user + try: + user = User(email=data['email']) + user.password = data['password'] # This will hash the password + db.session.add(user) + db.session.commit() + + # Generate auth token + token = user.generate_auth_token() + return jsonify({ + 'message': 'User registered successfully', + 'token': token + }), 201 + except Exception as e: + db.session.rollback() + return jsonify({'error': 'Registration failed'}), 500 + +@auth_bp.route('/login', methods=['POST']) +def login(): + data = request.get_json() + + # Validate required fields + if not all(k in data for k in ['email', 'password']): + return jsonify(MISSING_FIELDS) + + # Find user by email + user = User.query.filter_by(email=data['email']).first() + + # Verify user exists and password is correct + if user and user.verify_password(data['password']): + token = user.generate_auth_token() + return jsonify({ + 'message': 'Login successful', + 'token': token, + 'user': { + 'id': user.id, + 'email': user.email + } + }), 200 + + return jsonify(INVALID_CREDENTIALS) diff --git a/planventure-api/routes/trips.py b/planventure-api/routes/trips.py new file mode 100644 index 0000000..ba6a6f4 --- /dev/null +++ b/planventure-api/routes/trips.py @@ -0,0 +1,10 @@ +from flask import Blueprint, jsonify +from middleware.auth import auth_middleware + +trips_bp = Blueprint('trips', __name__) + +@trips_bp.route('/trips', methods=['GET']) +@auth_middleware +def get_trips(): + # This route is now protected and will only be accessible with a valid JWT token + return jsonify({"message": "Protected route accessed successfully"}) diff --git a/planventure-api/utils/__init__.py b/planventure-api/utils/__init__.py new file mode 100644 index 0000000..11c24b3 --- /dev/null +++ b/planventure-api/utils/__init__.py @@ -0,0 +1,4 @@ +from .password import hash_password, check_password +from .auth import auth_required, get_current_user_id + +__all__ = ['hash_password', 'check_password', 'auth_required', 'get_current_user_id'] diff --git a/planventure-api/utils/auth.py b/planventure-api/utils/auth.py new file mode 100644 index 0000000..6a16a80 --- /dev/null +++ b/planventure-api/utils/auth.py @@ -0,0 +1,16 @@ +from functools import wraps +from flask import jsonify +from flask_jwt_extended import verify_jwt_in_request, get_jwt_identity + +def auth_required(f): + @wraps(f) + def decorated(*args, **kwargs): + try: + verify_jwt_in_request() + return f(*args, **kwargs) + except Exception as e: + return jsonify({"msg": "Invalid token"}), 401 + return decorated + +def get_current_user_id(): + return get_jwt_identity() diff --git a/planventure-api/utils/password.py b/planventure-api/utils/password.py new file mode 100644 index 0000000..133f9e2 --- /dev/null +++ b/planventure-api/utils/password.py @@ -0,0 +1,13 @@ +import bcrypt + +def hash_password(password: str) -> str: + """Hash a password using bcrypt""" + salt = bcrypt.gensalt() + return bcrypt.hashpw(password.encode('utf-8'), salt).decode('utf-8') + +def check_password(password: str, password_hash: str) -> bool: + """Verify a password against its hash""" + return bcrypt.checkpw( + password.encode('utf-8'), + password_hash.encode('utf-8') + ) diff --git a/planventure-api/utils/validators.py b/planventure-api/utils/validators.py new file mode 100644 index 0000000..887f770 --- /dev/null +++ b/planventure-api/utils/validators.py @@ -0,0 +1,6 @@ +import re + +def validate_email(email: str) -> bool: + """Validate email format using regex pattern""" + pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$' + return bool(re.match(pattern, email)) From 43eb5d36643f760ae61e033f0b3f65156bdb263a Mon Sep 17 00:00:00 2001 From: LadyKerr Date: Wed, 12 Feb 2025 20:14:21 -0600 Subject: [PATCH 10/20] Add CORS and JWT configuration, implement trip management routes, and generate default itinerary --- planventure-api/.env.example | 8 ++ planventure-api/app.py | 11 +- planventure-api/config.py | 28 ++++ planventure-api/instance/planventure.db | Bin 16384 -> 16384 bytes planventure-api/middleware/auth.py | 2 +- planventure-api/models/user.py | 2 +- planventure-api/routes/__init__.py | 3 +- planventure-api/routes/trips.py | 174 +++++++++++++++++++++++- planventure-api/utils/__init__.py | 9 +- planventure-api/utils/itinerary.py | 29 ++++ 10 files changed, 257 insertions(+), 9 deletions(-) create mode 100644 planventure-api/.env.example create mode 100644 planventure-api/config.py create mode 100644 planventure-api/utils/itinerary.py diff --git a/planventure-api/.env.example b/planventure-api/.env.example new file mode 100644 index 0000000..38ba6c2 --- /dev/null +++ b/planventure-api/.env.example @@ -0,0 +1,8 @@ +# CORS Settings +CORS_ORIGINS=http://localhost:3000,http://localhost:5173 + +# JWT Settings +JWT_SECRET_KEY=your-secret-key-here + +# Database Settings +DATABASE_URL=sqlite:///planventure.db diff --git a/planventure-api/app.py b/planventure-api/app.py index 3c325f3..9cea4d3 100644 --- a/planventure-api/app.py +++ b/planventure-api/app.py @@ -5,6 +5,7 @@ from os import environ from dotenv import load_dotenv from datetime import timedelta +from config import Config # Load environment variables load_dotenv() @@ -14,7 +15,15 @@ def create_app(): app = Flask(__name__) - CORS(app) + + # Configure CORS + CORS(app, + resources={r"/*": { + "origins": Config.CORS_ORIGINS, + "methods": Config.CORS_METHODS, + "allow_headers": Config.CORS_HEADERS, + "supports_credentials": Config.CORS_SUPPORTS_CREDENTIALS + }}) # JWT Configuration app.config['JWT_SECRET_KEY'] = environ.get('JWT_SECRET_KEY', 'your-secret-key') diff --git a/planventure-api/config.py b/planventure-api/config.py new file mode 100644 index 0000000..6596ffc --- /dev/null +++ b/planventure-api/config.py @@ -0,0 +1,28 @@ +from os import environ +from dotenv import load_dotenv + +load_dotenv() + +class Config: + # CORS Settings + CORS_ORIGINS = environ.get( + 'CORS_ORIGINS', + 'http://localhost:3000,http://localhost:5173' + ).split(',') + + CORS_HEADERS = [ + 'Content-Type', + 'Authorization', + 'Access-Control-Allow-Credentials' + ] + + CORS_METHODS = [ + 'GET', + 'POST', + 'PUT', + 'DELETE', + 'OPTIONS' + ] + + # Cookie Settings + CORS_SUPPORTS_CREDENTIALS = True diff --git a/planventure-api/instance/planventure.db b/planventure-api/instance/planventure.db index 7bc439dd00daa31e2727126dfe629661da197024..88bbcca14756993f5caaa379cdde3d7cf2f95f8d 100644 GIT binary patch delta 946 zcmb`FJxjwt9LAeE)S(ESbvSNuFsYYI-x3`fYQ>?76mb#3BT4OPUL?6hN-3$-51_lF zf@?pBgWtf9;-#3PwSrW`4N0E=JrB?QZa5T%L*Z^!$lb3sgxvV-adSDFk1{LU`DlD| zk&j1>Y(67w=z1=9d#US7EzdPQR|HM>+$OGx5iUunBFSZdkTzLGGB&$7eMk&OBg&{1@XwPzWHEIt{tA)G&7la=iC*&am', methods=['GET', 'PUT', 'DELETE']) +@auth_middleware +def handle_trip(trip_id): + if request.method == 'GET': + return get_trip(trip_id) + elif request.method == 'PUT': + return update_trip(trip_id) + elif request.method == 'DELETE': + return delete_trip(trip_id) + +def get_trip(trip_id): + user_id = get_jwt_identity() + trip = Trip.query.filter_by(id=trip_id, user_id=user_id).first() + + if not trip: + return jsonify({'error': 'Trip not found'}), 404 + + return jsonify({ + 'id': trip.id, + 'destination': trip.destination, + 'start_date': trip.start_date.isoformat(), + 'end_date': trip.end_date.isoformat(), + 'latitude': trip.latitude, + 'longitude': trip.longitude, + 'itinerary': trip.itinerary + }), 200 + +def update_trip(trip_id): + user_id = get_jwt_identity() + trip = Trip.query.filter_by(id=trip_id, user_id=user_id).first() + + if not trip: + return jsonify({'error': 'Trip not found'}), 404 + + data = request.get_json() + + try: + if 'destination' in data: + trip.destination = data['destination'] + if 'start_date' in data or 'end_date' in data: + start_date = datetime.fromisoformat(data.get('start_date', trip.start_date.isoformat()).replace('Z', '+00:00')) + end_date = datetime.fromisoformat(data.get('end_date', trip.end_date.isoformat()).replace('Z', '+00:00')) + # Generate new itinerary template for new dates if itinerary is not provided + if 'itinerary' not in data: + data['itinerary'] = generate_default_itinerary(start_date, end_date) + if 'latitude' in data: + trip.latitude = data['latitude'] + if 'longitude' in data: + trip.longitude = data['longitude'] + if 'itinerary' in data: + trip.itinerary = data['itinerary'] + + db.session.commit() + return jsonify({'message': 'Trip updated successfully'}), 200 + except ValueError: + return jsonify({'error': 'Invalid date format'}), 400 + except Exception as e: + db.session.rollback() + return jsonify({'error': 'Failed to update trip'}), 500 + +def delete_trip(trip_id): + user_id = get_jwt_identity() + trip = Trip.query.filter_by(id=trip_id, user_id=user_id).first() + + if not trip: + return jsonify({'error': 'Trip not found'}), 404 + + try: + db.session.delete(trip) + db.session.commit() + return jsonify({'message': 'Trip deleted successfully'}), 200 + except Exception as e: + db.session.rollback() + return jsonify({'error': 'Failed to delete trip'}), 500 + +@trips_bp.errorhandler(405) +def method_not_allowed(e): + return jsonify({'error': 'Method not allowed'}), 405 diff --git a/planventure-api/utils/__init__.py b/planventure-api/utils/__init__.py index 11c24b3..98b5427 100644 --- a/planventure-api/utils/__init__.py +++ b/planventure-api/utils/__init__.py @@ -1,4 +1,11 @@ from .password import hash_password, check_password from .auth import auth_required, get_current_user_id +from .itinerary import generate_default_itinerary -__all__ = ['hash_password', 'check_password', 'auth_required', 'get_current_user_id'] +__all__ = [ + 'hash_password', + 'check_password', + 'auth_required', + 'get_current_user_id', + 'generate_default_itinerary' +] diff --git a/planventure-api/utils/itinerary.py b/planventure-api/utils/itinerary.py new file mode 100644 index 0000000..44be7d9 --- /dev/null +++ b/planventure-api/utils/itinerary.py @@ -0,0 +1,29 @@ +from datetime import datetime, timedelta + +def generate_default_itinerary(start_date: datetime, end_date: datetime) -> dict: + """Generate a default itinerary template for the trip duration""" + itinerary = {} + current_date = start_date + + while current_date <= end_date: + date_str = current_date.strftime('%Y-%m-%d') + itinerary[date_str] = { + 'activities': [], + 'meals': { + 'breakfast': {'time': '08:00', 'place': '', 'notes': ''}, + 'lunch': {'time': '13:00', 'place': '', 'notes': ''}, + 'dinner': {'time': '19:00', 'place': '', 'notes': ''} + }, + 'accommodation': { + 'name': '', + 'address': '', + 'check_in': '', + 'check_out': '', + 'confirmation': '' + }, + 'transportation': [], + 'notes': '' + } + current_date += timedelta(days=1) + + return itinerary From a3e4ca18ca00ddd8e267d6e6e1c5fe6ba776b856 Mon Sep 17 00:00:00 2001 From: LadyKerr Date: Thu, 13 Feb 2025 17:43:42 -0600 Subject: [PATCH 11/20] Add README.md for Planventure API with features, tech stack, and API endpoints --- planventure-api/README.md | 62 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 planventure-api/README.md diff --git a/planventure-api/README.md b/planventure-api/README.md new file mode 100644 index 0000000..a9abbf4 --- /dev/null +++ b/planventure-api/README.md @@ -0,0 +1,62 @@ +# Planventure API 🌍✈️ + +A Flask-based REST API for managing travel itineraries and trip planning. + +## Features + +- πŸ” User Authentication (JWT-based) +- πŸ—ΊοΈ Trip Management +- πŸ“… Itinerary Planning +- πŸ”’ Secure Password Hashing +- ⚑ CORS Support + +## Tech Stack + +- Python 3.x +- Flask +- SQLAlchemy +- Flask-JWT-Extended +- SQLite Database +- BCrypt for password hashing + +## API Endpoints + +### Authentication + +- `POST /auth/register` - Register a new user + ```json + { + "email": "user@example.com", + "password": "secure_password" + } + ``` + +- `POST /auth/login` - Login and get JWT token + ```json + \{ + "email": "user@example.com", + "password": "secure_password" +} + ``` + +### Trips + +- `GET /trips` - Get all trips +- `POST /trips` - Create a new trip + ```json + { + "destination": "Paris, France", + "start_date": "2024-06-15T00:00:00Z", + "end_date": "2024-06-22T00:00:00Z", + "latitude": 48.8566, + "longitude": 2.3522, + "itinerary": {} + } + ``` +- `GET /trips/` - Get a single trip +- `PUT /trips/` - Update a trip +- `DELETE /trips/` - Delete a trip + + + + From 6089195ea6d15232d1cd4ff1e21946c62a28ff1d Mon Sep 17 00:00:00 2001 From: LadyKerr Date: Thu, 13 Feb 2025 18:02:41 -0600 Subject: [PATCH 12/20] Add initial Planventure API setup with Flask and update README --- .gitignore | 5 ++- README.md | 71 +++++++++++++++++++++++++++----- index.html | 0 planventure-api/.sample.env | 4 ++ planventure-api/app.py | 16 +++++++ planventure-api/requirements.txt | 5 +++ 6 files changed, 90 insertions(+), 11 deletions(-) delete mode 100644 index.html create mode 100644 planventure-api/.sample.env create mode 100644 planventure-api/app.py create mode 100644 planventure-api/requirements.txt diff --git a/.gitignore b/.gitignore index 51e4ddf..203bd53 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,4 @@ -# Replace the .gitignore with the appropriate one from https://github.com/github/gitignore \ No newline at end of file +.vscode +# Bruno adds a dir to your vscode workspace +Planventure +__pycache__ \ No newline at end of file diff --git a/README.md b/README.md index 404aa9f..8ac2bbe 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,64 @@ -# Walkthrough Template +# Planventure API 🚁 -This repository serves as a template for creating a walkthrough. Follow the steps below to get started. +[![Open in GitHub Codespaces](https://github.com/codespaces/badge.svg)](https://codespaces.new/github-samples/planventure) -## Getting Started +A Flask-based REST API backend for the Planventure application. -1. Clone this repository. -2. Update the documentation in the `docs` folder (including the `README.md` folder). -3. Customize the code and other content as needed. -4. Update the `SUPPORT.md` file with the appropriate information. -5. Review the default LICENSE (MIT), CODE_OF_CONDUCT, and CONTRIBUTING files to ensure they meet your needs. These use the samples provided as part of the OSPO release process. -6. Update the `README.md` file in the repository root with the appropriate information. You can find an example at [github-samples/game-of-life-walkthrough](https://github.com/github-samples/game-of-life-walkthrough). -7. When you are ready to publish the repository, please make sure that the Git history is clean. Then, raise an issue for a 'sample release' at [https://github.com/github/open-source-releases](https://github.com/github/open-source-releases). +## Prerequisites +Before you begin, ensure you have the following: + +- A GitHub account - [sign up for FREE](https://github.com) +- Access to GitHub Copilot - [sign up for FREE](https://gh.io/gfb-copilot)! +- A Code Editor - [VS Code](https://code.visualstudio.com/download) is recommended +- API Client (like [Bruno](https://github.com/usebruno/bruno)) +- Git - [Download & Install Git](https://git-scm.com/downloads) + +## πŸš€ Getting Started + +## Build along in a Codespace + +1. Click the "Open in GitHub Codespaces" button above to start developing in a GitHub Codespace. + +### Local Development Setup + +If you prefer to develop locally, follow the steps below: + +1. Clone the repository to your local machine: +```sh +git clone https://github.com/github-samples/planventure.git +``` + +2. Create a virtual environment and activate it: +```sh +python -m venv venv +source venv/bin/activate # On Windows: venv\Scripts\activate +``` + +3. Navigate to the [planventue-api](/planventure-api/) directory: +```sh +cd planventure-api +``` + +4. Install the required dependencies: +```sh +pip install -r requirements.txt +``` + +5. Create an `.env` file based on [.sample.env](.sample.env): +```sh +cp .sample.env .env +``` + +6. Start the Flask development server: +```sh +flask run --debug +``` + +## πŸ“š API Endpoints +- GET / - Welcome message +- GET /health - Health check endpoint + +## πŸ“ License + +This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. +Footer \ No newline at end of file diff --git a/index.html b/index.html deleted file mode 100644 index e69de29..0000000 diff --git a/planventure-api/.sample.env b/planventure-api/.sample.env new file mode 100644 index 0000000..53df029 --- /dev/null +++ b/planventure-api/.sample.env @@ -0,0 +1,4 @@ +SECRET_KEY=your-secret-key-here +JWT_SECRET_KEY=your-jwt-secret-key-here +DATABASE_URL=your-sqldatabase-url-here +CORS_ORIGINS=your-cors-origins-here-host-hopefully-localhost:3000 \ No newline at end of file diff --git a/planventure-api/app.py b/planventure-api/app.py new file mode 100644 index 0000000..3f778d8 --- /dev/null +++ b/planventure-api/app.py @@ -0,0 +1,16 @@ +from flask import Flask, jsonify +from flask_cors import CORS + +app = Flask(__name__) +CORS(app) + +@app.route('/') +def home(): + return jsonify({"message": "Welcome to PlanVenture API"}) + +@app.route('/health') +def health_check(): + return jsonify({"status": "healthy"}) + +if __name__ == '__main__': + app.run(debug=True) diff --git a/planventure-api/requirements.txt b/planventure-api/requirements.txt new file mode 100644 index 0000000..11babe5 --- /dev/null +++ b/planventure-api/requirements.txt @@ -0,0 +1,5 @@ +# Core dependencies +flask==2.3.3 +flask-sqlalchemy==3.1.1 +flask-cors==4.0.0 +python-dotenv==1.0.0 \ No newline at end of file From 4c062b766e7d00018ea29266021d8353075370db Mon Sep 17 00:00:00 2001 From: LadyKerr Date: Thu, 13 Feb 2025 18:03:45 -0600 Subject: [PATCH 13/20] Update README to include branch switch instructions for local development --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 8ac2bbe..c80b01d 100644 --- a/README.md +++ b/README.md @@ -23,9 +23,10 @@ Before you begin, ensure you have the following: If you prefer to develop locally, follow the steps below: -1. Clone the repository to your local machine: +1. Clone the repository to your local machine and switch to the `apistart` branch: ```sh git clone https://github.com/github-samples/planventure.git +git switch apistart ``` 2. Create a virtual environment and activate it: From ceec435a847b27466f8bcca080bec5795d351bf5 Mon Sep 17 00:00:00 2001 From: LadyKerr Date: Wed, 19 Feb 2025 12:12:38 -0600 Subject: [PATCH 14/20] Add CORS support for trip management routes and handle preflight OPTIONS requests --- planventure-api/routes/trips.py | 33 ++++++++++++++++++++++++++++++--- 1 file changed, 30 insertions(+), 3 deletions(-) diff --git a/planventure-api/routes/trips.py b/planventure-api/routes/trips.py index 886d8bd..f0e1416 100644 --- a/planventure-api/routes/trips.py +++ b/planventure-api/routes/trips.py @@ -1,5 +1,7 @@ -from flask import Blueprint, request, jsonify, current_app +from flask import Blueprint, request, jsonify, current_app, make_response from flask_jwt_extended import get_jwt_identity, verify_jwt_in_request +from flask_cors import cross_origin +from Config import Config from app import db from models import Trip from middleware.auth import auth_middleware @@ -17,9 +19,22 @@ def validate_auth_header(): return False, 'Invalid authorization format. Use Bearer token' return True, None -@trips_bp.route('/trips', methods=['GET', 'POST']) +@trips_bp.route('/trips', methods=['GET', 'POST', 'OPTIONS']) +@cross_origin( + origins=Config.CORS_ORIGINS, + methods=Config.CORS_METHODS, + allow_headers=Config.CORS_HEADERS, + supports_credentials=Config.CORS_SUPPORTS_CREDENTIALS +) @auth_middleware def handle_trips(): + # Handle preflight OPTIONS request + if request.method == 'OPTIONS': + response = make_response() + response.headers.add('Access-Control-Allow-Methods', ','.join(Config.CORS_METHODS)) + response.headers.add('Access-Control-Allow-Headers', ','.join(Config.CORS_HEADERS)) + return response + try: # Log incoming request details token = request.headers.get('Authorization', '').replace('Bearer ', '') @@ -96,9 +111,21 @@ def get_trips(): } for trip in trips] }), 200 -@trips_bp.route('/trips/', methods=['GET', 'PUT', 'DELETE']) +@trips_bp.route('/trips/', methods=['GET', 'PUT', 'DELETE', 'OPTIONS']) +@cross_origin( + origins=Config.CORS_ORIGINS, + methods=Config.CORS_METHODS, + allow_headers=Config.CORS_HEADERS, + supports_credentials=Config.CORS_SUPPORTS_CREDENTIALS +) @auth_middleware def handle_trip(trip_id): + if request.method == 'OPTIONS': + response = make_response() + response.headers.add('Access-Control-Allow-Methods', ','.join(Config.CORS_METHODS)) + response.headers.add('Access-Control-Allow-Headers', ','.join(Config.CORS_HEADERS)) + return response + if request.method == 'GET': return get_trip(trip_id) elif request.method == 'PUT': From 8ddbce3711e2c00e7fb7bd0149cc8a045df4af95 Mon Sep 17 00:00:00 2001 From: LadyKerr Date: Wed, 19 Feb 2025 12:19:11 -0600 Subject: [PATCH 15/20] Fix import statement for configuration in trip management routes --- planventure-api/routes/trips.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/planventure-api/routes/trips.py b/planventure-api/routes/trips.py index f0e1416..78efa57 100644 --- a/planventure-api/routes/trips.py +++ b/planventure-api/routes/trips.py @@ -1,7 +1,7 @@ from flask import Blueprint, request, jsonify, current_app, make_response from flask_jwt_extended import get_jwt_identity, verify_jwt_in_request from flask_cors import cross_origin -from Config import Config +from config import Config from app import db from models import Trip from middleware.auth import auth_middleware From 0e51264bf42aa87574c251dab6aa4bb07d7adfab Mon Sep 17 00:00:00 2001 From: LadyKerr Date: Wed, 19 Feb 2025 12:31:52 -0600 Subject: [PATCH 16/20] Update database schemA --- planventure-api/instance/planventure.db | Bin 16384 -> 16384 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/planventure-api/instance/planventure.db b/planventure-api/instance/planventure.db index 88bbcca14756993f5caaa379cdde3d7cf2f95f8d..b0955cdad1f6e7ae8959f970fb1fe5e05b495b57 100644 GIT binary patch delta 238 zcmZo@U~Fh$oFL7}JyFJ)m775?Z`a0@1^hfLy!ROREBM~?rSaa|EGTe}x4w~;g`GjO zk=4;LCo!ecAvHHKGe<8uKUc*lNyX4eB_}K>zr?dNt31H#jII z(jzG{C#cXnAhjgDEGI8DJ2NOLBR?_8!rjQg$W+(BNY~I(!O+6W$kfWnT+h_Pzz7J? zWjLWy#zvddw<;3EEs6T~JT(|6n0n8mZX%%+PO07yX>_y7O^ From e9e1fa2da94eac06fb32138b9567cd8c74c22c8d Mon Sep 17 00:00:00 2001 From: Christopher Harrison Date: Fri, 21 Feb 2025 17:54:46 +0000 Subject: [PATCH 17/20] Update container files --- .devcontainer/Dockerfile | 15 ++++++++++++++ .devcontainer/devcontainer.json | 28 +++++++++++++++++++++++++ .devcontainer/docker-compose.yml | 35 ++++++++++++++++++++++++++++++++ .github/dependabot.yml | 18 ++++++++++------ 4 files changed, 90 insertions(+), 6 deletions(-) create mode 100644 .devcontainer/Dockerfile create mode 100644 .devcontainer/devcontainer.json create mode 100644 .devcontainer/docker-compose.yml diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile new file mode 100644 index 0000000..e47dd83 --- /dev/null +++ b/.devcontainer/Dockerfile @@ -0,0 +1,15 @@ +FROM mcr.microsoft.com/devcontainers/python:1-3-bookworm + +ENV PYTHONUNBUFFERED 1 + +# [Optional] If your requirements rarely change, uncomment this section to add them to the image. +# COPY requirements.txt /tmp/pip-tmp/ +# RUN pip3 --disable-pip-version-check --no-cache-dir install -r /tmp/pip-tmp/requirements.txt \ +# && rm -rf /tmp/pip-tmp + +# [Optional] Uncomment this section to install additional OS packages. +# RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \ +# && apt-get -y install --no-install-recommends + + + diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json new file mode 100644 index 0000000..1076e45 --- /dev/null +++ b/.devcontainer/devcontainer.json @@ -0,0 +1,28 @@ +// For format details, see https://aka.ms/devcontainer.json. For config options, see the +// README at: https://github.com/devcontainers/templates/tree/main/src/postgres +{ + "name": "Python 3 & PostgreSQL", + "dockerComposeFile": "docker-compose.yml", + "service": "app", + "workspaceFolder": "/workspaces/${localWorkspaceFolderBasename}", + "features": { + "ghcr.io/devcontainers/features/github-cli:1": {}, + "ghcr.io/devcontainers/features/node:1": {} + } + + // Features to add to the dev container. More info: https://containers.dev/features. + // "features": {}, + + // Use 'forwardPorts' to make a list of ports inside the container available locally. + // This can be used to network with other containers or the host. + // "forwardPorts": [5000, 5432], + + // Use 'postCreateCommand' to run commands after the container is created. + // "postCreateCommand": "pip install --user -r requirements.txt", + + // Configure tool-specific properties. + // "customizations": {}, + + // Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root. + // "remoteUser": "root" +} diff --git a/.devcontainer/docker-compose.yml b/.devcontainer/docker-compose.yml new file mode 100644 index 0000000..f2e9705 --- /dev/null +++ b/.devcontainer/docker-compose.yml @@ -0,0 +1,35 @@ +version: '3.8' + +services: + app: + build: + context: .. + dockerfile: .devcontainer/Dockerfile + + volumes: + - ../..:/workspaces:cached + + # Overrides default command so things don't shut down after the process ends. + command: sleep infinity + + # Runs app on the same network as the database container, allows "forwardPorts" in devcontainer.json function. + network_mode: service:db + + # Use "forwardPorts" in **devcontainer.json** to forward an app port locally. + # (Adding the "ports" property to this file will not forward from a Codespace.) + + db: + image: postgres:latest + restart: unless-stopped + volumes: + - postgres-data:/var/lib/postgresql/data + environment: + POSTGRES_USER: postgres + POSTGRES_DB: postgres + POSTGRES_PASSWORD: postgres + + # Add "forwardPorts": ["5432"] to **devcontainer.json** to forward PostgreSQL locally. + # (Adding the "ports" property to this file will not forward from a Codespace.) + +volumes: + postgres-data: diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 308031c..f33a02c 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -1,6 +1,12 @@ -# This is the dependabot configuration file that automates dependency updates -# Updates section configures how dependabot should handle dependency updates: -# - Monitors GitHub Actions workflow dependencies in the root directory -# - Checks for updates weekly -# -# Learn more at https://docs.github.com/en/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file#configuration-options-for-the-dependabotyml-file \ No newline at end of file +# To get started with Dependabot version updates, you'll need to specify which +# package ecosystems to update and where the package manifests are located. +# Please see the documentation for more information: +# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates +# https://containers.dev/guide/dependabot + +version: 2 +updates: + - package-ecosystem: "devcontainers" + directory: "/" + schedule: + interval: weekly From f7c30a01acbb08946e7c4187ba85ad1e5da494b5 Mon Sep 17 00:00:00 2001 From: LadyKerr Date: Mon, 21 Apr 2025 15:29:54 -0500 Subject: [PATCH 18/20] Update .gitignore, README, SECURITY, and SUPPORT files; remove obsolete .gitignore --- .gitignore | 178 ++++++++++++++++++++++++++++++++++++- README.md | 10 +-- SECURITY.md | 31 +++++++ SUPPORT.md | 10 +-- planventure-api/.gitignore | 4 - 5 files changed, 213 insertions(+), 20 deletions(-) create mode 100644 SECURITY.md delete mode 100644 planventure-api/.gitignore diff --git a/.gitignore b/.gitignore index 4d0cc89..b32a9b0 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,180 @@ .vscode # Bruno adds a dir to your vscode workspace Planventure -venv/ \ No newline at end of file +__pycache__ + +# Add the .gitignore from https://github.com/github/gitignore/blob/main/Python.gitignore +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# UV +# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +#uv.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/latest/usage/project/#working-with-version-control +.pdm.toml +.pdm-python +.pdm-build/ + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ + +# Ruff stuff: +.ruff_cache/ + +# PyPI configuration file +.pypirc \ No newline at end of file diff --git a/README.md b/README.md index 7c97131..f230289 100644 --- a/README.md +++ b/README.md @@ -7,9 +7,9 @@ A Flask-based REST API backend for the Planventure application. ## Prerequisites Before you begin, ensure you have the following: -- A GitHub account +- A GitHub account - [sign up for FREE](https://github.com) - Access to GitHub Copilot - [sign up for FREE](https://gh.io/gfb-copilot)! -- A Code Editor +- A Code Editor - [VS Code](https://code.visualstudio.com/download) is recommended - API Client (like [Bruno](https://github.com/usebruno/bruno)) - Git - [Download & Install Git](https://git-scm.com/downloads) @@ -23,7 +23,7 @@ Before you begin, ensure you have the following: If you prefer to develop locally, follow the steps below: -1. Clone the repository and navigate to the [planventue-api](/planventure-api/) directory: +1.Fork and clone the repository and navigate to the [planventue-api](/planventure-api/) directory: ```sh cd planventure-api ``` @@ -49,10 +49,6 @@ cp .sample.env .env flask run ``` -## Docker Setup - -If bulding locally, follow the Docker setup steps in the [DockerSetup](DockerSetup) file. - ## πŸ“š API Endpoints - GET / - Welcome message - GET /health - Health check endpoint diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..c176aa9 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,31 @@ +# Security + +Thanks for helping make GitHub safe for everyone. + +GitHub takes the security of our software products and services seriously, including all of the open source code repositories managed through our GitHub organizations, such as [GitHub](https://github.com/GitHub). + +Even though [open source repositories are outside of the scope of our bug bounty program](https://bounty.github.com/index.html#scope) and therefore not eligible for bounty rewards, we will ensure that your finding gets passed along to the appropriate maintainers for remediation. + +## Reporting Security Issues + +If you believe you have found a security vulnerability in any GitHub-owned repository, please report it to us through coordinated disclosure. + +**Please do not report security vulnerabilities through public GitHub issues, discussions, or pull requests.** + +Instead, please send an email to opensource-security[@]github.com. + +Please include as much of the information listed below as you can to help us better understand and resolve the issue: + + * The type of issue (e.g., buffer overflow, SQL injection, or cross-site scripting) + * Full paths of source file(s) related to the manifestation of the issue + * The location of the affected source code (tag/branch/commit or direct URL) + * Any special configuration required to reproduce the issue + * Step-by-step instructions to reproduce the issue + * Proof-of-concept or exploit code (if possible) + * Impact of the issue, including how an attacker might exploit the issue + +This information will help us triage your report more quickly. + +## Policy + +See [GitHub's Safe Harbor Policy](https://docs.github.com/en/site-policy/security-policies/github-bug-bounty-program-legal-safe-harbor#1-safe-harbor-terms) \ No newline at end of file diff --git a/SUPPORT.md b/SUPPORT.md index 0726719..be056c0 100644 --- a/SUPPORT.md +++ b/SUPPORT.md @@ -1,20 +1,14 @@ -# TODO: The maintainer of this repo has not updated this file - # Support ## How to file issues and get help This project uses GitHub issues to track bugs and feature requests. Please search the existing issues before filing new issues to avoid duplicates. For new issues, file your bug or feature request as a new issue. -For help or questions about using this project, please **TODO:** REPO MAINTAINER TO INSERT INSTRUCTIONS ON HOW TO ENGAGE REPO OWNERS OR COMMUNITY FOR HELP. COULD BE A SLACK OR DISCORD OR OTHER CHANNEL FOR HELP. WHERE WILL YOU HELP PEOPLE? +For help or questions about using this project, please open a new issue. The maintainers and community will try to help you as best as they can. -**TODO: REPO MAINTAINERS** Please include one of the following statements file: +**PLANVENTURE** is not actively developed but is maintained by GitHub staff **AND THE COMMUNITY**. We will do our best to respond to support and community questions in a timely manner. -- **THIS PROJECT NAME** is under active development and maintained by GitHub staff **AND THE COMMUNITY**. We will do our best to respond to support, feature requests, and community questions in a timely manner. -- **THIS PROJECT NAME** is not actively developed but is maintained by GitHub staff **AND THE COMMUNITY**. We will do our best to respond to support and community questions in a timely manner. -- **THIS PROJECT NAME** is no longer supported or maintained by GitHub staff. We will not respond to support or community questions. -- **THIS PROJECT NAME** is archived and deprecated. As an unsupported project, feel free to fork. ## GitHub Support Policy diff --git a/planventure-api/.gitignore b/planventure-api/.gitignore deleted file mode 100644 index 4936acf..0000000 --- a/planventure-api/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -venv/ -.env -__pycache__/ -*.pyc From 46a72eef64529b6c9a5dac20e900dc7127383b60 Mon Sep 17 00:00:00 2001 From: LadyKerr Date: Mon, 21 Apr 2025 16:00:52 -0500 Subject: [PATCH 19/20] Set up development environment with Docker, Docker Compose, and PostgreSQL; update README and add security guidelines --- .devcontainer/Dockerfile | 12 ++ .devcontainer/devcontainer.json | 64 ++++---- .devcontainer/docker-compose.yml | 35 +++++ .gitignore | 179 +++++++++++++++++++++- README.md | 21 +-- SECURITY.md | 31 ++++ SUPPORT.md | 10 +- docs/0-pre-requisites.md | 16 -- docs/1-introduction.md | 16 -- docs/README.md | 11 -- docs/images/README.md | 3 - docs/template.md | 24 --- planventure-api/PROMPTS.md | 252 +++++++++++++++++++++++++++++++ 13 files changed, 543 insertions(+), 131 deletions(-) create mode 100644 .devcontainer/Dockerfile create mode 100644 .devcontainer/docker-compose.yml create mode 100644 SECURITY.md delete mode 100644 docs/0-pre-requisites.md delete mode 100644 docs/1-introduction.md delete mode 100644 docs/README.md delete mode 100644 docs/images/README.md delete mode 100644 docs/template.md create mode 100644 planventure-api/PROMPTS.md diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile new file mode 100644 index 0000000..7d6e641 --- /dev/null +++ b/.devcontainer/Dockerfile @@ -0,0 +1,12 @@ +FROM mcr.microsoft.com/devcontainers/python:1-3-bookworm + +ENV PYTHONUNBUFFERED 1 + +# [Optional] If your requirements rarely change, uncomment this section to add them to the image. +# COPY requirements.txt /tmp/pip-tmp/ +# RUN pip3 --disable-pip-version-check --no-cache-dir install -r /tmp/pip-tmp/requirements.txt \ +# && rm -rf /tmp/pip-tmp + +# [Optional] Uncomment this section to install additional OS packages. +# RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \ +# && apt-get -y install --no-install-recommends \ No newline at end of file diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index 292c1c7..c73d7a3 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -1,40 +1,28 @@ // For format details, see https://aka.ms/devcontainer.json. For config options, see the -// README at: https://github.com/devcontainers/templates/tree/main/src/go +// README at: https://github.com/devcontainers/templates/tree/main/src/postgres { - "name": "Game of Life Walkthrough", - // Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile - "image": "mcr.microsoft.com/devcontainers/universal:latest", - - // Use 'forwardPorts' to make a list of ports inside the container available locally. - "forwardPorts": [ - 3000 - ], - - // Use 'postCreateCommand' to run commands after the container is created. - // "postCreateCommand": "" - - // Configure tool-specific properties. - "customizations": { - "codespaces": { - "openFiles": [ - "index.html", - "README.md" - ] - }, - "vscode": { - "extensions": [ - "GitHub.codespaces", - "GitHub.copilot", - "GitHub.copilot-chat", - "github.copilot-workspace", - "GitHub.remotehub", - "github.vscode-github-actions", - "GitHub.vscode-pull-request-github", - "ms-vscode.live-server" - ] - } - } - - // Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root. - // "remoteUser": "root" - } + "name": "Python 3 & PostgreSQL", + "dockerComposeFile": "docker-compose.yml", + "service": "app", + "workspaceFolder": "/workspaces/${localWorkspaceFolderBasename}", + "features": { + "ghcr.io/devcontainers/features/github-cli:1": {}, + "ghcr.io/devcontainers/features/node:1": {} + } + + // Features to add to the dev container. More info: https://containers.dev/features. + // "features": {}, + + // Use 'forwardPorts' to make a list of ports inside the container available locally. + // This can be used to network with other containers or the host. + // "forwardPorts": [5000, 5432], + + // Use 'postCreateCommand' to run commands after the container is created. + // "postCreateCommand": "pip install --user -r requirements.txt", + + // Configure tool-specific properties. + // "customizations": {}, + + // Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root. + // "remoteUser": "root" +} \ No newline at end of file diff --git a/.devcontainer/docker-compose.yml b/.devcontainer/docker-compose.yml new file mode 100644 index 0000000..42dfa2a --- /dev/null +++ b/.devcontainer/docker-compose.yml @@ -0,0 +1,35 @@ +version: '3.8' + +services: + app: + build: + context: .. + dockerfile: .devcontainer/Dockerfile + + volumes: + - ../..:/workspaces:cached + + # Overrides default command so things don't shut down after the process ends. + command: sleep infinity + + # Runs app on the same network as the database container, allows "forwardPorts" in devcontainer.json function. + network_mode: service:db + + # Use "forwardPorts" in **devcontainer.json** to forward an app port locally. + # (Adding the "ports" property to this file will not forward from a Codespace.) + + db: + image: postgres:latest + restart: unless-stopped + volumes: + - postgres-data:/var/lib/postgresql/data + environment: + POSTGRES_USER: postgres + POSTGRES_DB: postgres + POSTGRES_PASSWORD: postgres + + # Add "forwardPorts": ["5432"] to **devcontainer.json** to forward PostgreSQL locally. + # (Adding the "ports" property to this file will not forward from a Codespace.) + +volumes: + postgres-data: \ No newline at end of file diff --git a/.gitignore b/.gitignore index 203bd53..1b51498 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,181 @@ .vscode # Bruno adds a dir to your vscode workspace Planventure -__pycache__ \ No newline at end of file +__pycache__ +.DS_Store + +# Add the .gitignore from https://github.com/github/gitignore/blob/main/Python.gitignore +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# UV +# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +#uv.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/latest/usage/project/#working-with-version-control +.pdm.toml +.pdm-python +.pdm-build/ + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ + +# Ruff stuff: +.ruff_cache/ + +# PyPI configuration file +.pypirc \ No newline at end of file diff --git a/README.md b/README.md index c80b01d..165606a 100644 --- a/README.md +++ b/README.md @@ -23,10 +23,9 @@ Before you begin, ensure you have the following: If you prefer to develop locally, follow the steps below: -1. Clone the repository to your local machine and switch to the `apistart` branch: +1.Fork and clone the repository and navigate to the [planventue-api](/planventure-api/) directory: ```sh -git clone https://github.com/github-samples/planventure.git -git switch apistart +cd planventure-api ``` 2. Create a virtual environment and activate it: @@ -35,24 +34,19 @@ python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate ``` -3. Navigate to the [planventue-api](/planventure-api/) directory: -```sh -cd planventure-api -``` - -4. Install the required dependencies: +3. Install the required dependencies: ```sh pip install -r requirements.txt ``` -5. Create an `.env` file based on [.sample.env](.sample.env): +4. Create an `.env` file based on [.sample.env](/planventure-api/.sample.env): ```sh cp .sample.env .env ``` -6. Start the Flask development server: +5. Start the Flask development server: ```sh -flask run --debug +flask run ``` ## πŸ“š API Endpoints @@ -61,5 +55,4 @@ flask run --debug ## πŸ“ License -This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. -Footer \ No newline at end of file +This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. \ No newline at end of file diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..c176aa9 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,31 @@ +# Security + +Thanks for helping make GitHub safe for everyone. + +GitHub takes the security of our software products and services seriously, including all of the open source code repositories managed through our GitHub organizations, such as [GitHub](https://github.com/GitHub). + +Even though [open source repositories are outside of the scope of our bug bounty program](https://bounty.github.com/index.html#scope) and therefore not eligible for bounty rewards, we will ensure that your finding gets passed along to the appropriate maintainers for remediation. + +## Reporting Security Issues + +If you believe you have found a security vulnerability in any GitHub-owned repository, please report it to us through coordinated disclosure. + +**Please do not report security vulnerabilities through public GitHub issues, discussions, or pull requests.** + +Instead, please send an email to opensource-security[@]github.com. + +Please include as much of the information listed below as you can to help us better understand and resolve the issue: + + * The type of issue (e.g., buffer overflow, SQL injection, or cross-site scripting) + * Full paths of source file(s) related to the manifestation of the issue + * The location of the affected source code (tag/branch/commit or direct URL) + * Any special configuration required to reproduce the issue + * Step-by-step instructions to reproduce the issue + * Proof-of-concept or exploit code (if possible) + * Impact of the issue, including how an attacker might exploit the issue + +This information will help us triage your report more quickly. + +## Policy + +See [GitHub's Safe Harbor Policy](https://docs.github.com/en/site-policy/security-policies/github-bug-bounty-program-legal-safe-harbor#1-safe-harbor-terms) \ No newline at end of file diff --git a/SUPPORT.md b/SUPPORT.md index 0726719..be056c0 100644 --- a/SUPPORT.md +++ b/SUPPORT.md @@ -1,20 +1,14 @@ -# TODO: The maintainer of this repo has not updated this file - # Support ## How to file issues and get help This project uses GitHub issues to track bugs and feature requests. Please search the existing issues before filing new issues to avoid duplicates. For new issues, file your bug or feature request as a new issue. -For help or questions about using this project, please **TODO:** REPO MAINTAINER TO INSERT INSTRUCTIONS ON HOW TO ENGAGE REPO OWNERS OR COMMUNITY FOR HELP. COULD BE A SLACK OR DISCORD OR OTHER CHANNEL FOR HELP. WHERE WILL YOU HELP PEOPLE? +For help or questions about using this project, please open a new issue. The maintainers and community will try to help you as best as they can. -**TODO: REPO MAINTAINERS** Please include one of the following statements file: +**PLANVENTURE** is not actively developed but is maintained by GitHub staff **AND THE COMMUNITY**. We will do our best to respond to support and community questions in a timely manner. -- **THIS PROJECT NAME** is under active development and maintained by GitHub staff **AND THE COMMUNITY**. We will do our best to respond to support, feature requests, and community questions in a timely manner. -- **THIS PROJECT NAME** is not actively developed but is maintained by GitHub staff **AND THE COMMUNITY**. We will do our best to respond to support and community questions in a timely manner. -- **THIS PROJECT NAME** is no longer supported or maintained by GitHub staff. We will not respond to support or community questions. -- **THIS PROJECT NAME** is archived and deprecated. As an unsupported project, feel free to fork. ## GitHub Support Policy diff --git a/docs/0-pre-requisites.md b/docs/0-pre-requisites.md deleted file mode 100644 index e0d51b4..0000000 --- a/docs/0-pre-requisites.md +++ /dev/null @@ -1,16 +0,0 @@ -# Pre-requisites - -| [← Back to README][walkthrough-previous] | [Next: Introduction β†’][walkthrough-next] | -|:-----------------------------------|------------------------------------------:| - -List all the pre-requisites needed for this walkthrough. This may include software, tools, accounts, etc. - -- Pre-requisite 1 -- Pre-requisite 2 -- Pre-requisite 3 - -| [← Back to README][walkthrough-previous] | [Next: Introduction β†’][walkthrough-next] | -|:-----------------------------------|------------------------------------------:| - -[walkthrough-previous]: ../README.md -[walkthrough-next]: 1-introduction.md diff --git a/docs/1-introduction.md b/docs/1-introduction.md deleted file mode 100644 index 66a07fe..0000000 --- a/docs/1-introduction.md +++ /dev/null @@ -1,16 +0,0 @@ -# Introduction - -| [← Back to Pre-requisites][walkthrough-previous] | [Next: Template β†’][walkthrough-next] | -|:-----------------------------------|------------------------------------------:| - -Provide an introduction to your walkthrough. Explain the purpose, goals, and any other relevant information. - -- Overview of the walkthrough -- Objectives -- Expected outcomes - -| [← Back to Pre-requisites][walkthrough-previous] | [Next: Template β†’][walkthrough-next] | -|:-----------------------------------|------------------------------------------:| - -[walkthrough-previous]: 0-pre-requisites.md -[walkthrough-next]: template.md diff --git a/docs/README.md b/docs/README.md deleted file mode 100644 index 36a21d1..0000000 --- a/docs/README.md +++ /dev/null @@ -1,11 +0,0 @@ -# Table of Contents - -This folder contains the documentation for your walkthrough. Please update the individual pages to reflect the content of your walkthrough. - -## Pages - -1. [Pre-requisites](0-pre-requisites.md) -2. [Introduction](1-introduction.md) -3. [Template](template.md) - -Feel free to add more pages as needed. diff --git a/docs/images/README.md b/docs/images/README.md deleted file mode 100644 index 2fd76e4..0000000 --- a/docs/images/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# Supporting Images - -Please upload your images to this folder for consistency. \ No newline at end of file diff --git a/docs/template.md b/docs/template.md deleted file mode 100644 index e68d394..0000000 --- a/docs/template.md +++ /dev/null @@ -1,24 +0,0 @@ -# Page Title - -| [← Back to Introduction][walkthrough-previous] | [Next: (Next Page) β†’][walkthrough-next] | -|:-----------------------------------|------------------------------------------:| - -Use this template to create new pages for your walkthrough. Replace the headings and content with your own. - -## Heading 1 - -Content for heading 1. - -## Heading 2 - -Content for heading 2. - -## Heading 3 - -Content for heading 3. - -| [← Back to Introduction][walkthrough-previous] | [Next: (Next Page) β†’][walkthrough-next] | -|:-----------------------------------|------------------------------------------:| - -[walkthrough-previous]: 1-introduction.md -[walkthrough-next]: (next-page).md diff --git a/planventure-api/PROMPTS.md b/planventure-api/PROMPTS.md new file mode 100644 index 0000000..60b4ee9 --- /dev/null +++ b/planventure-api/PROMPTS.md @@ -0,0 +1,252 @@ +# Building the Planventure API with GitHub Copilot + +This guide will walk you through creating a Flask-based REST API with SQLAlchemy and JWT authentication using GitHub Copilot to accelerate development. + +## Prerequisites + +- Python 3.8 or higher +- VS Code with GitHub Copilot extension +- Bruno API Client (for testing API endpoints) +- Git installed + +## Project Structure + +We'll be working in the `api-start` branch and creating a structured API with: +- Authentication system +- Database models +- CRUD operations for trips +- JWT token protection + +## Step 1: Project Setup +### Prompts to Configure Flask with SQLAlchemy + +Open Copilot Chat and type: +``` +@workspace Update the Flask app with SQLAlchemy and basic configurations +``` + +When the code is generated, click "Apply in editor" to update your `app.py` file. + +### Update Dependencies + +In Copilot Chat, type: +``` +update requirements.txt with necessary packages for Flask API with SQLAlchemy and JWT +``` + +Install the updated dependencies: +```bash +pip install -r requirements.txt +``` + +### Create .env File + +Create a `.env` file for environment variables and add it to `.gitignore`. + +## Step 2: Database Models + +### User Model + +In Copilot Edits, type: +``` +Create SQLAlchemy User model with email, password_hash, and timestamps. add code in new files +``` + +Review and accept the generated code. + +### Initialize Database Tables + +Ask Copilot to create a database initialization script: +``` +update code to be able to create the db tables with a python shell script +``` + +Run the initialization script: +```bash +python init_db.py +``` + +### Install SQLite Viewer Extension + +1. Go to VS Code extensions +2. Search for "SQLite viewer" +3. Install the extension +4. Click on `init_db.py` to view the created tables + +### Trip Model + +In Copilot Edits, type: +``` +Create SQLAlchemy Trip model with user relationship, destination, start date, end date, coordinates and itinerary +``` + +Accept changes and run the initialization script again: +```bash +python3 init_db.py +``` + +### Commit Your Changes + +Use Source Control in VS Code: +1. Stage all changes +2. Click the sparkle icon to generate a commit message with Copilot +3. Click commit + +## Step 3: Authentication System + +### Password Hashing Utilities + +In Copilot Edits, type: +``` +Create password hashing and salt utility functions for the User model +``` + +Review, accept changes, and install required packages: +```bash +pip install bcrypt +``` + +### JWT Token Functions + +In Copilot Edits, type: +``` +Setup JWT token generation and validation functions +``` + +Review, accept changes, and install the JWT package: +```bash +pip install flask-jwt-extended +``` + +### Registration Route + +In Copilot Edits, type: +``` +Create auth routes for user registration with email validation +``` + +Review and accept the changes. + +### Test Registration Route + +Use Bruno API Client: +1. Create a new POST request +2. Set URL to `http://localhost:5000/auth/register` +3. Add header: `Content-Type: application/json` +4. Add JSON body: +```json +{ + "email": "user@example.com", + "password": "test1234" +} +``` +5. Send the request and verify the response + +### Login Route + +In Copilot Edits, type: +``` +Create login route with JWT token generation +``` + +Review, accept changes, and restart the Flask server. + +### Enable Development Mode + +To have Flask automatically reload on code changes: + +```bash +export FLASK_DEBUG=1 +flask run +``` + +### Authentication Middleware + +In Copilot Edits, type: +``` +Create auth middleware to protect routes +``` + +Review and accept the changes. + +### Commit Your Changes + +Use Source Control and Copilot to create a commit message. + +## Step 4: Trip Routes + +### Create Trip Routes Blueprint + +In Copilot Edits, type: +``` +Create Trip routes blueprint with CRUD operations +``` + +Review and accept the changes. + +> **Note**: Ensure that `verify_jwt_in_request` is set to `verify_jwt_in_request(optional=True)` if needed + +### Test Trip Routes + +Use Bruno API Client to test: +1. CREATE a new trip +2. GET a trip by ID + +### Add Itinerary Template Generator + +In Copilot Edits, type: +``` +Create function to generate default itinerary template +``` + +Review, accept changes, and test the updated route. + +## Step 5: Finalize API + +### Configure CORS for Frontend Access + +In Copilot Edits, type: +``` +Setup CORS configuration for React frontend +``` + +Review and accept the changes. + +### Add Health Check Endpoint + +In Copilot Edits, type: +``` +Create basic health check endpoint +``` + +Review and accept the changes. + +### Commit Final Changes + +Use Source Control with Copilot to create your final commit. + +### Create README + +Ask Copilot to write a comprehensive README for your API project. + +## Common Issues and Solutions + +### GOTCHAS: + +- Ensure there are no trailing slashes in any of the routes - especially the base `/trip` route +- Make sure all required packages are installed +- Check that JWT token validation is configured correctly +- Verify database tables are created properly using the SQLite viewer + +## Next Steps + +Consider these enhancements for your API: +- Add more comprehensive input validation +- Create custom error handlers for HTTP exceptions +- Setup logging configuration +- Add validation error handlers for form data +- Configure database migrations + +## Conclusion + +You now have a fully functional API with authentication, database models, and protected routes. This can serve as the backend for your Planventure application! \ No newline at end of file From f24d4b7cd0d81326ac3c9b03d5525df1b4049634 Mon Sep 17 00:00:00 2001 From: LadyKerr Date: Mon, 21 Apr 2025 16:09:21 -0500 Subject: [PATCH 20/20] Update dependabot configuration to monitor pip dependencies in the planventure-api directory --- .github/dependabot.yml | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 308031c..19d5e29 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -1,6 +1,14 @@ # This is the dependabot configuration file that automates dependency updates # Updates section configures how dependabot should handle dependency updates: -# - Monitors GitHub Actions workflow dependencies in the root directory +# - Monitors pip dependencies in the planventure-api directory # - Checks for updates weekly # -# Learn more at https://docs.github.com/en/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file#configuration-options-for-the-dependabotyml-file \ No newline at end of file +version: 2 +updates: + - package-ecosystem: "pip" + directory: "/planventure-api" + schedule: + interval: "weekly" + labels: + - "dependencies" + - "python" \ No newline at end of file pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy