Repository: fastapi/full-stack-fastapi-template Branch: master Commit: 8bf00250399b Files: 215 Total size: 593.3 KB Directory structure: gitextract_rs686u55/ ├── .copier/ │ ├── .copier-answers.yml.jinja │ └── update_dotenv.py ├── .gitattributes ├── .github/ │ ├── DISCUSSION_TEMPLATE/ │ │ └── questions.yml │ ├── FUNDING.yml │ ├── ISSUE_TEMPLATE/ │ │ ├── config.yml │ │ └── privileged.yml │ ├── dependabot.yml │ ├── labeler.yml │ └── workflows/ │ ├── add-to-project.yml │ ├── deploy-production.yml │ ├── deploy-staging.yml │ ├── detect-conflicts.yml │ ├── issue-manager.yml │ ├── labeler.yml │ ├── latest-changes.yml │ ├── playwright.yml │ ├── pre-commit.yml │ ├── smokeshow.yml │ ├── test-backend.yml │ └── test-docker-compose.yml ├── .gitignore ├── .pre-commit-config.yaml ├── .vscode/ │ └── extensions.json ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── SECURITY.md ├── backend/ │ ├── .dockerignore │ ├── .gitignore │ ├── Dockerfile │ ├── README.md │ ├── alembic.ini │ ├── app/ │ │ ├── __init__.py │ │ ├── alembic/ │ │ │ ├── README │ │ │ ├── env.py │ │ │ ├── script.py.mako │ │ │ └── versions/ │ │ │ ├── .keep │ │ │ ├── 1a31ce608336_add_cascade_delete_relationships.py │ │ │ ├── 9c0a54914c78_add_max_length_for_string_varchar_.py │ │ │ ├── d98dd8ec85a3_edit_replace_id_integers_in_all_models_.py │ │ │ ├── e2412789c190_initialize_models.py │ │ │ └── fe56fa70289e_add_created_at_to_user_and_item.py │ │ ├── api/ │ │ │ ├── __init__.py │ │ │ ├── deps.py │ │ │ ├── main.py │ │ │ └── routes/ │ │ │ ├── __init__.py │ │ │ ├── items.py │ │ │ ├── login.py │ │ │ ├── private.py │ │ │ ├── users.py │ │ │ └── utils.py │ │ ├── backend_pre_start.py │ │ ├── core/ │ │ │ ├── __init__.py │ │ │ ├── config.py │ │ │ ├── db.py │ │ │ └── security.py │ │ ├── crud.py │ │ ├── email-templates/ │ │ │ ├── build/ │ │ │ │ ├── new_account.html │ │ │ │ ├── reset_password.html │ │ │ │ └── test_email.html │ │ │ └── src/ │ │ │ ├── new_account.mjml │ │ │ ├── reset_password.mjml │ │ │ └── test_email.mjml │ │ ├── initial_data.py │ │ ├── main.py │ │ ├── models.py │ │ ├── tests_pre_start.py │ │ └── utils.py │ ├── pyproject.toml │ ├── scripts/ │ │ ├── format.sh │ │ ├── lint.sh │ │ ├── prestart.sh │ │ ├── test.sh │ │ └── tests-start.sh │ └── tests/ │ ├── __init__.py │ ├── api/ │ │ ├── __init__.py │ │ └── routes/ │ │ ├── __init__.py │ │ ├── test_items.py │ │ ├── test_login.py │ │ ├── test_private.py │ │ └── test_users.py │ ├── conftest.py │ ├── crud/ │ │ ├── __init__.py │ │ └── test_user.py │ ├── scripts/ │ │ ├── __init__.py │ │ ├── test_backend_pre_start.py │ │ └── test_test_pre_start.py │ └── utils/ │ ├── __init__.py │ ├── item.py │ ├── user.py │ └── utils.py ├── compose.override.yml ├── compose.traefik.yml ├── compose.yml ├── copier.yml ├── deployment.md ├── development.md ├── frontend/ │ ├── .dockerignore │ ├── .gitignore │ ├── Dockerfile │ ├── Dockerfile.playwright │ ├── README.md │ ├── biome.json │ ├── components.json │ ├── index.html │ ├── nginx-backend-not-found.conf │ ├── nginx.conf │ ├── openapi-ts.config.ts │ ├── package.json │ ├── playwright.config.ts │ ├── src/ │ │ ├── client/ │ │ │ ├── core/ │ │ │ │ ├── ApiError.ts │ │ │ │ ├── ApiRequestOptions.ts │ │ │ │ ├── ApiResult.ts │ │ │ │ ├── CancelablePromise.ts │ │ │ │ ├── OpenAPI.ts │ │ │ │ └── request.ts │ │ │ ├── index.ts │ │ │ ├── schemas.gen.ts │ │ │ ├── sdk.gen.ts │ │ │ └── types.gen.ts │ │ ├── components/ │ │ │ ├── Admin/ │ │ │ │ ├── AddUser.tsx │ │ │ │ ├── DeleteUser.tsx │ │ │ │ ├── EditUser.tsx │ │ │ │ ├── UserActionsMenu.tsx │ │ │ │ └── columns.tsx │ │ │ ├── Common/ │ │ │ │ ├── Appearance.tsx │ │ │ │ ├── AuthLayout.tsx │ │ │ │ ├── DataTable.tsx │ │ │ │ ├── ErrorComponent.tsx │ │ │ │ ├── Footer.tsx │ │ │ │ ├── Logo.tsx │ │ │ │ └── NotFound.tsx │ │ │ ├── Items/ │ │ │ │ ├── AddItem.tsx │ │ │ │ ├── DeleteItem.tsx │ │ │ │ ├── EditItem.tsx │ │ │ │ ├── ItemActionsMenu.tsx │ │ │ │ └── columns.tsx │ │ │ ├── Pending/ │ │ │ │ ├── PendingItems.tsx │ │ │ │ └── PendingUsers.tsx │ │ │ ├── Sidebar/ │ │ │ │ ├── AppSidebar.tsx │ │ │ │ ├── Main.tsx │ │ │ │ └── User.tsx │ │ │ ├── UserSettings/ │ │ │ │ ├── ChangePassword.tsx │ │ │ │ ├── DeleteAccount.tsx │ │ │ │ ├── DeleteConfirmation.tsx │ │ │ │ └── UserInformation.tsx │ │ │ ├── theme-provider.tsx │ │ │ └── ui/ │ │ │ ├── alert.tsx │ │ │ ├── avatar.tsx │ │ │ ├── badge.tsx │ │ │ ├── button-group.tsx │ │ │ ├── button.tsx │ │ │ ├── card.tsx │ │ │ ├── checkbox.tsx │ │ │ ├── dialog.tsx │ │ │ ├── dropdown-menu.tsx │ │ │ ├── form.tsx │ │ │ ├── input.tsx │ │ │ ├── label.tsx │ │ │ ├── loading-button.tsx │ │ │ ├── pagination.tsx │ │ │ ├── password-input.tsx │ │ │ ├── select.tsx │ │ │ ├── separator.tsx │ │ │ ├── sheet.tsx │ │ │ ├── sidebar.tsx │ │ │ ├── skeleton.tsx │ │ │ ├── sonner.tsx │ │ │ ├── table.tsx │ │ │ ├── tabs.tsx │ │ │ └── tooltip.tsx │ │ ├── hooks/ │ │ │ ├── useAuth.ts │ │ │ ├── useCopyToClipboard.ts │ │ │ ├── useCustomToast.ts │ │ │ └── useMobile.ts │ │ ├── index.css │ │ ├── lib/ │ │ │ └── utils.ts │ │ ├── main.tsx │ │ ├── routeTree.gen.ts │ │ ├── routes/ │ │ │ ├── __root.tsx │ │ │ ├── _layout/ │ │ │ │ ├── admin.tsx │ │ │ │ ├── index.tsx │ │ │ │ ├── items.tsx │ │ │ │ └── settings.tsx │ │ │ ├── _layout.tsx │ │ │ ├── login.tsx │ │ │ ├── recover-password.tsx │ │ │ ├── reset-password.tsx │ │ │ └── signup.tsx │ │ ├── utils.ts │ │ └── vite-env.d.ts │ ├── tests/ │ │ ├── admin.spec.ts │ │ ├── auth.setup.ts │ │ ├── config.ts │ │ ├── items.spec.ts │ │ ├── login.spec.ts │ │ ├── reset-password.spec.ts │ │ ├── sign-up.spec.ts │ │ ├── user-settings.spec.ts │ │ └── utils/ │ │ ├── mailcatcher.ts │ │ ├── privateApi.ts │ │ ├── random.ts │ │ └── user.ts │ ├── tsconfig.build.json │ ├── tsconfig.json │ ├── tsconfig.node.json │ └── vite.config.ts ├── hooks/ │ └── post_gen_project.py ├── package.json ├── pyproject.toml ├── release-notes.md └── scripts/ ├── generate-client.sh ├── test-local.sh └── test.sh ================================================ FILE CONTENTS ================================================ ================================================ FILE: .copier/.copier-answers.yml.jinja ================================================ {{ _copier_answers|to_json -}} ================================================ FILE: .copier/update_dotenv.py ================================================ from pathlib import Path import json # Update the .env file with the answers from the .copier-answers.yml file # without using Jinja2 templates in the .env file, this way the code works as is # without needing Copier, but if Copier is used, the .env file will be updated root_path = Path(__file__).parent.parent answers_path = Path(__file__).parent / ".copier-answers.yml" answers = json.loads(answers_path.read_text()) env_path = root_path / ".env" env_content = env_path.read_text() lines = [] for line in env_content.splitlines(): for key, value in answers.items(): upper_key = key.upper() if line.startswith(f"{upper_key}="): if " " in value: content = f"{upper_key}={value!r}" else: content = f"{upper_key}={value}" new_line = line.replace(line, content) lines.append(new_line) break else: lines.append(line) env_path.write_text("\n".join(lines)) ================================================ FILE: .gitattributes ================================================ * text=auto *.sh text eol=lf ================================================ FILE: .github/DISCUSSION_TEMPLATE/questions.yml ================================================ labels: [question] body: - type: markdown attributes: value: | Thanks for your interest in this project! 🚀 Please follow these instructions, fill every question, and do every step. 🙏 I'm asking this because answering questions and solving problems in GitHub is what consumes most of the time. I end up not being able to add new features, fix bugs, review pull requests, etc. as fast as I wish because I have to spend too much time handling questions. All that, on top of all the incredible help provided by a bunch of community members, that give a lot of their time to come here and help others. That's a lot of work, but if more users came to help others like them just a little bit more, it would be much less effort for them (and you and me 😅). By asking questions in a structured way (following this) it will be much easier to help you. And there's a high chance that you will find the solution along the way and you won't even have to submit it and wait for an answer. 😎 As there are too many questions, I'll have to discard and close the incomplete ones. That will allow me (and others) to focus on helping people like you that follow the whole process and help us help you. 🤓 - type: checkboxes id: checks attributes: label: First Check description: Please confirm and check all the following options. options: - label: I added a very descriptive title here. required: true - label: I used the GitHub search to find a similar question and didn't find it. required: true - label: I searched in the documentation/README. required: true - label: I already searched in Google "How to do X" and didn't find any information. required: true - label: I already read and followed all the tutorial in the docs/README and didn't find an answer. required: true - type: checkboxes id: help attributes: label: Commit to Help description: | After submitting this, I commit to one of: * Read open questions until I find 2 where I can help someone and add a comment to help there. * I already hit the "watch" button in this repository to receive notifications and I commit to help at least 2 people that ask questions in the future. options: - label: I commit to help with one of those options 👆 required: true - type: textarea id: example attributes: label: Example Code description: | Please add a self-contained, [minimal, reproducible, example](https://stackoverflow.com/help/minimal-reproducible-example) with your use case. If I (or someone) can copy it, run it, and see it right away, there's a much higher chance I (or someone) will be able to help you. placeholder: | Write your example code here. render: Text validations: required: true - type: textarea id: description attributes: label: Description description: | What is the problem, question, or error? Write a short description telling me what you are doing, what you expect to happen, and what is currently happening. placeholder: | * Open the browser and call the endpoint `/`. * It returns a JSON with `{"message": "Hello World"}`. * But I expected it to return `{"message": "Hello Morty"}`. validations: required: true - type: dropdown id: os attributes: label: Operating System description: What operating system are you on? multiple: true options: - Linux - Windows - macOS - Other validations: required: true - type: textarea id: os-details attributes: label: Operating System Details description: You can add more details about your operating system here, in particular if you chose "Other". validations: required: true - type: input id: python-version attributes: label: Python Version description: | What Python version are you using? You can find the Python version with: ```bash python --version ``` validations: required: true - type: textarea id: context attributes: label: Additional Context description: Add any additional context information or screenshots you think are useful. ================================================ FILE: .github/FUNDING.yml ================================================ github: [tiangolo] ================================================ FILE: .github/ISSUE_TEMPLATE/config.yml ================================================ blank_issues_enabled: false contact_links: - name: Security Contact about: Please report security vulnerabilities to security@tiangolo.com - name: Question or Problem about: Ask a question or ask about a problem in GitHub Discussions. url: https://github.com/fastapi/full-stack-fastapi-template/discussions/categories/questions - name: Feature Request about: To suggest an idea or ask about a feature, please start with a question saying what you would like to achieve. There might be a way to do it already. url: https://github.com/fastapi/full-stack-fastapi-template/discussions/categories/questions ================================================ FILE: .github/ISSUE_TEMPLATE/privileged.yml ================================================ name: Privileged description: You are @tiangolo or he asked you directly to create an issue here. If not, check the other options. 👇 body: - type: markdown attributes: value: | Thanks for your interest in this project! 🚀 If you are not @tiangolo or he didn't ask you directly to create an issue here, please start the conversation in a [Question in GitHub Discussions](https://github.com/tiangolo/full-stack-fastapi-template/discussions/categories/questions) instead. - type: checkboxes id: privileged attributes: label: Privileged issue description: Confirm that you are allowed to create an issue here. options: - label: I'm @tiangolo or he asked me directly to create an issue here. required: true - type: textarea id: content attributes: label: Issue Content description: Add the content of the issue here. ================================================ FILE: .github/dependabot.yml ================================================ version: 2 updates: # GitHub Actions - package-ecosystem: github-actions directory: / schedule: interval: daily commit-message: prefix: ⬆ labels: [dependencies, internal] # Python uv - package-ecosystem: uv directory: / schedule: interval: weekly commit-message: prefix: ⬆ labels: [dependencies, internal] # bun - package-ecosystem: bun directory: / schedule: interval: weekly commit-message: prefix: ⬆ labels: [dependencies, internal] ignore: - dependency-name: "@hey-api/openapi-ts" # Docker - package-ecosystem: docker directories: - /backend - /frontend schedule: interval: weekly commit-message: prefix: ⬆ labels: [dependencies, internal] # Docker Compose - package-ecosystem: docker-compose directory: / schedule: interval: weekly commit-message: prefix: ⬆ labels: [dependencies, internal] ================================================ FILE: .github/labeler.yml ================================================ docs: - all: - changed-files: - any-glob-to-any-file: - '**/*.md' - all-globs-to-all-files: - '!frontend/**' - '!backend/**' - '!.github/**' - '!scripts/**' - '!.gitignore' - '!.pre-commit-config.yaml' internal: - all: - changed-files: - any-glob-to-any-file: - .github/** - scripts/** - .gitignore - .pre-commit-config.yaml - all-globs-to-all-files: - '!./**/*.md' - '!frontend/**' - '!backend/**' ================================================ FILE: .github/workflows/add-to-project.yml ================================================ name: Add to Project on: pull_request_target: issues: types: - opened - reopened jobs: add-to-project: name: Add to project runs-on: ubuntu-latest steps: - uses: actions/add-to-project@v1.0.2 with: project-url: https://github.com/orgs/fastapi/projects/2 github-token: ${{ secrets.PROJECTS_TOKEN }} ================================================ FILE: .github/workflows/deploy-production.yml ================================================ name: Deploy to Production on: release: types: - published jobs: deploy: # Do not deploy in the main repository, only in user projects if: github.repository_owner != 'fastapi' runs-on: - self-hosted - production env: ENVIRONMENT: production DOMAIN: ${{ secrets.DOMAIN_PRODUCTION }} STACK_NAME: ${{ secrets.STACK_NAME_PRODUCTION }} SECRET_KEY: ${{ secrets.SECRET_KEY }} FIRST_SUPERUSER: ${{ secrets.FIRST_SUPERUSER }} FIRST_SUPERUSER_PASSWORD: ${{ secrets.FIRST_SUPERUSER_PASSWORD }} SMTP_HOST: ${{ secrets.SMTP_HOST }} SMTP_USER: ${{ secrets.SMTP_USER }} SMTP_PASSWORD: ${{ secrets.SMTP_PASSWORD }} EMAILS_FROM_EMAIL: ${{ secrets.EMAILS_FROM_EMAIL }} POSTGRES_PASSWORD: ${{ secrets.POSTGRES_PASSWORD }} SENTRY_DSN: ${{ secrets.SENTRY_DSN }} steps: - name: Checkout uses: actions/checkout@v6 - run: docker compose -f compose.yml --project-name ${{ secrets.STACK_NAME_PRODUCTION }} build - run: docker compose -f compose.yml --project-name ${{ secrets.STACK_NAME_PRODUCTION }} up -d ================================================ FILE: .github/workflows/deploy-staging.yml ================================================ name: Deploy to Staging on: push: branches: - master jobs: deploy: # Do not deploy in the main repository, only in user projects if: github.repository_owner != 'fastapi' runs-on: - self-hosted - staging env: ENVIRONMENT: staging DOMAIN: ${{ secrets.DOMAIN_STAGING }} STACK_NAME: ${{ secrets.STACK_NAME_STAGING }} SECRET_KEY: ${{ secrets.SECRET_KEY }} FIRST_SUPERUSER: ${{ secrets.FIRST_SUPERUSER }} FIRST_SUPERUSER_PASSWORD: ${{ secrets.FIRST_SUPERUSER_PASSWORD }} SMTP_HOST: ${{ secrets.SMTP_HOST }} SMTP_USER: ${{ secrets.SMTP_USER }} SMTP_PASSWORD: ${{ secrets.SMTP_PASSWORD }} EMAILS_FROM_EMAIL: ${{ secrets.EMAILS_FROM_EMAIL }} POSTGRES_PASSWORD: ${{ secrets.POSTGRES_PASSWORD }} SENTRY_DSN: ${{ secrets.SENTRY_DSN }} steps: - name: Checkout uses: actions/checkout@v6 - run: docker compose -f compose.yml --project-name ${{ secrets.STACK_NAME_STAGING }} build - run: docker compose -f compose.yml --project-name ${{ secrets.STACK_NAME_STAGING }} up -d ================================================ FILE: .github/workflows/detect-conflicts.yml ================================================ name: "Conflict detector" on: push: pull_request_target: types: [synchronize] jobs: main: permissions: contents: read pull-requests: write runs-on: ubuntu-latest steps: - name: Check if PRs have merge conflicts uses: eps1lon/actions-label-merge-conflict@v3 with: dirtyLabel: "conflicts" repoToken: "${{ secrets.GITHUB_TOKEN }}" commentOnDirty: "This pull request has a merge conflict that needs to be resolved." ================================================ FILE: .github/workflows/issue-manager.yml ================================================ name: Issue Manager on: schedule: - cron: "21 17 * * *" issue_comment: types: - created issues: types: - labeled pull_request_target: types: - labeled workflow_dispatch: permissions: issues: write pull-requests: write jobs: issue-manager: if: github.repository_owner == 'fastapi' runs-on: ubuntu-latest steps: - name: Dump GitHub context env: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" - uses: tiangolo/issue-manager@0.6.0 with: token: ${{ secrets.GITHUB_TOKEN }} config: > { "answered": { "delay": 864000, "message": "Assuming the original need was handled, this will be automatically closed now. But feel free to add more comments or create new issues or PRs." }, "waiting": { "delay": 2628000, "message": "As this PR has been waiting for the original user for a while but seems to be inactive, it's now going to be closed. But if there's anyone interested, feel free to create a new PR.", "reminder": { "before": "P3D", "message": "Heads-up: this will be closed in 3 days unless there's new activity." } }, "invalid": { "delay": 0, "message": "This was marked as invalid and will be closed now. If this is an error, please provide additional details." }, "maybe-ai": { "delay": 0, "message": "This was marked as potentially AI generated and will be closed now. If this is an error, please provide additional details, make sure to read the docs about contributing and AI." } } ================================================ FILE: .github/workflows/labeler.yml ================================================ name: Labels on: pull_request_target: types: - opened - synchronize - reopened # For label-checker - labeled - unlabeled jobs: labeler: permissions: contents: read pull-requests: write runs-on: ubuntu-latest steps: - uses: actions/labeler@v6 if: ${{ github.event.action != 'labeled' && github.event.action != 'unlabeled' }} - run: echo "Done adding labels" # Run this after labeler applied labels check-labels: needs: - labeler permissions: pull-requests: read runs-on: ubuntu-latest steps: - uses: docker://agilepathway/pull-request-label-checker:latest with: one_of: breaking,security,feature,bug,refactor,upgrade,docs,lang-all,internal repo_token: ${{ secrets.GITHUB_TOKEN }} ================================================ FILE: .github/workflows/latest-changes.yml ================================================ name: Latest Changes on: pull_request_target: branches: - master types: - closed workflow_dispatch: inputs: number: description: PR number required: true debug_enabled: description: "Run the build with tmate debugging enabled (https://github.com/marketplace/actions/debugging-with-tmate)" required: false default: "false" jobs: latest-changes: runs-on: ubuntu-latest permissions: pull-requests: read steps: - name: Dump GitHub context env: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" - uses: actions/checkout@v6 with: # To allow latest-changes to commit to the main branch token: ${{ secrets.LATEST_CHANGES }} - uses: tiangolo/latest-changes@0.4.1 with: token: ${{ secrets.GITHUB_TOKEN }} latest_changes_file: ./release-notes.md latest_changes_header: "## Latest Changes" end_regex: "^## " debug_logs: true label_header_prefix: "### " ================================================ FILE: .github/workflows/playwright.yml ================================================ name: Playwright Tests on: push: branches: - master pull_request: types: - opened - synchronize workflow_dispatch: inputs: debug_enabled: description: 'Run the build with tmate debugging enabled (https://github.com/marketplace/actions/debugging-with-tmate)' required: false default: 'false' jobs: changes: runs-on: ubuntu-latest # Set job outputs to values from filter step outputs: changed: ${{ steps.filter.outputs.changed }} steps: - uses: actions/checkout@v6 # For pull requests it's not necessary to checkout the code but for the main branch it is - uses: dorny/paths-filter@v4 id: filter with: filters: | changed: - backend/** - frontend/** - .env - compose*.yml - .github/workflows/playwright.yml test-playwright: needs: - changes if: ${{ needs.changes.outputs.changed == 'true' }} timeout-minutes: 60 runs-on: ubuntu-latest strategy: matrix: shardIndex: [1, 2, 3, 4] shardTotal: [4] fail-fast: false steps: - uses: actions/checkout@v6 - uses: oven-sh/setup-bun@v2 - uses: actions/setup-python@v6 with: python-version: '3.10' - name: Setup tmate session uses: mxschmitt/action-tmate@v3 if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.debug_enabled == 'true' }} with: limit-access-to-actor: true - name: Install uv uses: astral-sh/setup-uv@v7 - run: uv sync working-directory: backend - run: bun ci working-directory: frontend - run: bash scripts/generate-client.sh - run: docker compose build - run: docker compose down -v --remove-orphans - name: Run Playwright tests run: docker compose run --rm playwright bunx playwright test --fail-on-flaky-tests --trace=retain-on-failure --shard=${{ matrix.shardIndex }}/${{ matrix.shardTotal }} - run: docker compose down -v --remove-orphans - name: Upload blob report to GitHub Actions Artifacts if: ${{ !cancelled() }} uses: actions/upload-artifact@v7 with: name: blob-report-${{ matrix.shardIndex }} path: frontend/blob-report include-hidden-files: true retention-days: 1 merge-playwright-reports: needs: - test-playwright - changes # Merge reports after playwright-tests, even if some shards have failed if: ${{ !cancelled() && needs.changes.outputs.changed == 'true' }} runs-on: ubuntu-latest steps: - uses: actions/checkout@v6 - uses: oven-sh/setup-bun@v2 - name: Install dependencies run: bun ci - name: Download blob reports from GitHub Actions Artifacts uses: actions/download-artifact@v8 with: path: frontend/all-blob-reports pattern: blob-report-* merge-multiple: true - name: Merge into HTML Report run: bunx playwright merge-reports --reporter html ./all-blob-reports working-directory: frontend - name: Upload HTML report uses: actions/upload-artifact@v7 with: name: html-report--attempt-${{ github.run_attempt }} path: frontend/playwright-report retention-days: 30 include-hidden-files: true # https://github.com/marketplace/actions/alls-green#why alls-green-playwright: # This job does nothing and is only used for the branch protection if: always() needs: - test-playwright runs-on: ubuntu-latest steps: - name: Decide whether the needed jobs succeeded or failed uses: re-actors/alls-green@release/v1 with: jobs: ${{ toJSON(needs) }} allowed-skips: test-playwright ================================================ FILE: .github/workflows/pre-commit.yml ================================================ name: pre-commit on: pull_request: types: - opened - synchronize env: # Forks and Dependabot don't have access to secrets HAS_SECRETS: ${{ secrets.PRE_COMMIT != '' }} jobs: pre-commit: runs-on: ubuntu-latest steps: - name: Dump GitHub context env: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" - uses: actions/checkout@v6 name: Checkout PR for own repo if: env.HAS_SECRETS == 'true' with: # To be able to commit it needs to fetch the head of the branch, not the # merge commit ref: ${{ github.head_ref }} # And it needs the full history to be able to compute diffs fetch-depth: 0 # A token other than the default GITHUB_TOKEN is needed to be able to trigger CI token: ${{ secrets.PRE_COMMIT }} # pre-commit lite ci needs the default checkout configs to work - uses: actions/checkout@v6 name: Checkout PR for fork if: env.HAS_SECRETS == 'false' with: # To be able to commit it needs the head branch of the PR, the remote one ref: ${{ github.event.pull_request.head.sha }} fetch-depth: 0 - uses: oven-sh/setup-bun@v2 - name: Set up Python uses: actions/setup-python@v6 with: python-version: "3.11" - name: Setup uv uses: astral-sh/setup-uv@v7 with: cache-dependency-glob: | requirements**.txt pyproject.toml uv.lock - name: Install backend dependencies run: uv sync --all-packages - name: Install frontend dependencies run: bun ci - name: Run prek - pre-commit id: precommit run: uvx prek run --from-ref origin/${GITHUB_BASE_REF} --to-ref HEAD --show-diff-on-failure continue-on-error: true - name: Commit and push changes if: env.HAS_SECRETS == 'true' run: | git config user.name "github-actions[bot]" git config user.email "github-actions[bot]@users.noreply.github.com" git add -A if git diff --staged --quiet; then echo "No changes to commit" else git commit -m "🎨 Auto format and update with pre-commit" git push fi - uses: pre-commit-ci/lite-action@v1.1.0 if: env.HAS_SECRETS == 'false' with: msg: 🎨 Auto format and update with pre-commit - name: Error out on pre-commit errors if: steps.precommit.outcome == 'failure' run: exit 1 # https://github.com/marketplace/actions/alls-green#why pre-commit-alls-green: # This job does nothing and is only used for the branch protection if: always() needs: - pre-commit runs-on: ubuntu-latest steps: - name: Dump GitHub context env: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" - name: Decide whether the needed jobs succeeded or failed uses: re-actors/alls-green@release/v1 with: jobs: ${{ toJSON(needs) }} ================================================ FILE: .github/workflows/smokeshow.yml ================================================ name: Smokeshow on: workflow_run: workflows: [Test Backend] types: [completed] jobs: smokeshow: runs-on: ubuntu-latest permissions: actions: read statuses: write steps: - uses: actions/checkout@v6 - uses: actions/setup-python@v6 with: python-version: "3.13" - run: pip install smokeshow - uses: actions/download-artifact@v8 with: name: coverage-html path: backend/htmlcov github-token: ${{ secrets.GITHUB_TOKEN }} run-id: ${{ github.event.workflow_run.id }} - run: smokeshow upload backend/htmlcov env: SMOKESHOW_GITHUB_STATUS_DESCRIPTION: Coverage {coverage-percentage} SMOKESHOW_GITHUB_COVERAGE_THRESHOLD: 90 SMOKESHOW_GITHUB_CONTEXT: coverage SMOKESHOW_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} SMOKESHOW_GITHUB_PR_HEAD_SHA: ${{ github.event.workflow_run.head_sha }} SMOKESHOW_AUTH_KEY: ${{ secrets.SMOKESHOW_AUTH_KEY }} ================================================ FILE: .github/workflows/test-backend.yml ================================================ name: Test Backend on: push: branches: - master pull_request: types: - opened - synchronize jobs: test-backend: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v6 - name: Set up Python uses: actions/setup-python@v6 with: python-version: "3.10" - name: Install uv uses: astral-sh/setup-uv@v7 - run: docker compose down -v --remove-orphans - run: docker compose up -d db mailcatcher - name: Migrate DB run: uv run bash scripts/prestart.sh working-directory: backend - name: Run tests run: uv run bash scripts/tests-start.sh "Coverage for ${{ github.sha }}" working-directory: backend - run: docker compose down -v --remove-orphans - name: Store coverage files uses: actions/upload-artifact@v7 with: name: coverage-html path: backend/htmlcov include-hidden-files: true - name: Coverage report run: uv run coverage report --fail-under=90 working-directory: backend ================================================ FILE: .github/workflows/test-docker-compose.yml ================================================ name: Test Docker Compose on: push: branches: - master pull_request: types: - opened - synchronize jobs: test-docker-compose: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v6 - run: docker compose build - run: docker compose down -v --remove-orphans - run: docker compose up -d --wait backend frontend adminer - name: Test backend is up run: curl http://localhost:8000/api/v1/utils/health-check - name: Test frontend is up run: curl http://localhost:5173 - run: docker compose down -v --remove-orphans ================================================ FILE: .gitignore ================================================ .vscode/* !.vscode/extensions.json node_modules/ /test-results/ /playwright-report/ /blob-report/ /playwright/.cache/ ================================================ FILE: .pre-commit-config.yaml ================================================ # See https://pre-commit.com for more information # See https://pre-commit.com/hooks.html for more hooks repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.4.0 hooks: - id: check-added-large-files - id: check-toml - id: check-yaml args: - --unsafe - id: end-of-file-fixer exclude: | (?x)^( frontend/src/client/.*| backend/app/email-templates/build/.* )$ - id: trailing-whitespace exclude: ^frontend/src/client/.* - repo: local hooks: - id: local-biome-check name: biome check entry: npm run lint language: system types: [text] files: ^frontend/ - id: local-ruff-check name: ruff check entry: uv run ruff check --force-exclude --fix --exit-non-zero-on-fix require_serial: true language: unsupported types: [python] - id: local-ruff-format name: ruff format entry: uv run ruff format --force-exclude --exit-non-zero-on-format require_serial: true language: unsupported types: [python] - id: local-mypy name: mypy check entry: uv run mypy backend/app require_serial: true language: unsupported pass_filenames: false - id: generate-frontend-sdk name: Generate Frontend SDK entry: bash ./scripts/generate-client.sh pass_filenames: false language: unsupported files: ^backend/.*$|^scripts/generate-client\.sh$ ================================================ FILE: .vscode/extensions.json ================================================ { "recommendations": [ "FastAPILabs.fastapi-vscode", "astral-sh.ty", "biomejs.biome", "bradlc.vscode-tailwindcss", "charliermarsh.ruff", "docker.docker", "github.vscode-github-actions", "mjmlio.vscode-mjml", "ms-playwright.playwright", "ms-python.python", "tombi-toml.tombi" ] } ================================================ FILE: CONTRIBUTING.md ================================================ # Contributing Thank you for your interest in contributing to the Full Stack FastAPI Template! 🙇 ## Discussions First For **big changes** (new features, architectural changes, significant refactoring), please start by opening a [GitHub Discussion](https://github.com/fastapi/full-stack-fastapi-template/discussions) first. This allows the community and maintainers to provide feedback on the approach before you invest significant time in implementation. For small, straightforward changes, you can go directly to a Pull Request without starting a discussion first. This includes: - Typos and grammatical fixes - Small reproducible bug fixes - Fixing lint warnings or type errors - Minor code improvements (e.g., removing unused code) ## Developing For detailed instructions on setting up your development environment, running the stack, linting, pre-commit hooks, and more, see the [Development Guide](development.md). ## Pull Requests When submitting a pull request: 1. Make sure all tests pass before submitting. 2. Keep PRs focused on a single change. 3. Update tests if you're changing functionality. 4. Reference any related issues in your PR description. ## Automated Code and AI You are encouraged to use all the tools you want to do your work and contribute as efficiently as possible, this includes AI (LLM) tools, etc. Nevertheless, contributions should have meaningful human intervention, judgement, context, etc. If the **human effort** put in a PR, e.g. writing LLM prompts, is **less** than the **effort we would need to put** to **review it**, please **don't** submit the PR. Think of it this way: we can already write LLM prompts or run automated tools ourselves, and that would be faster than reviewing external PRs. ### Closing Automated and AI PRs If we see PRs that seem AI generated or automated in similar ways, we'll flag them and close them. The same applies to comments and descriptions, please don't copy paste the content generated by an LLM. ### Human Effort Denial of Service Using automated tools and AI to submit PRs or comments that we have to carefully review and handle would be the equivalent of a [Denial-of-service attack](https://en.wikipedia.org/wiki/Denial-of-service_attack) on our human effort. It would be very little effort from the person submitting the PR (an LLM prompt) that generates a large amount of effort on our side (carefully reviewing code). Please don't do that. We'll need to block accounts that spam us with repeated automated PRs or comments. ### Use Tools Wisely As Uncle Ben said: > With great ~~power~~ **tools** comes great responsibility. Avoid inadvertently doing harm. You have amazing tools at hand, use them wisely to help effectively. ## Questions? If you have questions about contributing, feel free to open a [GitHub Discussion](https://github.com/fastapi/full-stack-fastapi-template/discussions). ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2019 Sebastián Ramírez Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ # Full Stack FastAPI Template Test Docker Compose Test Backend Coverage ## Technology Stack and Features - ⚡ [**FastAPI**](https://fastapi.tiangolo.com) for the Python backend API. - 🧰 [SQLModel](https://sqlmodel.tiangolo.com) for the Python SQL database interactions (ORM). - 🔍 [Pydantic](https://docs.pydantic.dev), used by FastAPI, for the data validation and settings management. - 💾 [PostgreSQL](https://www.postgresql.org) as the SQL database. - 🚀 [React](https://react.dev) for the frontend. - 💃 Using TypeScript, hooks, [Vite](https://vitejs.dev), and other parts of a modern frontend stack. - 🎨 [Tailwind CSS](https://tailwindcss.com) and [shadcn/ui](https://ui.shadcn.com) for the frontend components. - 🤖 An automatically generated frontend client. - 🧪 [Playwright](https://playwright.dev) for End-to-End testing. - 🦇 Dark mode support. - 🐋 [Docker Compose](https://www.docker.com) for development and production. - 🔒 Secure password hashing by default. - 🔑 JWT (JSON Web Token) authentication. - 📫 Email based password recovery. - 📬 [Mailcatcher](https://mailcatcher.me) for local email testing during development. - ✅ Tests with [Pytest](https://pytest.org). - 📞 [Traefik](https://traefik.io) as a reverse proxy / load balancer. - 🚢 Deployment instructions using Docker Compose, including how to set up a frontend Traefik proxy to handle automatic HTTPS certificates. - 🏭 CI (continuous integration) and CD (continuous deployment) based on GitHub Actions. ### Dashboard Login [![API docs](img/login.png)](https://github.com/fastapi/full-stack-fastapi-template) ### Dashboard - Admin [![API docs](img/dashboard.png)](https://github.com/fastapi/full-stack-fastapi-template) ### Dashboard - Items [![API docs](img/dashboard-items.png)](https://github.com/fastapi/full-stack-fastapi-template) ### Dashboard - Dark Mode [![API docs](img/dashboard-dark.png)](https://github.com/fastapi/full-stack-fastapi-template) ### Interactive API Documentation [![API docs](img/docs.png)](https://github.com/fastapi/full-stack-fastapi-template) ## How To Use It You can **just fork or clone** this repository and use it as is. ✨ It just works. ✨ ### How to Use a Private Repository If you want to have a private repository, GitHub won't allow you to simply fork it as it doesn't allow changing the visibility of forks. But you can do the following: - Create a new GitHub repo, for example `my-full-stack`. - Clone this repository manually, set the name with the name of the project you want to use, for example `my-full-stack`: ```bash git clone git@github.com:fastapi/full-stack-fastapi-template.git my-full-stack ``` - Enter into the new directory: ```bash cd my-full-stack ``` - Set the new origin to your new repository, copy it from the GitHub interface, for example: ```bash git remote set-url origin git@github.com:octocat/my-full-stack.git ``` - Add this repo as another "remote" to allow you to get updates later: ```bash git remote add upstream git@github.com:fastapi/full-stack-fastapi-template.git ``` - Push the code to your new repository: ```bash git push -u origin master ``` ### Update From the Original Template After cloning the repository, and after doing changes, you might want to get the latest changes from this original template. - Make sure you added the original repository as a remote, you can check it with: ```bash git remote -v origin git@github.com:octocat/my-full-stack.git (fetch) origin git@github.com:octocat/my-full-stack.git (push) upstream git@github.com:fastapi/full-stack-fastapi-template.git (fetch) upstream git@github.com:fastapi/full-stack-fastapi-template.git (push) ``` - Pull the latest changes without merging: ```bash git pull --no-commit upstream master ``` This will download the latest changes from this template without committing them, that way you can check everything is right before committing. - If there are conflicts, solve them in your editor. - Once you are done, commit the changes: ```bash git merge --continue ``` ### Configure You can then update configs in the `.env` files to customize your configurations. Before deploying it, make sure you change at least the values for: - `SECRET_KEY` - `FIRST_SUPERUSER_PASSWORD` - `POSTGRES_PASSWORD` You can (and should) pass these as environment variables from secrets. Read the [deployment.md](./deployment.md) docs for more details. ### Generate Secret Keys Some environment variables in the `.env` file have a default value of `changethis`. You have to change them with a secret key, to generate secret keys you can run the following command: ```bash python -c "import secrets; print(secrets.token_urlsafe(32))" ``` Copy the content and use that as password / secret key. And run that again to generate another secure key. ## How To Use It - Alternative With Copier This repository also supports generating a new project using [Copier](https://copier.readthedocs.io). It will copy all the files, ask you configuration questions, and update the `.env` files with your answers. ### Install Copier You can install Copier with: ```bash pip install copier ``` Or better, if you have [`pipx`](https://pipx.pypa.io/), you can run it with: ```bash pipx install copier ``` **Note**: If you have `pipx`, installing copier is optional, you could run it directly. ### Generate a Project With Copier Decide a name for your new project's directory, you will use it below. For example, `my-awesome-project`. Go to the directory that will be the parent of your project, and run the command with your project's name: ```bash copier copy https://github.com/fastapi/full-stack-fastapi-template my-awesome-project --trust ``` If you have `pipx` and you didn't install `copier`, you can run it directly: ```bash pipx run copier copy https://github.com/fastapi/full-stack-fastapi-template my-awesome-project --trust ``` **Note** the `--trust` option is necessary to be able to execute a [post-creation script](https://github.com/fastapi/full-stack-fastapi-template/blob/master/.copier/update_dotenv.py) that updates your `.env` files. ### Input Variables Copier will ask you for some data, you might want to have at hand before generating the project. But don't worry, you can just update any of that in the `.env` files afterwards. The input variables, with their default values (some auto generated) are: - `project_name`: (default: `"FastAPI Project"`) The name of the project, shown to API users (in .env). - `stack_name`: (default: `"fastapi-project"`) The name of the stack used for Docker Compose labels and project name (no spaces, no periods) (in .env). - `secret_key`: (default: `"changethis"`) The secret key for the project, used for security, stored in .env, you can generate one with the method above. - `first_superuser`: (default: `"admin@example.com"`) The email of the first superuser (in .env). - `first_superuser_password`: (default: `"changethis"`) The password of the first superuser (in .env). - `smtp_host`: (default: "") The SMTP server host to send emails, you can set it later in .env. - `smtp_user`: (default: "") The SMTP server user to send emails, you can set it later in .env. - `smtp_password`: (default: "") The SMTP server password to send emails, you can set it later in .env. - `emails_from_email`: (default: `"info@example.com"`) The email account to send emails from, you can set it later in .env. - `postgres_password`: (default: `"changethis"`) The password for the PostgreSQL database, stored in .env, you can generate one with the method above. - `sentry_dsn`: (default: "") The DSN for Sentry, if you are using it, you can set it later in .env. ## Backend Development Backend docs: [backend/README.md](./backend/README.md). ## Frontend Development Frontend docs: [frontend/README.md](./frontend/README.md). ## Deployment Deployment docs: [deployment.md](./deployment.md). ## Development General development docs: [development.md](./development.md). This includes using Docker Compose, custom local domains, `.env` configurations, etc. ## Release Notes Check the file [release-notes.md](./release-notes.md). ## License The Full Stack FastAPI Template is licensed under the terms of the MIT license. ================================================ FILE: SECURITY.md ================================================ # Security Policy Security is very important for this project and its community. 🔒 Learn more about it below. 👇 ## Versions The latest version or release is supported. You are encouraged to write tests for your application and update your versions frequently after ensuring that your tests are passing. This way you will benefit from the latest features, bug fixes, and **security fixes**. ## Reporting a Vulnerability If you think you found a vulnerability, and even if you are not sure about it, please report it right away by sending an email to: security@tiangolo.com. Please try to be as explicit as possible, describing all the steps and example code to reproduce the security issue. I (the author, [@tiangolo](https://twitter.com/tiangolo)) will review it thoroughly and get back to you. ## Public Discussions Please restrain from publicly discussing a potential security vulnerability. 🙊 It's better to discuss privately and try to find a solution first, to limit the potential impact as much as possible. --- Thanks for your help! The community and I thank you for that. 🙇 ================================================ FILE: backend/.dockerignore ================================================ # Python __pycache__ app.egg-info *.pyc .mypy_cache .coverage htmlcov .venv ================================================ FILE: backend/.gitignore ================================================ __pycache__ app.egg-info *.pyc .mypy_cache .coverage htmlcov .cache .venv ================================================ FILE: backend/Dockerfile ================================================ FROM python:3.10 ENV PYTHONUNBUFFERED=1 # Install uv # Ref: https://docs.astral.sh/uv/guides/integration/docker/#installing-uv COPY --from=ghcr.io/astral-sh/uv:0.9.26 /uv /uvx /bin/ # Compile bytecode # Ref: https://docs.astral.sh/uv/guides/integration/docker/#compiling-bytecode ENV UV_COMPILE_BYTECODE=1 # uv Cache # Ref: https://docs.astral.sh/uv/guides/integration/docker/#caching ENV UV_LINK_MODE=copy WORKDIR /app/ # Place executables in the environment at the front of the path # Ref: https://docs.astral.sh/uv/guides/integration/docker/#using-the-environment ENV PATH="/app/.venv/bin:$PATH" # Install dependencies # Ref: https://docs.astral.sh/uv/guides/integration/docker/#intermediate-layers RUN --mount=type=cache,target=/root/.cache/uv \ --mount=type=bind,source=uv.lock,target=uv.lock \ --mount=type=bind,source=pyproject.toml,target=pyproject.toml \ uv sync --frozen --no-install-workspace --package app COPY ./backend/scripts /app/backend/scripts COPY ./backend/pyproject.toml ./backend/alembic.ini /app/backend/ COPY ./backend/app /app/backend/app # Sync the project # Ref: https://docs.astral.sh/uv/guides/integration/docker/#intermediate-layers RUN --mount=type=cache,target=/root/.cache/uv \ --mount=type=bind,source=uv.lock,target=uv.lock \ --mount=type=bind,source=pyproject.toml,target=pyproject.toml \ uv sync --frozen --package app WORKDIR /app/backend/ CMD ["fastapi", "run", "--workers", "4", "app/main.py"] ================================================ FILE: backend/README.md ================================================ # FastAPI Project - Backend ## Requirements * [Docker](https://www.docker.com/). * [uv](https://docs.astral.sh/uv/) for Python package and environment management. ## Docker Compose Start the local development environment with Docker Compose following the guide in [../development.md](../development.md). ## General Workflow By default, the dependencies are managed with [uv](https://docs.astral.sh/uv/), go there and install it. From `./backend/` you can install all the dependencies with: ```console $ uv sync ``` Then you can activate the virtual environment with: ```console $ source .venv/bin/activate ``` Make sure your editor is using the correct Python virtual environment, with the interpreter at `backend/.venv/bin/python`. Modify or add SQLModel models for data and SQL tables in `./backend/app/models.py`, API endpoints in `./backend/app/api/`, CRUD (Create, Read, Update, Delete) utils in `./backend/app/crud.py`. ## VS Code There are already configurations in place to run the backend through the VS Code debugger, so that you can use breakpoints, pause and explore variables, etc. The setup is also already configured so you can run the tests through the VS Code Python tests tab. ## Docker Compose Override During development, you can change Docker Compose settings that will only affect the local development environment in the file `compose.override.yml`. The changes to that file only affect the local development environment, not the production environment. So, you can add "temporary" changes that help the development workflow. For example, the directory with the backend code is synchronized in the Docker container, copying the code you change live to the directory inside the container. That allows you to test your changes right away, without having to build the Docker image again. It should only be done during development, for production, you should build the Docker image with a recent version of the backend code. But during development, it allows you to iterate very fast. There is also a command override that runs `fastapi run --reload` instead of the default `fastapi run`. It starts a single server process (instead of multiple, as would be for production) and reloads the process whenever the code changes. Have in mind that if you have a syntax error and save the Python file, it will break and exit, and the container will stop. After that, you can restart the container by fixing the error and running again: ```console $ docker compose watch ``` There is also a commented out `command` override, you can uncomment it and comment the default one. It makes the backend container run a process that does "nothing", but keeps the container alive. That allows you to get inside your running container and execute commands inside, for example a Python interpreter to test installed dependencies, or start the development server that reloads when it detects changes. To get inside the container with a `bash` session you can start the stack with: ```console $ docker compose watch ``` and then in another terminal, `exec` inside the running container: ```console $ docker compose exec backend bash ``` You should see an output like: ```console root@7f2607af31c3:/app# ``` that means that you are in a `bash` session inside your container, as a `root` user, under the `/app` directory, this directory has another directory called "app" inside, that's where your code lives inside the container: `/app/app`. There you can use the `fastapi run --reload` command to run the debug live reloading server. ```console $ fastapi run --reload app/main.py ``` ...it will look like: ```console root@7f2607af31c3:/app# fastapi run --reload app/main.py ``` and then hit enter. That runs the live reloading server that auto reloads when it detects code changes. Nevertheless, if it doesn't detect a change but a syntax error, it will just stop with an error. But as the container is still alive and you are in a Bash session, you can quickly restart it after fixing the error, running the same command ("up arrow" and "Enter"). ...this previous detail is what makes it useful to have the container alive doing nothing and then, in a Bash session, make it run the live reload server. ## Backend tests To test the backend run: ```console $ bash ./scripts/test.sh ``` The tests run with Pytest, modify and add tests to `./backend/tests/`. If you use GitHub Actions the tests will run automatically. ### Test running stack If your stack is already up and you just want to run the tests, you can use: ```bash docker compose exec backend bash scripts/tests-start.sh ``` That `/app/scripts/tests-start.sh` script just calls `pytest` after making sure that the rest of the stack is running. If you need to pass extra arguments to `pytest`, you can pass them to that command and they will be forwarded. For example, to stop on first error: ```bash docker compose exec backend bash scripts/tests-start.sh -x ``` ### Test Coverage When the tests are run, a file `htmlcov/index.html` is generated, you can open it in your browser to see the coverage of the tests. ## Migrations As during local development your app directory is mounted as a volume inside the container, you can also run the migrations with `alembic` commands inside the container and the migration code will be in your app directory (instead of being only inside the container). So you can add it to your git repository. Make sure you create a "revision" of your models and that you "upgrade" your database with that revision every time you change them. As this is what will update the tables in your database. Otherwise, your application will have errors. * Start an interactive session in the backend container: ```console $ docker compose exec backend bash ``` * Alembic is already configured to import your SQLModel models from `./backend/app/models.py`. * After changing a model (for example, adding a column), inside the container, create a revision, e.g.: ```console $ alembic revision --autogenerate -m "Add column last_name to User model" ``` * Commit to the git repository the files generated in the alembic directory. * After creating the revision, run the migration in the database (this is what will actually change the database): ```console $ alembic upgrade head ``` If you don't want to use migrations at all, uncomment the lines in the file at `./backend/app/core/db.py` that end in: ```python SQLModel.metadata.create_all(engine) ``` and comment the line in the file `scripts/prestart.sh` that contains: ```console $ alembic upgrade head ``` If you don't want to start with the default models and want to remove them / modify them, from the beginning, without having any previous revision, you can remove the revision files (`.py` Python files) under `./backend/app/alembic/versions/`. And then create a first migration as described above. ## Email Templates The email templates are in `./backend/app/email-templates/`. Here, there are two directories: `build` and `src`. The `src` directory contains the source files that are used to build the final email templates. The `build` directory contains the final email templates that are used by the application. Before continuing, ensure you have the [MJML extension](https://github.com/mjmlio/vscode-mjml) installed in your VS Code. Once you have the MJML extension installed, you can create a new email template in the `src` directory. After creating the new email template and with the `.mjml` file open in your editor, open the command palette with `Ctrl+Shift+P` and search for `MJML: Export to HTML`. This will convert the `.mjml` file to a `.html` file and now you can save it in the build directory. ================================================ FILE: backend/alembic.ini ================================================ # A generic, single database configuration. [alembic] # path to migration scripts script_location = app/alembic # template used to generate migration files # file_template = %%(rev)s_%%(slug)s # timezone to use when rendering the date # within the migration file as well as the filename. # string value is passed to dateutil.tz.gettz() # leave blank for localtime # timezone = # max length of characters to apply to the # "slug" field #truncate_slug_length = 40 # set to 'true' to run the environment during # the 'revision' command, regardless of autogenerate # revision_environment = false # set to 'true' to allow .pyc and .pyo files without # a source .py file to be detected as revisions in the # versions/ directory # sourceless = false # version location specification; this defaults # to alembic/versions. When using multiple version # directories, initial revisions must be specified with --version-path # version_locations = %(here)s/bar %(here)s/bat alembic/versions # the output encoding used when revision files # are written from script.py.mako # output_encoding = utf-8 # Logging configuration [loggers] keys = root,sqlalchemy,alembic [handlers] keys = console [formatters] keys = generic [logger_root] level = WARN handlers = console qualname = [logger_sqlalchemy] level = WARN handlers = qualname = sqlalchemy.engine [logger_alembic] level = INFO handlers = qualname = alembic [handler_console] class = StreamHandler args = (sys.stderr,) level = NOTSET formatter = generic [formatter_generic] format = %(levelname)-5.5s [%(name)s] %(message)s datefmt = %H:%M:%S ================================================ FILE: backend/app/__init__.py ================================================ ================================================ FILE: backend/app/alembic/README ================================================ Generic single-database configuration. ================================================ FILE: backend/app/alembic/env.py ================================================ import os from logging.config import fileConfig from alembic import context from sqlalchemy import engine_from_config, pool # this is the Alembic Config object, which provides # access to the values within the .ini file in use. config = context.config # Interpret the config file for Python logging. # This line sets up loggers basically. assert config.config_file_name is not None fileConfig(config.config_file_name) # add your model's MetaData object here # for 'autogenerate' support # from myapp import mymodel # target_metadata = mymodel.Base.metadata # target_metadata = None from app.models import SQLModel # noqa from app.core.config import settings # noqa target_metadata = SQLModel.metadata # other values from the config, defined by the needs of env.py, # can be acquired: # my_important_option = config.get_main_option("my_important_option") # ... etc. def get_url(): return str(settings.SQLALCHEMY_DATABASE_URI) def run_migrations_offline(): """Run migrations in 'offline' mode. This configures the context with just a URL and not an Engine, though an Engine is acceptable here as well. By skipping the Engine creation we don't even need a DBAPI to be available. Calls to context.execute() here emit the given string to the script output. """ url = get_url() context.configure( url=url, target_metadata=target_metadata, literal_binds=True, compare_type=True ) with context.begin_transaction(): context.run_migrations() def run_migrations_online(): """Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context. """ configuration = config.get_section(config.config_ini_section) configuration["sqlalchemy.url"] = get_url() connectable = engine_from_config( configuration, prefix="sqlalchemy.", poolclass=pool.NullPool, ) with connectable.connect() as connection: context.configure( connection=connection, target_metadata=target_metadata, compare_type=True ) with context.begin_transaction(): context.run_migrations() if context.is_offline_mode(): run_migrations_offline() else: run_migrations_online() ================================================ FILE: backend/app/alembic/script.py.mako ================================================ """${message} Revision ID: ${up_revision} Revises: ${down_revision | comma,n} Create Date: ${create_date} """ from alembic import op import sqlalchemy as sa import sqlmodel.sql.sqltypes ${imports if imports else ""} # revision identifiers, used by Alembic. revision = ${repr(up_revision)} down_revision = ${repr(down_revision)} branch_labels = ${repr(branch_labels)} depends_on = ${repr(depends_on)} def upgrade(): ${upgrades if upgrades else "pass"} def downgrade(): ${downgrades if downgrades else "pass"} ================================================ FILE: backend/app/alembic/versions/.keep ================================================ ================================================ FILE: backend/app/alembic/versions/1a31ce608336_add_cascade_delete_relationships.py ================================================ """Add cascade delete relationships Revision ID: 1a31ce608336 Revises: d98dd8ec85a3 Create Date: 2024-07-31 22:24:34.447891 """ from alembic import op import sqlalchemy as sa import sqlmodel.sql.sqltypes # revision identifiers, used by Alembic. revision = '1a31ce608336' down_revision = 'd98dd8ec85a3' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.alter_column('item', 'owner_id', existing_type=sa.UUID(), nullable=False) op.drop_constraint('item_owner_id_fkey', 'item', type_='foreignkey') op.create_foreign_key(None, 'item', 'user', ['owner_id'], ['id'], ondelete='CASCADE') # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_constraint(None, 'item', type_='foreignkey') op.create_foreign_key('item_owner_id_fkey', 'item', 'user', ['owner_id'], ['id']) op.alter_column('item', 'owner_id', existing_type=sa.UUID(), nullable=True) # ### end Alembic commands ### ================================================ FILE: backend/app/alembic/versions/9c0a54914c78_add_max_length_for_string_varchar_.py ================================================ """Add max length for string(varchar) fields in User and Items models Revision ID: 9c0a54914c78 Revises: e2412789c190 Create Date: 2024-06-17 14:42:44.639457 """ from alembic import op import sqlalchemy as sa import sqlmodel.sql.sqltypes # revision identifiers, used by Alembic. revision = '9c0a54914c78' down_revision = 'e2412789c190' branch_labels = None depends_on = None def upgrade(): # Adjust the length of the email field in the User table op.alter_column('user', 'email', existing_type=sa.String(), type_=sa.String(length=255), existing_nullable=False) # Adjust the length of the full_name field in the User table op.alter_column('user', 'full_name', existing_type=sa.String(), type_=sa.String(length=255), existing_nullable=True) # Adjust the length of the title field in the Item table op.alter_column('item', 'title', existing_type=sa.String(), type_=sa.String(length=255), existing_nullable=False) # Adjust the length of the description field in the Item table op.alter_column('item', 'description', existing_type=sa.String(), type_=sa.String(length=255), existing_nullable=True) def downgrade(): # Revert the length of the email field in the User table op.alter_column('user', 'email', existing_type=sa.String(length=255), type_=sa.String(), existing_nullable=False) # Revert the length of the full_name field in the User table op.alter_column('user', 'full_name', existing_type=sa.String(length=255), type_=sa.String(), existing_nullable=True) # Revert the length of the title field in the Item table op.alter_column('item', 'title', existing_type=sa.String(length=255), type_=sa.String(), existing_nullable=False) # Revert the length of the description field in the Item table op.alter_column('item', 'description', existing_type=sa.String(length=255), type_=sa.String(), existing_nullable=True) ================================================ FILE: backend/app/alembic/versions/d98dd8ec85a3_edit_replace_id_integers_in_all_models_.py ================================================ """Edit replace id integers in all models to use UUID instead Revision ID: d98dd8ec85a3 Revises: 9c0a54914c78 Create Date: 2024-07-19 04:08:04.000976 """ from alembic import op import sqlalchemy as sa import sqlmodel.sql.sqltypes from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = 'd98dd8ec85a3' down_revision = '9c0a54914c78' branch_labels = None depends_on = None def upgrade(): # Ensure uuid-ossp extension is available op.execute('CREATE EXTENSION IF NOT EXISTS "uuid-ossp"') # Create a new UUID column with a default UUID value op.add_column('user', sa.Column('new_id', postgresql.UUID(as_uuid=True), default=sa.text('uuid_generate_v4()'))) op.add_column('item', sa.Column('new_id', postgresql.UUID(as_uuid=True), default=sa.text('uuid_generate_v4()'))) op.add_column('item', sa.Column('new_owner_id', postgresql.UUID(as_uuid=True), nullable=True)) # Populate the new columns with UUIDs op.execute('UPDATE "user" SET new_id = uuid_generate_v4()') op.execute('UPDATE item SET new_id = uuid_generate_v4()') op.execute('UPDATE item SET new_owner_id = (SELECT new_id FROM "user" WHERE "user".id = item.owner_id)') # Set the new_id as not nullable op.alter_column('user', 'new_id', nullable=False) op.alter_column('item', 'new_id', nullable=False) # Drop old columns and rename new columns op.drop_constraint('item_owner_id_fkey', 'item', type_='foreignkey') op.drop_column('item', 'owner_id') op.alter_column('item', 'new_owner_id', new_column_name='owner_id') op.drop_column('user', 'id') op.alter_column('user', 'new_id', new_column_name='id') op.drop_column('item', 'id') op.alter_column('item', 'new_id', new_column_name='id') # Create primary key constraint op.create_primary_key('user_pkey', 'user', ['id']) op.create_primary_key('item_pkey', 'item', ['id']) # Recreate foreign key constraint op.create_foreign_key('item_owner_id_fkey', 'item', 'user', ['owner_id'], ['id']) def downgrade(): # Reverse the upgrade process op.add_column('user', sa.Column('old_id', sa.Integer, autoincrement=True)) op.add_column('item', sa.Column('old_id', sa.Integer, autoincrement=True)) op.add_column('item', sa.Column('old_owner_id', sa.Integer, nullable=True)) # Populate the old columns with default values # Generate sequences for the integer IDs if not exist op.execute('CREATE SEQUENCE IF NOT EXISTS user_id_seq AS INTEGER OWNED BY "user".old_id') op.execute('CREATE SEQUENCE IF NOT EXISTS item_id_seq AS INTEGER OWNED BY item.old_id') op.execute('SELECT setval(\'user_id_seq\', COALESCE((SELECT MAX(old_id) + 1 FROM "user"), 1), false)') op.execute('SELECT setval(\'item_id_seq\', COALESCE((SELECT MAX(old_id) + 1 FROM item), 1), false)') op.execute('UPDATE "user" SET old_id = nextval(\'user_id_seq\')') op.execute('UPDATE item SET old_id = nextval(\'item_id_seq\'), old_owner_id = (SELECT old_id FROM "user" WHERE "user".id = item.owner_id)') # Drop new columns and rename old columns back op.drop_constraint('item_owner_id_fkey', 'item', type_='foreignkey') op.drop_column('item', 'owner_id') op.alter_column('item', 'old_owner_id', new_column_name='owner_id') op.drop_column('user', 'id') op.alter_column('user', 'old_id', new_column_name='id') op.drop_column('item', 'id') op.alter_column('item', 'old_id', new_column_name='id') # Create primary key constraint op.create_primary_key('user_pkey', 'user', ['id']) op.create_primary_key('item_pkey', 'item', ['id']) # Recreate foreign key constraint op.create_foreign_key('item_owner_id_fkey', 'item', 'user', ['owner_id'], ['id']) ================================================ FILE: backend/app/alembic/versions/e2412789c190_initialize_models.py ================================================ """Initialize models Revision ID: e2412789c190 Revises: Create Date: 2023-11-24 22:55:43.195942 """ import sqlalchemy as sa import sqlmodel.sql.sqltypes from alembic import op # revision identifiers, used by Alembic. revision = "e2412789c190" down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table( "user", sa.Column("email", sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column("is_active", sa.Boolean(), nullable=False), sa.Column("is_superuser", sa.Boolean(), nullable=False), sa.Column("full_name", sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column("id", sa.Integer(), nullable=False), sa.Column( "hashed_password", sqlmodel.sql.sqltypes.AutoString(), nullable=False ), sa.PrimaryKeyConstraint("id"), ) op.create_index(op.f("ix_user_email"), "user", ["email"], unique=True) op.create_table( "item", sa.Column("description", sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column("id", sa.Integer(), nullable=False), sa.Column("title", sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column("owner_id", sa.Integer(), nullable=False), sa.ForeignKeyConstraint( ["owner_id"], ["user.id"], ), sa.PrimaryKeyConstraint("id"), ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_table("item") op.drop_index(op.f("ix_user_email"), table_name="user") op.drop_table("user") # ### end Alembic commands ### ================================================ FILE: backend/app/alembic/versions/fe56fa70289e_add_created_at_to_user_and_item.py ================================================ """Add created_at to User and Item Revision ID: fe56fa70289e Revises: 1a31ce608336 Create Date: 2026-01-23 15:50:37.171462 """ from alembic import op import sqlalchemy as sa import sqlmodel.sql.sqltypes # revision identifiers, used by Alembic. revision = 'fe56fa70289e' down_revision = '1a31ce608336' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('item', sa.Column('created_at', sa.DateTime(timezone=True), nullable=True)) op.add_column('user', sa.Column('created_at', sa.DateTime(timezone=True), nullable=True)) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('user', 'created_at') op.drop_column('item', 'created_at') # ### end Alembic commands ### ================================================ FILE: backend/app/api/__init__.py ================================================ ================================================ FILE: backend/app/api/deps.py ================================================ from collections.abc import Generator from typing import Annotated import jwt from fastapi import Depends, HTTPException, status from fastapi.security import OAuth2PasswordBearer from jwt.exceptions import InvalidTokenError from pydantic import ValidationError from sqlmodel import Session from app.core import security from app.core.config import settings from app.core.db import engine from app.models import TokenPayload, User reusable_oauth2 = OAuth2PasswordBearer( tokenUrl=f"{settings.API_V1_STR}/login/access-token" ) def get_db() -> Generator[Session, None, None]: with Session(engine) as session: yield session SessionDep = Annotated[Session, Depends(get_db)] TokenDep = Annotated[str, Depends(reusable_oauth2)] def get_current_user(session: SessionDep, token: TokenDep) -> User: try: payload = jwt.decode( token, settings.SECRET_KEY, algorithms=[security.ALGORITHM] ) token_data = TokenPayload(**payload) except (InvalidTokenError, ValidationError): raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Could not validate credentials", ) user = session.get(User, token_data.sub) if not user: raise HTTPException(status_code=404, detail="User not found") if not user.is_active: raise HTTPException(status_code=400, detail="Inactive user") return user CurrentUser = Annotated[User, Depends(get_current_user)] def get_current_active_superuser(current_user: CurrentUser) -> User: if not current_user.is_superuser: raise HTTPException( status_code=403, detail="The user doesn't have enough privileges" ) return current_user ================================================ FILE: backend/app/api/main.py ================================================ from fastapi import APIRouter from app.api.routes import items, login, private, users, utils from app.core.config import settings api_router = APIRouter() api_router.include_router(login.router) api_router.include_router(users.router) api_router.include_router(utils.router) api_router.include_router(items.router) if settings.ENVIRONMENT == "local": api_router.include_router(private.router) ================================================ FILE: backend/app/api/routes/__init__.py ================================================ ================================================ FILE: backend/app/api/routes/items.py ================================================ import uuid from typing import Any from fastapi import APIRouter, HTTPException from sqlmodel import col, func, select from app.api.deps import CurrentUser, SessionDep from app.models import Item, ItemCreate, ItemPublic, ItemsPublic, ItemUpdate, Message router = APIRouter(prefix="/items", tags=["items"]) @router.get("/", response_model=ItemsPublic) def read_items( session: SessionDep, current_user: CurrentUser, skip: int = 0, limit: int = 100 ) -> Any: """ Retrieve items. """ if current_user.is_superuser: count_statement = select(func.count()).select_from(Item) count = session.exec(count_statement).one() statement = ( select(Item).order_by(col(Item.created_at).desc()).offset(skip).limit(limit) ) items = session.exec(statement).all() else: count_statement = ( select(func.count()) .select_from(Item) .where(Item.owner_id == current_user.id) ) count = session.exec(count_statement).one() statement = ( select(Item) .where(Item.owner_id == current_user.id) .order_by(col(Item.created_at).desc()) .offset(skip) .limit(limit) ) items = session.exec(statement).all() return ItemsPublic(data=items, count=count) @router.get("/{id}", response_model=ItemPublic) def read_item(session: SessionDep, current_user: CurrentUser, id: uuid.UUID) -> Any: """ Get item by ID. """ item = session.get(Item, id) if not item: raise HTTPException(status_code=404, detail="Item not found") if not current_user.is_superuser and (item.owner_id != current_user.id): raise HTTPException(status_code=403, detail="Not enough permissions") return item @router.post("/", response_model=ItemPublic) def create_item( *, session: SessionDep, current_user: CurrentUser, item_in: ItemCreate ) -> Any: """ Create new item. """ item = Item.model_validate(item_in, update={"owner_id": current_user.id}) session.add(item) session.commit() session.refresh(item) return item @router.put("/{id}", response_model=ItemPublic) def update_item( *, session: SessionDep, current_user: CurrentUser, id: uuid.UUID, item_in: ItemUpdate, ) -> Any: """ Update an item. """ item = session.get(Item, id) if not item: raise HTTPException(status_code=404, detail="Item not found") if not current_user.is_superuser and (item.owner_id != current_user.id): raise HTTPException(status_code=403, detail="Not enough permissions") update_dict = item_in.model_dump(exclude_unset=True) item.sqlmodel_update(update_dict) session.add(item) session.commit() session.refresh(item) return item @router.delete("/{id}") def delete_item( session: SessionDep, current_user: CurrentUser, id: uuid.UUID ) -> Message: """ Delete an item. """ item = session.get(Item, id) if not item: raise HTTPException(status_code=404, detail="Item not found") if not current_user.is_superuser and (item.owner_id != current_user.id): raise HTTPException(status_code=403, detail="Not enough permissions") session.delete(item) session.commit() return Message(message="Item deleted successfully") ================================================ FILE: backend/app/api/routes/login.py ================================================ from datetime import timedelta from typing import Annotated, Any from fastapi import APIRouter, Depends, HTTPException from fastapi.responses import HTMLResponse from fastapi.security import OAuth2PasswordRequestForm from app import crud from app.api.deps import CurrentUser, SessionDep, get_current_active_superuser from app.core import security from app.core.config import settings from app.models import Message, NewPassword, Token, UserPublic, UserUpdate from app.utils import ( generate_password_reset_token, generate_reset_password_email, send_email, verify_password_reset_token, ) router = APIRouter(tags=["login"]) @router.post("/login/access-token") def login_access_token( session: SessionDep, form_data: Annotated[OAuth2PasswordRequestForm, Depends()] ) -> Token: """ OAuth2 compatible token login, get an access token for future requests """ user = crud.authenticate( session=session, email=form_data.username, password=form_data.password ) if not user: raise HTTPException(status_code=400, detail="Incorrect email or password") elif not user.is_active: raise HTTPException(status_code=400, detail="Inactive user") access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES) return Token( access_token=security.create_access_token( user.id, expires_delta=access_token_expires ) ) @router.post("/login/test-token", response_model=UserPublic) def test_token(current_user: CurrentUser) -> Any: """ Test access token """ return current_user @router.post("/password-recovery/{email}") def recover_password(email: str, session: SessionDep) -> Message: """ Password Recovery """ user = crud.get_user_by_email(session=session, email=email) # Always return the same response to prevent email enumeration attacks # Only send email if user actually exists if user: password_reset_token = generate_password_reset_token(email=email) email_data = generate_reset_password_email( email_to=user.email, email=email, token=password_reset_token ) send_email( email_to=user.email, subject=email_data.subject, html_content=email_data.html_content, ) return Message( message="If that email is registered, we sent a password recovery link" ) @router.post("/reset-password/") def reset_password(session: SessionDep, body: NewPassword) -> Message: """ Reset password """ email = verify_password_reset_token(token=body.token) if not email: raise HTTPException(status_code=400, detail="Invalid token") user = crud.get_user_by_email(session=session, email=email) if not user: # Don't reveal that the user doesn't exist - use same error as invalid token raise HTTPException(status_code=400, detail="Invalid token") elif not user.is_active: raise HTTPException(status_code=400, detail="Inactive user") user_in_update = UserUpdate(password=body.new_password) crud.update_user( session=session, db_user=user, user_in=user_in_update, ) return Message(message="Password updated successfully") @router.post( "/password-recovery-html-content/{email}", dependencies=[Depends(get_current_active_superuser)], response_class=HTMLResponse, ) def recover_password_html_content(email: str, session: SessionDep) -> Any: """ HTML Content for Password Recovery """ user = crud.get_user_by_email(session=session, email=email) if not user: raise HTTPException( status_code=404, detail="The user with this username does not exist in the system.", ) password_reset_token = generate_password_reset_token(email=email) email_data = generate_reset_password_email( email_to=user.email, email=email, token=password_reset_token ) return HTMLResponse( content=email_data.html_content, headers={"subject:": email_data.subject} ) ================================================ FILE: backend/app/api/routes/private.py ================================================ from typing import Any from fastapi import APIRouter from pydantic import BaseModel from app.api.deps import SessionDep from app.core.security import get_password_hash from app.models import ( User, UserPublic, ) router = APIRouter(tags=["private"], prefix="/private") class PrivateUserCreate(BaseModel): email: str password: str full_name: str is_verified: bool = False @router.post("/users/", response_model=UserPublic) def create_user(user_in: PrivateUserCreate, session: SessionDep) -> Any: """ Create a new user. """ user = User( email=user_in.email, full_name=user_in.full_name, hashed_password=get_password_hash(user_in.password), ) session.add(user) session.commit() return user ================================================ FILE: backend/app/api/routes/users.py ================================================ import uuid from typing import Any from fastapi import APIRouter, Depends, HTTPException from sqlmodel import col, delete, func, select from app import crud from app.api.deps import ( CurrentUser, SessionDep, get_current_active_superuser, ) from app.core.config import settings from app.core.security import get_password_hash, verify_password from app.models import ( Item, Message, UpdatePassword, User, UserCreate, UserPublic, UserRegister, UsersPublic, UserUpdate, UserUpdateMe, ) from app.utils import generate_new_account_email, send_email router = APIRouter(prefix="/users", tags=["users"]) @router.get( "/", dependencies=[Depends(get_current_active_superuser)], response_model=UsersPublic, ) def read_users(session: SessionDep, skip: int = 0, limit: int = 100) -> Any: """ Retrieve users. """ count_statement = select(func.count()).select_from(User) count = session.exec(count_statement).one() statement = ( select(User).order_by(col(User.created_at).desc()).offset(skip).limit(limit) ) users = session.exec(statement).all() return UsersPublic(data=users, count=count) @router.post( "/", dependencies=[Depends(get_current_active_superuser)], response_model=UserPublic ) def create_user(*, session: SessionDep, user_in: UserCreate) -> Any: """ Create new user. """ user = crud.get_user_by_email(session=session, email=user_in.email) if user: raise HTTPException( status_code=400, detail="The user with this email already exists in the system.", ) user = crud.create_user(session=session, user_create=user_in) if settings.emails_enabled and user_in.email: email_data = generate_new_account_email( email_to=user_in.email, username=user_in.email, password=user_in.password ) send_email( email_to=user_in.email, subject=email_data.subject, html_content=email_data.html_content, ) return user @router.patch("/me", response_model=UserPublic) def update_user_me( *, session: SessionDep, user_in: UserUpdateMe, current_user: CurrentUser ) -> Any: """ Update own user. """ if user_in.email: existing_user = crud.get_user_by_email(session=session, email=user_in.email) if existing_user and existing_user.id != current_user.id: raise HTTPException( status_code=409, detail="User with this email already exists" ) user_data = user_in.model_dump(exclude_unset=True) current_user.sqlmodel_update(user_data) session.add(current_user) session.commit() session.refresh(current_user) return current_user @router.patch("/me/password", response_model=Message) def update_password_me( *, session: SessionDep, body: UpdatePassword, current_user: CurrentUser ) -> Any: """ Update own password. """ verified, _ = verify_password(body.current_password, current_user.hashed_password) if not verified: raise HTTPException(status_code=400, detail="Incorrect password") if body.current_password == body.new_password: raise HTTPException( status_code=400, detail="New password cannot be the same as the current one" ) hashed_password = get_password_hash(body.new_password) current_user.hashed_password = hashed_password session.add(current_user) session.commit() return Message(message="Password updated successfully") @router.get("/me", response_model=UserPublic) def read_user_me(current_user: CurrentUser) -> Any: """ Get current user. """ return current_user @router.delete("/me", response_model=Message) def delete_user_me(session: SessionDep, current_user: CurrentUser) -> Any: """ Delete own user. """ if current_user.is_superuser: raise HTTPException( status_code=403, detail="Super users are not allowed to delete themselves" ) session.delete(current_user) session.commit() return Message(message="User deleted successfully") @router.post("/signup", response_model=UserPublic) def register_user(session: SessionDep, user_in: UserRegister) -> Any: """ Create new user without the need to be logged in. """ user = crud.get_user_by_email(session=session, email=user_in.email) if user: raise HTTPException( status_code=400, detail="The user with this email already exists in the system", ) user_create = UserCreate.model_validate(user_in) user = crud.create_user(session=session, user_create=user_create) return user @router.get("/{user_id}", response_model=UserPublic) def read_user_by_id( user_id: uuid.UUID, session: SessionDep, current_user: CurrentUser ) -> Any: """ Get a specific user by id. """ user = session.get(User, user_id) if user == current_user: return user if not current_user.is_superuser: raise HTTPException( status_code=403, detail="The user doesn't have enough privileges", ) if user is None: raise HTTPException(status_code=404, detail="User not found") return user @router.patch( "/{user_id}", dependencies=[Depends(get_current_active_superuser)], response_model=UserPublic, ) def update_user( *, session: SessionDep, user_id: uuid.UUID, user_in: UserUpdate, ) -> Any: """ Update a user. """ db_user = session.get(User, user_id) if not db_user: raise HTTPException( status_code=404, detail="The user with this id does not exist in the system", ) if user_in.email: existing_user = crud.get_user_by_email(session=session, email=user_in.email) if existing_user and existing_user.id != user_id: raise HTTPException( status_code=409, detail="User with this email already exists" ) db_user = crud.update_user(session=session, db_user=db_user, user_in=user_in) return db_user @router.delete("/{user_id}", dependencies=[Depends(get_current_active_superuser)]) def delete_user( session: SessionDep, current_user: CurrentUser, user_id: uuid.UUID ) -> Message: """ Delete a user. """ user = session.get(User, user_id) if not user: raise HTTPException(status_code=404, detail="User not found") if user == current_user: raise HTTPException( status_code=403, detail="Super users are not allowed to delete themselves" ) statement = delete(Item).where(col(Item.owner_id) == user_id) session.exec(statement) session.delete(user) session.commit() return Message(message="User deleted successfully") ================================================ FILE: backend/app/api/routes/utils.py ================================================ from fastapi import APIRouter, Depends from pydantic.networks import EmailStr from app.api.deps import get_current_active_superuser from app.models import Message from app.utils import generate_test_email, send_email router = APIRouter(prefix="/utils", tags=["utils"]) @router.post( "/test-email/", dependencies=[Depends(get_current_active_superuser)], status_code=201, ) def test_email(email_to: EmailStr) -> Message: """ Test emails. """ email_data = generate_test_email(email_to=email_to) send_email( email_to=email_to, subject=email_data.subject, html_content=email_data.html_content, ) return Message(message="Test email sent") @router.get("/health-check/") async def health_check() -> bool: return True ================================================ FILE: backend/app/backend_pre_start.py ================================================ import logging from sqlalchemy import Engine from sqlmodel import Session, select from tenacity import after_log, before_log, retry, stop_after_attempt, wait_fixed from app.core.db import engine logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) max_tries = 60 * 5 # 5 minutes wait_seconds = 1 @retry( stop=stop_after_attempt(max_tries), wait=wait_fixed(wait_seconds), before=before_log(logger, logging.INFO), after=after_log(logger, logging.WARN), ) def init(db_engine: Engine) -> None: try: with Session(db_engine) as session: # Try to create session to check if DB is awake session.exec(select(1)) except Exception as e: logger.error(e) raise e def main() -> None: logger.info("Initializing service") init(engine) logger.info("Service finished initializing") if __name__ == "__main__": main() ================================================ FILE: backend/app/core/__init__.py ================================================ ================================================ FILE: backend/app/core/config.py ================================================ import secrets import warnings from typing import Annotated, Any, Literal from pydantic import ( AnyUrl, BeforeValidator, EmailStr, HttpUrl, PostgresDsn, computed_field, model_validator, ) from pydantic_settings import BaseSettings, SettingsConfigDict from typing_extensions import Self def parse_cors(v: Any) -> list[str] | str: if isinstance(v, str) and not v.startswith("["): return [i.strip() for i in v.split(",") if i.strip()] elif isinstance(v, list | str): return v raise ValueError(v) class Settings(BaseSettings): model_config = SettingsConfigDict( # Use top level .env file (one level above ./backend/) env_file="../.env", env_ignore_empty=True, extra="ignore", ) API_V1_STR: str = "/api/v1" SECRET_KEY: str = secrets.token_urlsafe(32) # 60 minutes * 24 hours * 8 days = 8 days ACCESS_TOKEN_EXPIRE_MINUTES: int = 60 * 24 * 8 FRONTEND_HOST: str = "http://localhost:5173" ENVIRONMENT: Literal["local", "staging", "production"] = "local" BACKEND_CORS_ORIGINS: Annotated[ list[AnyUrl] | str, BeforeValidator(parse_cors) ] = [] @computed_field # type: ignore[prop-decorator] @property def all_cors_origins(self) -> list[str]: return [str(origin).rstrip("/") for origin in self.BACKEND_CORS_ORIGINS] + [ self.FRONTEND_HOST ] PROJECT_NAME: str SENTRY_DSN: HttpUrl | None = None POSTGRES_SERVER: str POSTGRES_PORT: int = 5432 POSTGRES_USER: str POSTGRES_PASSWORD: str = "" POSTGRES_DB: str = "" @computed_field # type: ignore[prop-decorator] @property def SQLALCHEMY_DATABASE_URI(self) -> PostgresDsn: return PostgresDsn.build( scheme="postgresql+psycopg", username=self.POSTGRES_USER, password=self.POSTGRES_PASSWORD, host=self.POSTGRES_SERVER, port=self.POSTGRES_PORT, path=self.POSTGRES_DB, ) SMTP_TLS: bool = True SMTP_SSL: bool = False SMTP_PORT: int = 587 SMTP_HOST: str | None = None SMTP_USER: str | None = None SMTP_PASSWORD: str | None = None EMAILS_FROM_EMAIL: EmailStr | None = None EMAILS_FROM_NAME: str | None = None @model_validator(mode="after") def _set_default_emails_from(self) -> Self: if not self.EMAILS_FROM_NAME: self.EMAILS_FROM_NAME = self.PROJECT_NAME return self EMAIL_RESET_TOKEN_EXPIRE_HOURS: int = 48 @computed_field # type: ignore[prop-decorator] @property def emails_enabled(self) -> bool: return bool(self.SMTP_HOST and self.EMAILS_FROM_EMAIL) EMAIL_TEST_USER: EmailStr = "test@example.com" FIRST_SUPERUSER: EmailStr FIRST_SUPERUSER_PASSWORD: str def _check_default_secret(self, var_name: str, value: str | None) -> None: if value == "changethis": message = ( f'The value of {var_name} is "changethis", ' "for security, please change it, at least for deployments." ) if self.ENVIRONMENT == "local": warnings.warn(message, stacklevel=1) else: raise ValueError(message) @model_validator(mode="after") def _enforce_non_default_secrets(self) -> Self: self._check_default_secret("SECRET_KEY", self.SECRET_KEY) self._check_default_secret("POSTGRES_PASSWORD", self.POSTGRES_PASSWORD) self._check_default_secret( "FIRST_SUPERUSER_PASSWORD", self.FIRST_SUPERUSER_PASSWORD ) return self settings = Settings() # type: ignore ================================================ FILE: backend/app/core/db.py ================================================ from sqlmodel import Session, create_engine, select from app import crud from app.core.config import settings from app.models import User, UserCreate engine = create_engine(str(settings.SQLALCHEMY_DATABASE_URI)) # make sure all SQLModel models are imported (app.models) before initializing DB # otherwise, SQLModel might fail to initialize relationships properly # for more details: https://github.com/fastapi/full-stack-fastapi-template/issues/28 def init_db(session: Session) -> None: # Tables should be created with Alembic migrations # But if you don't want to use migrations, create # the tables un-commenting the next lines # from sqlmodel import SQLModel # This works because the models are already imported and registered from app.models # SQLModel.metadata.create_all(engine) user = session.exec( select(User).where(User.email == settings.FIRST_SUPERUSER) ).first() if not user: user_in = UserCreate( email=settings.FIRST_SUPERUSER, password=settings.FIRST_SUPERUSER_PASSWORD, is_superuser=True, ) user = crud.create_user(session=session, user_create=user_in) ================================================ FILE: backend/app/core/security.py ================================================ from datetime import datetime, timedelta, timezone from typing import Any import jwt from pwdlib import PasswordHash from pwdlib.hashers.argon2 import Argon2Hasher from pwdlib.hashers.bcrypt import BcryptHasher from app.core.config import settings password_hash = PasswordHash( ( Argon2Hasher(), BcryptHasher(), ) ) ALGORITHM = "HS256" def create_access_token(subject: str | Any, expires_delta: timedelta) -> str: expire = datetime.now(timezone.utc) + expires_delta to_encode = {"exp": expire, "sub": str(subject)} encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt def verify_password( plain_password: str, hashed_password: str ) -> tuple[bool, str | None]: return password_hash.verify_and_update(plain_password, hashed_password) def get_password_hash(password: str) -> str: return password_hash.hash(password) ================================================ FILE: backend/app/crud.py ================================================ import uuid from typing import Any from sqlmodel import Session, select from app.core.security import get_password_hash, verify_password from app.models import Item, ItemCreate, User, UserCreate, UserUpdate def create_user(*, session: Session, user_create: UserCreate) -> User: db_obj = User.model_validate( user_create, update={"hashed_password": get_password_hash(user_create.password)} ) session.add(db_obj) session.commit() session.refresh(db_obj) return db_obj def update_user(*, session: Session, db_user: User, user_in: UserUpdate) -> Any: user_data = user_in.model_dump(exclude_unset=True) extra_data = {} if "password" in user_data: password = user_data["password"] hashed_password = get_password_hash(password) extra_data["hashed_password"] = hashed_password db_user.sqlmodel_update(user_data, update=extra_data) session.add(db_user) session.commit() session.refresh(db_user) return db_user def get_user_by_email(*, session: Session, email: str) -> User | None: statement = select(User).where(User.email == email) session_user = session.exec(statement).first() return session_user # Dummy hash to use for timing attack prevention when user is not found # This is an Argon2 hash of a random password, used to ensure constant-time comparison DUMMY_HASH = "$argon2id$v=19$m=65536,t=3,p=4$MjQyZWE1MzBjYjJlZTI0Yw$YTU4NGM5ZTZmYjE2NzZlZjY0ZWY3ZGRkY2U2OWFjNjk" def authenticate(*, session: Session, email: str, password: str) -> User | None: db_user = get_user_by_email(session=session, email=email) if not db_user: # Prevent timing attacks by running password verification even when user doesn't exist # This ensures the response time is similar whether or not the email exists verify_password(password, DUMMY_HASH) return None verified, updated_password_hash = verify_password(password, db_user.hashed_password) if not verified: return None if updated_password_hash: db_user.hashed_password = updated_password_hash session.add(db_user) session.commit() session.refresh(db_user) return db_user def create_item(*, session: Session, item_in: ItemCreate, owner_id: uuid.UUID) -> Item: db_item = Item.model_validate(item_in, update={"owner_id": owner_id}) session.add(db_item) session.commit() session.refresh(db_item) return db_item ================================================ FILE: backend/app/email-templates/build/new_account.html ================================================
{{ project_name }} - New Account
Welcome to your new account!
Here are your account details:
Username: {{ username }}
Password: {{ password }}
Go to Dashboard

================================================ FILE: backend/app/email-templates/build/reset_password.html ================================================
{{ project_name }} - Password Recovery
Hello {{ username }}
We've received a request to reset your password. You can do it by clicking the button below:
Reset password
Or copy and paste the following link into your browser:
This password will expire in {{ valid_hours }} hours.

If you didn't request a password recovery you can disregard this email.
================================================ FILE: backend/app/email-templates/build/test_email.html ================================================
{{ project_name }}
Test email for: {{ email }}

================================================ FILE: backend/app/email-templates/src/new_account.mjml ================================================ {{ project_name }} - New Account Welcome to your new account! Here are your account details: Username: {{ username }} Password: {{ password }} Go to Dashboard ================================================ FILE: backend/app/email-templates/src/reset_password.mjml ================================================ {{ project_name }} - Password Recovery Hello {{ username }} We've received a request to reset your password. You can do it by clicking the button below: Reset password Or copy and paste the following link into your browser: {{ link }} This password will expire in {{ valid_hours }} hours. If you didn't request a password recovery you can disregard this email. ================================================ FILE: backend/app/email-templates/src/test_email.mjml ================================================ {{ project_name }} Test email for: {{ email }} ================================================ FILE: backend/app/initial_data.py ================================================ import logging from sqlmodel import Session from app.core.db import engine, init_db logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) def init() -> None: with Session(engine) as session: init_db(session) def main() -> None: logger.info("Creating initial data") init() logger.info("Initial data created") if __name__ == "__main__": main() ================================================ FILE: backend/app/main.py ================================================ import sentry_sdk from fastapi import FastAPI from fastapi.routing import APIRoute from starlette.middleware.cors import CORSMiddleware from app.api.main import api_router from app.core.config import settings def custom_generate_unique_id(route: APIRoute) -> str: return f"{route.tags[0]}-{route.name}" if settings.SENTRY_DSN and settings.ENVIRONMENT != "local": sentry_sdk.init(dsn=str(settings.SENTRY_DSN), enable_tracing=True) app = FastAPI( title=settings.PROJECT_NAME, openapi_url=f"{settings.API_V1_STR}/openapi.json", generate_unique_id_function=custom_generate_unique_id, ) # Set all CORS enabled origins if settings.all_cors_origins: app.add_middleware( CORSMiddleware, allow_origins=settings.all_cors_origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) app.include_router(api_router, prefix=settings.API_V1_STR) ================================================ FILE: backend/app/models.py ================================================ import uuid from datetime import datetime, timezone from pydantic import EmailStr from sqlalchemy import DateTime from sqlmodel import Field, Relationship, SQLModel def get_datetime_utc() -> datetime: return datetime.now(timezone.utc) # Shared properties class UserBase(SQLModel): email: EmailStr = Field(unique=True, index=True, max_length=255) is_active: bool = True is_superuser: bool = False full_name: str | None = Field(default=None, max_length=255) # Properties to receive via API on creation class UserCreate(UserBase): password: str = Field(min_length=8, max_length=128) class UserRegister(SQLModel): email: EmailStr = Field(max_length=255) password: str = Field(min_length=8, max_length=128) full_name: str | None = Field(default=None, max_length=255) # Properties to receive via API on update, all are optional class UserUpdate(UserBase): email: EmailStr | None = Field(default=None, max_length=255) # type: ignore password: str | None = Field(default=None, min_length=8, max_length=128) class UserUpdateMe(SQLModel): full_name: str | None = Field(default=None, max_length=255) email: EmailStr | None = Field(default=None, max_length=255) class UpdatePassword(SQLModel): current_password: str = Field(min_length=8, max_length=128) new_password: str = Field(min_length=8, max_length=128) # Database model, database table inferred from class name class User(UserBase, table=True): id: uuid.UUID = Field(default_factory=uuid.uuid4, primary_key=True) hashed_password: str created_at: datetime | None = Field( default_factory=get_datetime_utc, sa_type=DateTime(timezone=True), # type: ignore ) items: list["Item"] = Relationship(back_populates="owner", cascade_delete=True) # Properties to return via API, id is always required class UserPublic(UserBase): id: uuid.UUID created_at: datetime | None = None class UsersPublic(SQLModel): data: list[UserPublic] count: int # Shared properties class ItemBase(SQLModel): title: str = Field(min_length=1, max_length=255) description: str | None = Field(default=None, max_length=255) # Properties to receive on item creation class ItemCreate(ItemBase): pass # Properties to receive on item update class ItemUpdate(ItemBase): title: str | None = Field(default=None, min_length=1, max_length=255) # type: ignore # Database model, database table inferred from class name class Item(ItemBase, table=True): id: uuid.UUID = Field(default_factory=uuid.uuid4, primary_key=True) created_at: datetime | None = Field( default_factory=get_datetime_utc, sa_type=DateTime(timezone=True), # type: ignore ) owner_id: uuid.UUID = Field( foreign_key="user.id", nullable=False, ondelete="CASCADE" ) owner: User | None = Relationship(back_populates="items") # Properties to return via API, id is always required class ItemPublic(ItemBase): id: uuid.UUID owner_id: uuid.UUID created_at: datetime | None = None class ItemsPublic(SQLModel): data: list[ItemPublic] count: int # Generic message class Message(SQLModel): message: str # JSON payload containing access token class Token(SQLModel): access_token: str token_type: str = "bearer" # Contents of JWT token class TokenPayload(SQLModel): sub: str | None = None class NewPassword(SQLModel): token: str new_password: str = Field(min_length=8, max_length=128) ================================================ FILE: backend/app/tests_pre_start.py ================================================ import logging from sqlalchemy import Engine from sqlmodel import Session, select from tenacity import after_log, before_log, retry, stop_after_attempt, wait_fixed from app.core.db import engine logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) max_tries = 60 * 5 # 5 minutes wait_seconds = 1 @retry( stop=stop_after_attempt(max_tries), wait=wait_fixed(wait_seconds), before=before_log(logger, logging.INFO), after=after_log(logger, logging.WARN), ) def init(db_engine: Engine) -> None: try: # Try to create session to check if DB is awake with Session(db_engine) as session: session.exec(select(1)) except Exception as e: logger.error(e) raise e def main() -> None: logger.info("Initializing service") init(engine) logger.info("Service finished initializing") if __name__ == "__main__": main() ================================================ FILE: backend/app/utils.py ================================================ import logging from dataclasses import dataclass from datetime import datetime, timedelta, timezone from pathlib import Path from typing import Any import emails # type: ignore import jwt from jinja2 import Template from jwt.exceptions import InvalidTokenError from app.core import security from app.core.config import settings logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) @dataclass class EmailData: html_content: str subject: str def render_email_template(*, template_name: str, context: dict[str, Any]) -> str: template_str = ( Path(__file__).parent / "email-templates" / "build" / template_name ).read_text() html_content = Template(template_str).render(context) return html_content def send_email( *, email_to: str, subject: str = "", html_content: str = "", ) -> None: assert settings.emails_enabled, "no provided configuration for email variables" message = emails.Message( subject=subject, html=html_content, mail_from=(settings.EMAILS_FROM_NAME, settings.EMAILS_FROM_EMAIL), ) smtp_options = {"host": settings.SMTP_HOST, "port": settings.SMTP_PORT} if settings.SMTP_TLS: smtp_options["tls"] = True elif settings.SMTP_SSL: smtp_options["ssl"] = True if settings.SMTP_USER: smtp_options["user"] = settings.SMTP_USER if settings.SMTP_PASSWORD: smtp_options["password"] = settings.SMTP_PASSWORD response = message.send(to=email_to, smtp=smtp_options) logger.info(f"send email result: {response}") def generate_test_email(email_to: str) -> EmailData: project_name = settings.PROJECT_NAME subject = f"{project_name} - Test email" html_content = render_email_template( template_name="test_email.html", context={"project_name": settings.PROJECT_NAME, "email": email_to}, ) return EmailData(html_content=html_content, subject=subject) def generate_reset_password_email(email_to: str, email: str, token: str) -> EmailData: project_name = settings.PROJECT_NAME subject = f"{project_name} - Password recovery for user {email}" link = f"{settings.FRONTEND_HOST}/reset-password?token={token}" html_content = render_email_template( template_name="reset_password.html", context={ "project_name": settings.PROJECT_NAME, "username": email, "email": email_to, "valid_hours": settings.EMAIL_RESET_TOKEN_EXPIRE_HOURS, "link": link, }, ) return EmailData(html_content=html_content, subject=subject) def generate_new_account_email( email_to: str, username: str, password: str ) -> EmailData: project_name = settings.PROJECT_NAME subject = f"{project_name} - New account for user {username}" html_content = render_email_template( template_name="new_account.html", context={ "project_name": settings.PROJECT_NAME, "username": username, "password": password, "email": email_to, "link": settings.FRONTEND_HOST, }, ) return EmailData(html_content=html_content, subject=subject) def generate_password_reset_token(email: str) -> str: delta = timedelta(hours=settings.EMAIL_RESET_TOKEN_EXPIRE_HOURS) now = datetime.now(timezone.utc) expires = now + delta exp = expires.timestamp() encoded_jwt = jwt.encode( {"exp": exp, "nbf": now, "sub": email}, settings.SECRET_KEY, algorithm=security.ALGORITHM, ) return encoded_jwt def verify_password_reset_token(token: str) -> str | None: try: decoded_token = jwt.decode( token, settings.SECRET_KEY, algorithms=[security.ALGORITHM] ) return str(decoded_token["sub"]) except InvalidTokenError: return None ================================================ FILE: backend/pyproject.toml ================================================ [project] name = "app" version = "0.1.0" description = "" requires-python = ">=3.10,<4.0" dependencies = [ "fastapi[standard]<1.0.0,>=0.114.2", "python-multipart<1.0.0,>=0.0.7", "email-validator<3.0.0.0,>=2.1.0.post1", "tenacity<9.0.0,>=8.2.3", "pydantic>2.0", "emails<1.0,>=0.6", "jinja2<4.0.0,>=3.1.4", "alembic<2.0.0,>=1.12.1", "httpx<1.0.0,>=0.25.1", "psycopg[binary]<4.0.0,>=3.1.13", "sqlmodel<1.0.0,>=0.0.21", "pydantic-settings<3.0.0,>=2.2.1", "sentry-sdk[fastapi]>=2.0.0,<3.0.0", "pyjwt<3.0.0,>=2.8.0", "pwdlib[argon2,bcrypt]>=0.3.0", ] [dependency-groups] dev = [ "pytest<8.0.0,>=7.4.3", "mypy<2.0.0,>=1.8.0", "ruff<1.0.0,>=0.2.2", "prek>=0.2.24,<1.0.0", "coverage<8.0.0,>=7.4.3", ] [build-system] requires = ["hatchling"] build-backend = "hatchling.build" [tool.mypy] strict = true exclude = ["venv", ".venv", "alembic"] [tool.ruff] target-version = "py310" exclude = ["alembic"] [tool.ruff.lint] select = [ "E", # pycodestyle errors "W", # pycodestyle warnings "F", # pyflakes "I", # isort "B", # flake8-bugbear "C4", # flake8-comprehensions "UP", # pyupgrade "ARG001", # unused arguments in functions "T201", # print statements are not allowed ] ignore = [ "E501", # line too long, handled by black "B008", # do not perform function calls in argument defaults "W191", # indentation contains tabs "B904", # Allow raising exceptions without from e, for HTTPException ] [tool.ruff.lint.pyupgrade] # Preserve types, even if a file imports `from __future__ import annotations`. keep-runtime-typing = true [tool.coverage.run] source = ["app"] dynamic_context = "test_function" [tool.coverage.report] show_missing = true sort = "-Cover" [tool.coverage.html] show_contexts = true ================================================ FILE: backend/scripts/format.sh ================================================ #!/bin/sh -e set -x ruff check app scripts --fix ruff format app scripts ================================================ FILE: backend/scripts/lint.sh ================================================ #!/usr/bin/env bash set -e set -x mypy app ruff check app ruff format app --check ================================================ FILE: backend/scripts/prestart.sh ================================================ #! /usr/bin/env bash set -e set -x # Let the DB start python app/backend_pre_start.py # Run migrations alembic upgrade head # Create initial data in DB python app/initial_data.py ================================================ FILE: backend/scripts/test.sh ================================================ #!/usr/bin/env bash set -e set -x coverage run -m pytest tests/ coverage report coverage html --title "${@-coverage}" ================================================ FILE: backend/scripts/tests-start.sh ================================================ #! /usr/bin/env bash set -e set -x python app/tests_pre_start.py bash scripts/test.sh "$@" ================================================ FILE: backend/tests/__init__.py ================================================ ================================================ FILE: backend/tests/api/__init__.py ================================================ ================================================ FILE: backend/tests/api/routes/__init__.py ================================================ ================================================ FILE: backend/tests/api/routes/test_items.py ================================================ import uuid from fastapi.testclient import TestClient from sqlmodel import Session from app.core.config import settings from tests.utils.item import create_random_item def test_create_item( client: TestClient, superuser_token_headers: dict[str, str] ) -> None: data = {"title": "Foo", "description": "Fighters"} response = client.post( f"{settings.API_V1_STR}/items/", headers=superuser_token_headers, json=data, ) assert response.status_code == 200 content = response.json() assert content["title"] == data["title"] assert content["description"] == data["description"] assert "id" in content assert "owner_id" in content def test_read_item( client: TestClient, superuser_token_headers: dict[str, str], db: Session ) -> None: item = create_random_item(db) response = client.get( f"{settings.API_V1_STR}/items/{item.id}", headers=superuser_token_headers, ) assert response.status_code == 200 content = response.json() assert content["title"] == item.title assert content["description"] == item.description assert content["id"] == str(item.id) assert content["owner_id"] == str(item.owner_id) def test_read_item_not_found( client: TestClient, superuser_token_headers: dict[str, str] ) -> None: response = client.get( f"{settings.API_V1_STR}/items/{uuid.uuid4()}", headers=superuser_token_headers, ) assert response.status_code == 404 content = response.json() assert content["detail"] == "Item not found" def test_read_item_not_enough_permissions( client: TestClient, normal_user_token_headers: dict[str, str], db: Session ) -> None: item = create_random_item(db) response = client.get( f"{settings.API_V1_STR}/items/{item.id}", headers=normal_user_token_headers, ) assert response.status_code == 403 content = response.json() assert content["detail"] == "Not enough permissions" def test_read_items( client: TestClient, superuser_token_headers: dict[str, str], db: Session ) -> None: create_random_item(db) create_random_item(db) response = client.get( f"{settings.API_V1_STR}/items/", headers=superuser_token_headers, ) assert response.status_code == 200 content = response.json() assert len(content["data"]) >= 2 def test_update_item( client: TestClient, superuser_token_headers: dict[str, str], db: Session ) -> None: item = create_random_item(db) data = {"title": "Updated title", "description": "Updated description"} response = client.put( f"{settings.API_V1_STR}/items/{item.id}", headers=superuser_token_headers, json=data, ) assert response.status_code == 200 content = response.json() assert content["title"] == data["title"] assert content["description"] == data["description"] assert content["id"] == str(item.id) assert content["owner_id"] == str(item.owner_id) def test_update_item_not_found( client: TestClient, superuser_token_headers: dict[str, str] ) -> None: data = {"title": "Updated title", "description": "Updated description"} response = client.put( f"{settings.API_V1_STR}/items/{uuid.uuid4()}", headers=superuser_token_headers, json=data, ) assert response.status_code == 404 content = response.json() assert content["detail"] == "Item not found" def test_update_item_not_enough_permissions( client: TestClient, normal_user_token_headers: dict[str, str], db: Session ) -> None: item = create_random_item(db) data = {"title": "Updated title", "description": "Updated description"} response = client.put( f"{settings.API_V1_STR}/items/{item.id}", headers=normal_user_token_headers, json=data, ) assert response.status_code == 403 content = response.json() assert content["detail"] == "Not enough permissions" def test_delete_item( client: TestClient, superuser_token_headers: dict[str, str], db: Session ) -> None: item = create_random_item(db) response = client.delete( f"{settings.API_V1_STR}/items/{item.id}", headers=superuser_token_headers, ) assert response.status_code == 200 content = response.json() assert content["message"] == "Item deleted successfully" def test_delete_item_not_found( client: TestClient, superuser_token_headers: dict[str, str] ) -> None: response = client.delete( f"{settings.API_V1_STR}/items/{uuid.uuid4()}", headers=superuser_token_headers, ) assert response.status_code == 404 content = response.json() assert content["detail"] == "Item not found" def test_delete_item_not_enough_permissions( client: TestClient, normal_user_token_headers: dict[str, str], db: Session ) -> None: item = create_random_item(db) response = client.delete( f"{settings.API_V1_STR}/items/{item.id}", headers=normal_user_token_headers, ) assert response.status_code == 403 content = response.json() assert content["detail"] == "Not enough permissions" ================================================ FILE: backend/tests/api/routes/test_login.py ================================================ from unittest.mock import patch from fastapi.testclient import TestClient from pwdlib.hashers.bcrypt import BcryptHasher from sqlmodel import Session from app.core.config import settings from app.core.security import get_password_hash, verify_password from app.crud import create_user from app.models import User, UserCreate from app.utils import generate_password_reset_token from tests.utils.user import user_authentication_headers from tests.utils.utils import random_email, random_lower_string def test_get_access_token(client: TestClient) -> None: login_data = { "username": settings.FIRST_SUPERUSER, "password": settings.FIRST_SUPERUSER_PASSWORD, } r = client.post(f"{settings.API_V1_STR}/login/access-token", data=login_data) tokens = r.json() assert r.status_code == 200 assert "access_token" in tokens assert tokens["access_token"] def test_get_access_token_incorrect_password(client: TestClient) -> None: login_data = { "username": settings.FIRST_SUPERUSER, "password": "incorrect", } r = client.post(f"{settings.API_V1_STR}/login/access-token", data=login_data) assert r.status_code == 400 def test_use_access_token( client: TestClient, superuser_token_headers: dict[str, str] ) -> None: r = client.post( f"{settings.API_V1_STR}/login/test-token", headers=superuser_token_headers, ) result = r.json() assert r.status_code == 200 assert "email" in result def test_recovery_password( client: TestClient, normal_user_token_headers: dict[str, str] ) -> None: with ( patch("app.core.config.settings.SMTP_HOST", "smtp.example.com"), patch("app.core.config.settings.SMTP_USER", "admin@example.com"), ): email = "test@example.com" r = client.post( f"{settings.API_V1_STR}/password-recovery/{email}", headers=normal_user_token_headers, ) assert r.status_code == 200 assert r.json() == { "message": "If that email is registered, we sent a password recovery link" } def test_recovery_password_user_not_exits( client: TestClient, normal_user_token_headers: dict[str, str] ) -> None: email = "jVgQr@example.com" r = client.post( f"{settings.API_V1_STR}/password-recovery/{email}", headers=normal_user_token_headers, ) # Should return 200 with generic message to prevent email enumeration attacks assert r.status_code == 200 assert r.json() == { "message": "If that email is registered, we sent a password recovery link" } def test_reset_password(client: TestClient, db: Session) -> None: email = random_email() password = random_lower_string() new_password = random_lower_string() user_create = UserCreate( email=email, full_name="Test User", password=password, is_active=True, is_superuser=False, ) user = create_user(session=db, user_create=user_create) token = generate_password_reset_token(email=email) headers = user_authentication_headers(client=client, email=email, password=password) data = {"new_password": new_password, "token": token} r = client.post( f"{settings.API_V1_STR}/reset-password/", headers=headers, json=data, ) assert r.status_code == 200 assert r.json() == {"message": "Password updated successfully"} db.refresh(user) verified, _ = verify_password(new_password, user.hashed_password) assert verified def test_reset_password_invalid_token( client: TestClient, superuser_token_headers: dict[str, str] ) -> None: data = {"new_password": "changethis", "token": "invalid"} r = client.post( f"{settings.API_V1_STR}/reset-password/", headers=superuser_token_headers, json=data, ) response = r.json() assert "detail" in response assert r.status_code == 400 assert response["detail"] == "Invalid token" def test_login_with_bcrypt_password_upgrades_to_argon2( client: TestClient, db: Session ) -> None: """Test that logging in with a bcrypt password hash upgrades it to argon2.""" email = random_email() password = random_lower_string() # Create a bcrypt hash directly (simulating legacy password) bcrypt_hasher = BcryptHasher() bcrypt_hash = bcrypt_hasher.hash(password) assert bcrypt_hash.startswith("$2") # bcrypt hashes start with $2 user = User(email=email, hashed_password=bcrypt_hash, is_active=True) db.add(user) db.commit() db.refresh(user) assert user.hashed_password.startswith("$2") login_data = {"username": email, "password": password} r = client.post(f"{settings.API_V1_STR}/login/access-token", data=login_data) assert r.status_code == 200 tokens = r.json() assert "access_token" in tokens db.refresh(user) # Verify the hash was upgraded to argon2 assert user.hashed_password.startswith("$argon2") verified, updated_hash = verify_password(password, user.hashed_password) assert verified # Should not need another update since it's already argon2 assert updated_hash is None def test_login_with_argon2_password_keeps_hash(client: TestClient, db: Session) -> None: """Test that logging in with an argon2 password hash does not update it.""" email = random_email() password = random_lower_string() # Create an argon2 hash (current default) argon2_hash = get_password_hash(password) assert argon2_hash.startswith("$argon2") # Create user with argon2 hash user = User(email=email, hashed_password=argon2_hash, is_active=True) db.add(user) db.commit() db.refresh(user) original_hash = user.hashed_password login_data = {"username": email, "password": password} r = client.post(f"{settings.API_V1_STR}/login/access-token", data=login_data) assert r.status_code == 200 tokens = r.json() assert "access_token" in tokens db.refresh(user) assert user.hashed_password == original_hash assert user.hashed_password.startswith("$argon2") ================================================ FILE: backend/tests/api/routes/test_private.py ================================================ from fastapi.testclient import TestClient from sqlmodel import Session, select from app.core.config import settings from app.models import User def test_create_user(client: TestClient, db: Session) -> None: r = client.post( f"{settings.API_V1_STR}/private/users/", json={ "email": "pollo@listo.com", "password": "password123", "full_name": "Pollo Listo", }, ) assert r.status_code == 200 data = r.json() user = db.exec(select(User).where(User.id == data["id"])).first() assert user assert user.email == "pollo@listo.com" assert user.full_name == "Pollo Listo" ================================================ FILE: backend/tests/api/routes/test_users.py ================================================ import uuid from unittest.mock import patch from fastapi.testclient import TestClient from sqlmodel import Session, select from app import crud from app.core.config import settings from app.core.security import verify_password from app.models import User, UserCreate from tests.utils.user import create_random_user from tests.utils.utils import random_email, random_lower_string def test_get_users_superuser_me( client: TestClient, superuser_token_headers: dict[str, str] ) -> None: r = client.get(f"{settings.API_V1_STR}/users/me", headers=superuser_token_headers) current_user = r.json() assert current_user assert current_user["is_active"] is True assert current_user["is_superuser"] assert current_user["email"] == settings.FIRST_SUPERUSER def test_get_users_normal_user_me( client: TestClient, normal_user_token_headers: dict[str, str] ) -> None: r = client.get(f"{settings.API_V1_STR}/users/me", headers=normal_user_token_headers) current_user = r.json() assert current_user assert current_user["is_active"] is True assert current_user["is_superuser"] is False assert current_user["email"] == settings.EMAIL_TEST_USER def test_create_user_new_email( client: TestClient, superuser_token_headers: dict[str, str], db: Session ) -> None: with ( patch("app.utils.send_email", return_value=None), patch("app.core.config.settings.SMTP_HOST", "smtp.example.com"), patch("app.core.config.settings.SMTP_USER", "admin@example.com"), ): username = random_email() password = random_lower_string() data = {"email": username, "password": password} r = client.post( f"{settings.API_V1_STR}/users/", headers=superuser_token_headers, json=data, ) assert 200 <= r.status_code < 300 created_user = r.json() user = crud.get_user_by_email(session=db, email=username) assert user assert user.email == created_user["email"] def test_get_existing_user_as_superuser( client: TestClient, superuser_token_headers: dict[str, str], db: Session ) -> None: username = random_email() password = random_lower_string() user_in = UserCreate(email=username, password=password) user = crud.create_user(session=db, user_create=user_in) user_id = user.id r = client.get( f"{settings.API_V1_STR}/users/{user_id}", headers=superuser_token_headers, ) assert 200 <= r.status_code < 300 api_user = r.json() existing_user = crud.get_user_by_email(session=db, email=username) assert existing_user assert existing_user.email == api_user["email"] def test_get_non_existing_user_as_superuser( client: TestClient, superuser_token_headers: dict[str, str] ) -> None: r = client.get( f"{settings.API_V1_STR}/users/{uuid.uuid4()}", headers=superuser_token_headers, ) assert r.status_code == 404 assert r.json() == {"detail": "User not found"} def test_get_existing_user_current_user(client: TestClient, db: Session) -> None: username = random_email() password = random_lower_string() user_in = UserCreate(email=username, password=password) user = crud.create_user(session=db, user_create=user_in) user_id = user.id login_data = { "username": username, "password": password, } r = client.post(f"{settings.API_V1_STR}/login/access-token", data=login_data) tokens = r.json() a_token = tokens["access_token"] headers = {"Authorization": f"Bearer {a_token}"} r = client.get( f"{settings.API_V1_STR}/users/{user_id}", headers=headers, ) assert 200 <= r.status_code < 300 api_user = r.json() existing_user = crud.get_user_by_email(session=db, email=username) assert existing_user assert existing_user.email == api_user["email"] def test_get_existing_user_permissions_error( db: Session, client: TestClient, normal_user_token_headers: dict[str, str], ) -> None: user = create_random_user(db) r = client.get( f"{settings.API_V1_STR}/users/{user.id}", headers=normal_user_token_headers, ) assert r.status_code == 403 assert r.json() == {"detail": "The user doesn't have enough privileges"} def test_get_non_existing_user_permissions_error( client: TestClient, normal_user_token_headers: dict[str, str], ) -> None: user_id = uuid.uuid4() r = client.get( f"{settings.API_V1_STR}/users/{user_id}", headers=normal_user_token_headers, ) assert r.status_code == 403 assert r.json() == {"detail": "The user doesn't have enough privileges"} def test_create_user_existing_username( client: TestClient, superuser_token_headers: dict[str, str], db: Session ) -> None: username = random_email() # username = email password = random_lower_string() user_in = UserCreate(email=username, password=password) crud.create_user(session=db, user_create=user_in) data = {"email": username, "password": password} r = client.post( f"{settings.API_V1_STR}/users/", headers=superuser_token_headers, json=data, ) created_user = r.json() assert r.status_code == 400 assert "_id" not in created_user def test_create_user_by_normal_user( client: TestClient, normal_user_token_headers: dict[str, str] ) -> None: username = random_email() password = random_lower_string() data = {"email": username, "password": password} r = client.post( f"{settings.API_V1_STR}/users/", headers=normal_user_token_headers, json=data, ) assert r.status_code == 403 def test_retrieve_users( client: TestClient, superuser_token_headers: dict[str, str], db: Session ) -> None: username = random_email() password = random_lower_string() user_in = UserCreate(email=username, password=password) crud.create_user(session=db, user_create=user_in) username2 = random_email() password2 = random_lower_string() user_in2 = UserCreate(email=username2, password=password2) crud.create_user(session=db, user_create=user_in2) r = client.get(f"{settings.API_V1_STR}/users/", headers=superuser_token_headers) all_users = r.json() assert len(all_users["data"]) > 1 assert "count" in all_users for item in all_users["data"]: assert "email" in item def test_update_user_me( client: TestClient, normal_user_token_headers: dict[str, str], db: Session ) -> None: full_name = "Updated Name" email = random_email() data = {"full_name": full_name, "email": email} r = client.patch( f"{settings.API_V1_STR}/users/me", headers=normal_user_token_headers, json=data, ) assert r.status_code == 200 updated_user = r.json() assert updated_user["email"] == email assert updated_user["full_name"] == full_name user_query = select(User).where(User.email == email) user_db = db.exec(user_query).first() assert user_db assert user_db.email == email assert user_db.full_name == full_name def test_update_password_me( client: TestClient, superuser_token_headers: dict[str, str], db: Session ) -> None: new_password = random_lower_string() data = { "current_password": settings.FIRST_SUPERUSER_PASSWORD, "new_password": new_password, } r = client.patch( f"{settings.API_V1_STR}/users/me/password", headers=superuser_token_headers, json=data, ) assert r.status_code == 200 updated_user = r.json() assert updated_user["message"] == "Password updated successfully" user_query = select(User).where(User.email == settings.FIRST_SUPERUSER) user_db = db.exec(user_query).first() assert user_db assert user_db.email == settings.FIRST_SUPERUSER verified, _ = verify_password(new_password, user_db.hashed_password) assert verified # Revert to the old password to keep consistency in test old_data = { "current_password": new_password, "new_password": settings.FIRST_SUPERUSER_PASSWORD, } r = client.patch( f"{settings.API_V1_STR}/users/me/password", headers=superuser_token_headers, json=old_data, ) db.refresh(user_db) assert r.status_code == 200 verified, _ = verify_password( settings.FIRST_SUPERUSER_PASSWORD, user_db.hashed_password ) assert verified def test_update_password_me_incorrect_password( client: TestClient, superuser_token_headers: dict[str, str] ) -> None: new_password = random_lower_string() data = {"current_password": new_password, "new_password": new_password} r = client.patch( f"{settings.API_V1_STR}/users/me/password", headers=superuser_token_headers, json=data, ) assert r.status_code == 400 updated_user = r.json() assert updated_user["detail"] == "Incorrect password" def test_update_user_me_email_exists( client: TestClient, normal_user_token_headers: dict[str, str], db: Session ) -> None: username = random_email() password = random_lower_string() user_in = UserCreate(email=username, password=password) user = crud.create_user(session=db, user_create=user_in) data = {"email": user.email} r = client.patch( f"{settings.API_V1_STR}/users/me", headers=normal_user_token_headers, json=data, ) assert r.status_code == 409 assert r.json()["detail"] == "User with this email already exists" def test_update_password_me_same_password_error( client: TestClient, superuser_token_headers: dict[str, str] ) -> None: data = { "current_password": settings.FIRST_SUPERUSER_PASSWORD, "new_password": settings.FIRST_SUPERUSER_PASSWORD, } r = client.patch( f"{settings.API_V1_STR}/users/me/password", headers=superuser_token_headers, json=data, ) assert r.status_code == 400 updated_user = r.json() assert ( updated_user["detail"] == "New password cannot be the same as the current one" ) def test_register_user(client: TestClient, db: Session) -> None: username = random_email() password = random_lower_string() full_name = random_lower_string() data = {"email": username, "password": password, "full_name": full_name} r = client.post( f"{settings.API_V1_STR}/users/signup", json=data, ) assert r.status_code == 200 created_user = r.json() assert created_user["email"] == username assert created_user["full_name"] == full_name user_query = select(User).where(User.email == username) user_db = db.exec(user_query).first() assert user_db assert user_db.email == username assert user_db.full_name == full_name verified, _ = verify_password(password, user_db.hashed_password) assert verified def test_register_user_already_exists_error(client: TestClient) -> None: password = random_lower_string() full_name = random_lower_string() data = { "email": settings.FIRST_SUPERUSER, "password": password, "full_name": full_name, } r = client.post( f"{settings.API_V1_STR}/users/signup", json=data, ) assert r.status_code == 400 assert r.json()["detail"] == "The user with this email already exists in the system" def test_update_user( client: TestClient, superuser_token_headers: dict[str, str], db: Session ) -> None: username = random_email() password = random_lower_string() user_in = UserCreate(email=username, password=password) user = crud.create_user(session=db, user_create=user_in) data = {"full_name": "Updated_full_name"} r = client.patch( f"{settings.API_V1_STR}/users/{user.id}", headers=superuser_token_headers, json=data, ) assert r.status_code == 200 updated_user = r.json() assert updated_user["full_name"] == "Updated_full_name" user_query = select(User).where(User.email == username) user_db = db.exec(user_query).first() db.refresh(user_db) assert user_db assert user_db.full_name == "Updated_full_name" def test_update_user_not_exists( client: TestClient, superuser_token_headers: dict[str, str] ) -> None: data = {"full_name": "Updated_full_name"} r = client.patch( f"{settings.API_V1_STR}/users/{uuid.uuid4()}", headers=superuser_token_headers, json=data, ) assert r.status_code == 404 assert r.json()["detail"] == "The user with this id does not exist in the system" def test_update_user_email_exists( client: TestClient, superuser_token_headers: dict[str, str], db: Session ) -> None: username = random_email() password = random_lower_string() user_in = UserCreate(email=username, password=password) user = crud.create_user(session=db, user_create=user_in) username2 = random_email() password2 = random_lower_string() user_in2 = UserCreate(email=username2, password=password2) user2 = crud.create_user(session=db, user_create=user_in2) data = {"email": user2.email} r = client.patch( f"{settings.API_V1_STR}/users/{user.id}", headers=superuser_token_headers, json=data, ) assert r.status_code == 409 assert r.json()["detail"] == "User with this email already exists" def test_delete_user_me(client: TestClient, db: Session) -> None: username = random_email() password = random_lower_string() user_in = UserCreate(email=username, password=password) user = crud.create_user(session=db, user_create=user_in) user_id = user.id login_data = { "username": username, "password": password, } r = client.post(f"{settings.API_V1_STR}/login/access-token", data=login_data) tokens = r.json() a_token = tokens["access_token"] headers = {"Authorization": f"Bearer {a_token}"} r = client.delete( f"{settings.API_V1_STR}/users/me", headers=headers, ) assert r.status_code == 200 deleted_user = r.json() assert deleted_user["message"] == "User deleted successfully" result = db.exec(select(User).where(User.id == user_id)).first() assert result is None user_query = select(User).where(User.id == user_id) user_db = db.execute(user_query).first() assert user_db is None def test_delete_user_me_as_superuser( client: TestClient, superuser_token_headers: dict[str, str] ) -> None: r = client.delete( f"{settings.API_V1_STR}/users/me", headers=superuser_token_headers, ) assert r.status_code == 403 response = r.json() assert response["detail"] == "Super users are not allowed to delete themselves" def test_delete_user_super_user( client: TestClient, superuser_token_headers: dict[str, str], db: Session ) -> None: username = random_email() password = random_lower_string() user_in = UserCreate(email=username, password=password) user = crud.create_user(session=db, user_create=user_in) user_id = user.id r = client.delete( f"{settings.API_V1_STR}/users/{user_id}", headers=superuser_token_headers, ) assert r.status_code == 200 deleted_user = r.json() assert deleted_user["message"] == "User deleted successfully" result = db.exec(select(User).where(User.id == user_id)).first() assert result is None def test_delete_user_not_found( client: TestClient, superuser_token_headers: dict[str, str] ) -> None: r = client.delete( f"{settings.API_V1_STR}/users/{uuid.uuid4()}", headers=superuser_token_headers, ) assert r.status_code == 404 assert r.json()["detail"] == "User not found" def test_delete_user_current_super_user_error( client: TestClient, superuser_token_headers: dict[str, str], db: Session ) -> None: super_user = crud.get_user_by_email(session=db, email=settings.FIRST_SUPERUSER) assert super_user user_id = super_user.id r = client.delete( f"{settings.API_V1_STR}/users/{user_id}", headers=superuser_token_headers, ) assert r.status_code == 403 assert r.json()["detail"] == "Super users are not allowed to delete themselves" def test_delete_user_without_privileges( client: TestClient, normal_user_token_headers: dict[str, str], db: Session ) -> None: username = random_email() password = random_lower_string() user_in = UserCreate(email=username, password=password) user = crud.create_user(session=db, user_create=user_in) r = client.delete( f"{settings.API_V1_STR}/users/{user.id}", headers=normal_user_token_headers, ) assert r.status_code == 403 assert r.json()["detail"] == "The user doesn't have enough privileges" ================================================ FILE: backend/tests/conftest.py ================================================ from collections.abc import Generator import pytest from fastapi.testclient import TestClient from sqlmodel import Session, delete from app.core.config import settings from app.core.db import engine, init_db from app.main import app from app.models import Item, User from tests.utils.user import authentication_token_from_email from tests.utils.utils import get_superuser_token_headers @pytest.fixture(scope="session", autouse=True) def db() -> Generator[Session, None, None]: with Session(engine) as session: init_db(session) yield session statement = delete(Item) session.execute(statement) statement = delete(User) session.execute(statement) session.commit() @pytest.fixture(scope="module") def client() -> Generator[TestClient, None, None]: with TestClient(app) as c: yield c @pytest.fixture(scope="module") def superuser_token_headers(client: TestClient) -> dict[str, str]: return get_superuser_token_headers(client) @pytest.fixture(scope="module") def normal_user_token_headers(client: TestClient, db: Session) -> dict[str, str]: return authentication_token_from_email( client=client, email=settings.EMAIL_TEST_USER, db=db ) ================================================ FILE: backend/tests/crud/__init__.py ================================================ ================================================ FILE: backend/tests/crud/test_user.py ================================================ from fastapi.encoders import jsonable_encoder from pwdlib.hashers.bcrypt import BcryptHasher from sqlmodel import Session from app import crud from app.core.security import verify_password from app.models import User, UserCreate, UserUpdate from tests.utils.utils import random_email, random_lower_string def test_create_user(db: Session) -> None: email = random_email() password = random_lower_string() user_in = UserCreate(email=email, password=password) user = crud.create_user(session=db, user_create=user_in) assert user.email == email assert hasattr(user, "hashed_password") def test_authenticate_user(db: Session) -> None: email = random_email() password = random_lower_string() user_in = UserCreate(email=email, password=password) user = crud.create_user(session=db, user_create=user_in) authenticated_user = crud.authenticate(session=db, email=email, password=password) assert authenticated_user assert user.email == authenticated_user.email def test_not_authenticate_user(db: Session) -> None: email = random_email() password = random_lower_string() user = crud.authenticate(session=db, email=email, password=password) assert user is None def test_check_if_user_is_active(db: Session) -> None: email = random_email() password = random_lower_string() user_in = UserCreate(email=email, password=password) user = crud.create_user(session=db, user_create=user_in) assert user.is_active is True def test_check_if_user_is_active_inactive(db: Session) -> None: email = random_email() password = random_lower_string() user_in = UserCreate(email=email, password=password, is_active=False) user = crud.create_user(session=db, user_create=user_in) assert user.is_active is False def test_check_if_user_is_superuser(db: Session) -> None: email = random_email() password = random_lower_string() user_in = UserCreate(email=email, password=password, is_superuser=True) user = crud.create_user(session=db, user_create=user_in) assert user.is_superuser is True def test_check_if_user_is_superuser_normal_user(db: Session) -> None: username = random_email() password = random_lower_string() user_in = UserCreate(email=username, password=password) user = crud.create_user(session=db, user_create=user_in) assert user.is_superuser is False def test_get_user(db: Session) -> None: password = random_lower_string() username = random_email() user_in = UserCreate(email=username, password=password, is_superuser=True) user = crud.create_user(session=db, user_create=user_in) user_2 = db.get(User, user.id) assert user_2 assert user.email == user_2.email assert jsonable_encoder(user) == jsonable_encoder(user_2) def test_update_user(db: Session) -> None: password = random_lower_string() email = random_email() user_in = UserCreate(email=email, password=password, is_superuser=True) user = crud.create_user(session=db, user_create=user_in) new_password = random_lower_string() user_in_update = UserUpdate(password=new_password, is_superuser=True) if user.id is not None: crud.update_user(session=db, db_user=user, user_in=user_in_update) user_2 = db.get(User, user.id) assert user_2 assert user.email == user_2.email verified, _ = verify_password(new_password, user_2.hashed_password) assert verified def test_authenticate_user_with_bcrypt_upgrades_to_argon2(db: Session) -> None: """Test that a user with bcrypt password hash gets upgraded to argon2 on login.""" email = random_email() password = random_lower_string() # Create a bcrypt hash directly (simulating legacy password) bcrypt_hasher = BcryptHasher() bcrypt_hash = bcrypt_hasher.hash(password) assert bcrypt_hash.startswith("$2") # bcrypt hashes start with $2 # Create user with bcrypt hash directly in the database user = User(email=email, hashed_password=bcrypt_hash) db.add(user) db.commit() db.refresh(user) # Verify the hash is bcrypt before authentication assert user.hashed_password.startswith("$2") # Authenticate - this should upgrade the hash to argon2 authenticated_user = crud.authenticate(session=db, email=email, password=password) assert authenticated_user assert authenticated_user.email == email db.refresh(authenticated_user) # Verify the hash was upgraded to argon2 assert authenticated_user.hashed_password.startswith("$argon2") verified, updated_hash = verify_password( password, authenticated_user.hashed_password ) assert verified # Should not need another update since it's already argon2 assert updated_hash is None ================================================ FILE: backend/tests/scripts/__init__.py ================================================ ================================================ FILE: backend/tests/scripts/test_backend_pre_start.py ================================================ from unittest.mock import MagicMock, patch from sqlmodel import select from app.backend_pre_start import init, logger def test_init_successful_connection() -> None: engine_mock = MagicMock() session_mock = MagicMock() session_mock.__enter__.return_value = session_mock select1 = select(1) with ( patch("app.backend_pre_start.Session", return_value=session_mock), patch("app.backend_pre_start.select", return_value=select1), patch.object(logger, "info"), patch.object(logger, "error"), patch.object(logger, "warn"), ): try: init(engine_mock) connection_successful = True except Exception: connection_successful = False assert connection_successful, ( "The database connection should be successful and not raise an exception." ) session_mock.exec.assert_called_once_with(select1) ================================================ FILE: backend/tests/scripts/test_test_pre_start.py ================================================ from unittest.mock import MagicMock, patch from sqlmodel import select from app.tests_pre_start import init, logger def test_init_successful_connection() -> None: engine_mock = MagicMock() session_mock = MagicMock() session_mock.__enter__.return_value = session_mock select1 = select(1) with ( patch("app.tests_pre_start.Session", return_value=session_mock), patch("app.tests_pre_start.select", return_value=select1), patch.object(logger, "info"), patch.object(logger, "error"), patch.object(logger, "warn"), ): try: init(engine_mock) connection_successful = True except Exception: connection_successful = False assert connection_successful, ( "The database connection should be successful and not raise an exception." ) session_mock.exec.assert_called_once_with(select1) ================================================ FILE: backend/tests/utils/__init__.py ================================================ ================================================ FILE: backend/tests/utils/item.py ================================================ from sqlmodel import Session from app import crud from app.models import Item, ItemCreate from tests.utils.user import create_random_user from tests.utils.utils import random_lower_string def create_random_item(db: Session) -> Item: user = create_random_user(db) owner_id = user.id assert owner_id is not None title = random_lower_string() description = random_lower_string() item_in = ItemCreate(title=title, description=description) return crud.create_item(session=db, item_in=item_in, owner_id=owner_id) ================================================ FILE: backend/tests/utils/user.py ================================================ from fastapi.testclient import TestClient from sqlmodel import Session from app import crud from app.core.config import settings from app.models import User, UserCreate, UserUpdate from tests.utils.utils import random_email, random_lower_string def user_authentication_headers( *, client: TestClient, email: str, password: str ) -> dict[str, str]: data = {"username": email, "password": password} r = client.post(f"{settings.API_V1_STR}/login/access-token", data=data) response = r.json() auth_token = response["access_token"] headers = {"Authorization": f"Bearer {auth_token}"} return headers def create_random_user(db: Session) -> User: email = random_email() password = random_lower_string() user_in = UserCreate(email=email, password=password) user = crud.create_user(session=db, user_create=user_in) return user def authentication_token_from_email( *, client: TestClient, email: str, db: Session ) -> dict[str, str]: """ Return a valid token for the user with given email. If the user doesn't exist it is created first. """ password = random_lower_string() user = crud.get_user_by_email(session=db, email=email) if not user: user_in_create = UserCreate(email=email, password=password) user = crud.create_user(session=db, user_create=user_in_create) else: user_in_update = UserUpdate(password=password) if not user.id: raise Exception("User id not set") user = crud.update_user(session=db, db_user=user, user_in=user_in_update) return user_authentication_headers(client=client, email=email, password=password) ================================================ FILE: backend/tests/utils/utils.py ================================================ import random import string from fastapi.testclient import TestClient from app.core.config import settings def random_lower_string() -> str: return "".join(random.choices(string.ascii_lowercase, k=32)) def random_email() -> str: return f"{random_lower_string()}@{random_lower_string()}.com" def get_superuser_token_headers(client: TestClient) -> dict[str, str]: login_data = { "username": settings.FIRST_SUPERUSER, "password": settings.FIRST_SUPERUSER_PASSWORD, } r = client.post(f"{settings.API_V1_STR}/login/access-token", data=login_data) tokens = r.json() a_token = tokens["access_token"] headers = {"Authorization": f"Bearer {a_token}"} return headers ================================================ FILE: compose.override.yml ================================================ services: # Local services are available on their ports, but also available on: # http://api.localhost.tiangolo.com: backend # http://dashboard.localhost.tiangolo.com: frontend # etc. To enable it, update .env, set: # DOMAIN=localhost.tiangolo.com proxy: image: traefik:3.6 volumes: - /var/run/docker.sock:/var/run/docker.sock ports: - "80:80" - "8090:8080" # Duplicate the command from compose.yml to add --api.insecure=true command: # Enable Docker in Traefik, so that it reads labels from Docker services - --providers.docker # Add a constraint to only use services with the label for this stack - --providers.docker.constraints=Label(`traefik.constraint-label`, `traefik-public`) # Do not expose all Docker services, only the ones explicitly exposed - --providers.docker.exposedbydefault=false # Create an entrypoint "http" listening on port 80 - --entrypoints.http.address=:80 # Create an entrypoint "https" listening on port 443 - --entrypoints.https.address=:443 # Enable the access log, with HTTP requests - --accesslog # Enable the Traefik log, for configurations and errors - --log # Enable debug logging for local development - --log.level=DEBUG # Enable the Dashboard and API - --api # Enable the Dashboard and API in insecure mode for local development - --api.insecure=true labels: # Enable Traefik for this service, to make it available in the public network - traefik.enable=true - traefik.constraint-label=traefik-public # Dummy https-redirect middleware that doesn't really redirect, only to # allow running it locally - traefik.http.middlewares.https-redirect.contenttype.autodetect=false networks: - traefik-public - default db: restart: "no" ports: - "5432:5432" adminer: restart: "no" ports: - "8080:8080" backend: restart: "no" ports: - "8000:8000" build: context: . dockerfile: backend/Dockerfile # command: sleep infinity # Infinite loop to keep container alive doing nothing command: - fastapi - run - --reload - "app/main.py" develop: watch: - path: ./backend action: sync target: /app/backend ignore: - ./backend/.venv - .venv - path: ./backend/pyproject.toml action: rebuild # TODO: remove once coverage is done locally volumes: - ./backend/htmlcov:/app/backend/htmlcov environment: SMTP_HOST: "mailcatcher" SMTP_PORT: "1025" SMTP_TLS: "false" EMAILS_FROM_EMAIL: "noreply@example.com" mailcatcher: image: schickling/mailcatcher ports: - "1080:1080" - "1025:1025" frontend: restart: "no" ports: - "5173:80" build: context: . dockerfile: frontend/Dockerfile args: - VITE_API_URL=http://localhost:8000 - NODE_ENV=development playwright: build: context: . dockerfile: frontend/Dockerfile.playwright args: - VITE_API_URL=http://backend:8000 - NODE_ENV=production ipc: host depends_on: - backend - mailcatcher env_file: - .env environment: - VITE_API_URL=http://backend:8000 - MAILCATCHER_HOST=http://mailcatcher:1080 # For the reports when run locally - PLAYWRIGHT_HTML_HOST=0.0.0.0 - CI=${CI} volumes: - ./frontend/blob-report:/app/frontend/blob-report - ./frontend/test-results:/app/frontend/test-results ports: - 9323:9323 networks: traefik-public: # For local dev, don't expect an external Traefik network external: false ================================================ FILE: compose.traefik.yml ================================================ services: traefik: image: traefik:3.6 ports: # Listen on port 80, default for HTTP, necessary to redirect to HTTPS - 80:80 # Listen on port 443, default for HTTPS - 443:443 restart: always labels: # Enable Traefik for this service, to make it available in the public network - traefik.enable=true # Use the traefik-public network (declared below) - traefik.docker.network=traefik-public # Define the port inside of the Docker service to use - traefik.http.services.traefik-dashboard.loadbalancer.server.port=8080 # Make Traefik use this domain (from an environment variable) in HTTP - traefik.http.routers.traefik-dashboard-http.entrypoints=http - traefik.http.routers.traefik-dashboard-http.rule=Host(`traefik.${DOMAIN?Variable not set}`) # traefik-https the actual router using HTTPS - traefik.http.routers.traefik-dashboard-https.entrypoints=https - traefik.http.routers.traefik-dashboard-https.rule=Host(`traefik.${DOMAIN?Variable not set}`) - traefik.http.routers.traefik-dashboard-https.tls=true # Use the "le" (Let's Encrypt) resolver created below - traefik.http.routers.traefik-dashboard-https.tls.certresolver=le # Use the special Traefik service api@internal with the web UI/Dashboard - traefik.http.routers.traefik-dashboard-https.service=api@internal # https-redirect middleware to redirect HTTP to HTTPS - traefik.http.middlewares.https-redirect.redirectscheme.scheme=https - traefik.http.middlewares.https-redirect.redirectscheme.permanent=true # traefik-http set up only to use the middleware to redirect to https - traefik.http.routers.traefik-dashboard-http.middlewares=https-redirect # admin-auth middleware with HTTP Basic auth # Using the environment variables USERNAME and HASHED_PASSWORD - traefik.http.middlewares.admin-auth.basicauth.users=${USERNAME?Variable not set}:${HASHED_PASSWORD?Variable not set} # Enable HTTP Basic auth, using the middleware created above - traefik.http.routers.traefik-dashboard-https.middlewares=admin-auth volumes: # Add Docker as a mounted volume, so that Traefik can read the labels of other services - /var/run/docker.sock:/var/run/docker.sock:ro # Mount the volume to store the certificates - traefik-public-certificates:/certificates command: # Enable Docker in Traefik, so that it reads labels from Docker services - --providers.docker # Do not expose all Docker services, only the ones explicitly exposed - --providers.docker.exposedbydefault=false # Create an entrypoint "http" listening on port 80 - --entrypoints.http.address=:80 # Create an entrypoint "https" listening on port 443 - --entrypoints.https.address=:443 # Create the certificate resolver "le" for Let's Encrypt, uses the environment variable EMAIL - --certificatesresolvers.le.acme.email=${EMAIL?Variable not set} # Store the Let's Encrypt certificates in the mounted volume - --certificatesresolvers.le.acme.storage=/certificates/acme.json # Use the TLS Challenge for Let's Encrypt - --certificatesresolvers.le.acme.tlschallenge=true # Enable the access log, with HTTP requests - --accesslog # Enable the Traefik log, for configurations and errors - --log # Enable the Dashboard and API - --api networks: # Use the public network created to be shared between Traefik and # any other service that needs to be publicly available with HTTPS - traefik-public volumes: # Create a volume to store the certificates, even if the container is recreated traefik-public-certificates: networks: # Use the previously created public network "traefik-public", shared with other # services that need to be publicly available via this Traefik traefik-public: external: true ================================================ FILE: compose.yml ================================================ services: db: image: postgres:18 restart: always healthcheck: test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER} -d ${POSTGRES_DB}"] interval: 10s retries: 5 start_period: 30s timeout: 10s volumes: - app-db-data:/var/lib/postgresql/data/pgdata env_file: - .env environment: - PGDATA=/var/lib/postgresql/data/pgdata - POSTGRES_PASSWORD=${POSTGRES_PASSWORD?Variable not set} - POSTGRES_USER=${POSTGRES_USER?Variable not set} - POSTGRES_DB=${POSTGRES_DB?Variable not set} adminer: image: adminer restart: always networks: - traefik-public - default depends_on: - db environment: - ADMINER_DESIGN=pepa-linha-dark labels: - traefik.enable=true - traefik.docker.network=traefik-public - traefik.constraint-label=traefik-public - traefik.http.routers.${STACK_NAME?Variable not set}-adminer-http.rule=Host(`adminer.${DOMAIN?Variable not set}`) - traefik.http.routers.${STACK_NAME?Variable not set}-adminer-http.entrypoints=http - traefik.http.routers.${STACK_NAME?Variable not set}-adminer-http.middlewares=https-redirect - traefik.http.routers.${STACK_NAME?Variable not set}-adminer-https.rule=Host(`adminer.${DOMAIN?Variable not set}`) - traefik.http.routers.${STACK_NAME?Variable not set}-adminer-https.entrypoints=https - traefik.http.routers.${STACK_NAME?Variable not set}-adminer-https.tls=true - traefik.http.routers.${STACK_NAME?Variable not set}-adminer-https.tls.certresolver=le - traefik.http.services.${STACK_NAME?Variable not set}-adminer.loadbalancer.server.port=8080 prestart: image: '${DOCKER_IMAGE_BACKEND?Variable not set}:${TAG-latest}' build: context: . dockerfile: backend/Dockerfile networks: - traefik-public - default depends_on: db: condition: service_healthy restart: true command: bash scripts/prestart.sh env_file: - .env environment: - DOMAIN=${DOMAIN} - FRONTEND_HOST=${FRONTEND_HOST?Variable not set} - ENVIRONMENT=${ENVIRONMENT} - BACKEND_CORS_ORIGINS=${BACKEND_CORS_ORIGINS} - SECRET_KEY=${SECRET_KEY?Variable not set} - FIRST_SUPERUSER=${FIRST_SUPERUSER?Variable not set} - FIRST_SUPERUSER_PASSWORD=${FIRST_SUPERUSER_PASSWORD?Variable not set} - SMTP_HOST=${SMTP_HOST} - SMTP_USER=${SMTP_USER} - SMTP_PASSWORD=${SMTP_PASSWORD} - EMAILS_FROM_EMAIL=${EMAILS_FROM_EMAIL} - POSTGRES_SERVER=db - POSTGRES_PORT=${POSTGRES_PORT} - POSTGRES_DB=${POSTGRES_DB} - POSTGRES_USER=${POSTGRES_USER?Variable not set} - POSTGRES_PASSWORD=${POSTGRES_PASSWORD?Variable not set} - SENTRY_DSN=${SENTRY_DSN} backend: image: '${DOCKER_IMAGE_BACKEND?Variable not set}:${TAG-latest}' restart: always networks: - traefik-public - default depends_on: db: condition: service_healthy restart: true prestart: condition: service_completed_successfully env_file: - .env environment: - DOMAIN=${DOMAIN} - FRONTEND_HOST=${FRONTEND_HOST?Variable not set} - ENVIRONMENT=${ENVIRONMENT} - BACKEND_CORS_ORIGINS=${BACKEND_CORS_ORIGINS} - SECRET_KEY=${SECRET_KEY?Variable not set} - FIRST_SUPERUSER=${FIRST_SUPERUSER?Variable not set} - FIRST_SUPERUSER_PASSWORD=${FIRST_SUPERUSER_PASSWORD?Variable not set} - SMTP_HOST=${SMTP_HOST} - SMTP_USER=${SMTP_USER} - SMTP_PASSWORD=${SMTP_PASSWORD} - EMAILS_FROM_EMAIL=${EMAILS_FROM_EMAIL} - POSTGRES_SERVER=db - POSTGRES_PORT=${POSTGRES_PORT} - POSTGRES_DB=${POSTGRES_DB} - POSTGRES_USER=${POSTGRES_USER?Variable not set} - POSTGRES_PASSWORD=${POSTGRES_PASSWORD?Variable not set} - SENTRY_DSN=${SENTRY_DSN} healthcheck: test: ["CMD", "curl", "-f", "http://localhost:8000/api/v1/utils/health-check/"] interval: 10s timeout: 5s retries: 5 build: context: . dockerfile: backend/Dockerfile labels: - traefik.enable=true - traefik.docker.network=traefik-public - traefik.constraint-label=traefik-public - traefik.http.services.${STACK_NAME?Variable not set}-backend.loadbalancer.server.port=8000 - traefik.http.routers.${STACK_NAME?Variable not set}-backend-http.rule=Host(`api.${DOMAIN?Variable not set}`) - traefik.http.routers.${STACK_NAME?Variable not set}-backend-http.entrypoints=http - traefik.http.routers.${STACK_NAME?Variable not set}-backend-https.rule=Host(`api.${DOMAIN?Variable not set}`) - traefik.http.routers.${STACK_NAME?Variable not set}-backend-https.entrypoints=https - traefik.http.routers.${STACK_NAME?Variable not set}-backend-https.tls=true - traefik.http.routers.${STACK_NAME?Variable not set}-backend-https.tls.certresolver=le # Enable redirection for HTTP and HTTPS - traefik.http.routers.${STACK_NAME?Variable not set}-backend-http.middlewares=https-redirect frontend: image: '${DOCKER_IMAGE_FRONTEND?Variable not set}:${TAG-latest}' restart: always networks: - traefik-public - default build: context: . dockerfile: frontend/Dockerfile args: - VITE_API_URL=https://api.${DOMAIN?Variable not set} - NODE_ENV=production labels: - traefik.enable=true - traefik.docker.network=traefik-public - traefik.constraint-label=traefik-public - traefik.http.services.${STACK_NAME?Variable not set}-frontend.loadbalancer.server.port=80 - traefik.http.routers.${STACK_NAME?Variable not set}-frontend-http.rule=Host(`dashboard.${DOMAIN?Variable not set}`) - traefik.http.routers.${STACK_NAME?Variable not set}-frontend-http.entrypoints=http - traefik.http.routers.${STACK_NAME?Variable not set}-frontend-https.rule=Host(`dashboard.${DOMAIN?Variable not set}`) - traefik.http.routers.${STACK_NAME?Variable not set}-frontend-https.entrypoints=https - traefik.http.routers.${STACK_NAME?Variable not set}-frontend-https.tls=true - traefik.http.routers.${STACK_NAME?Variable not set}-frontend-https.tls.certresolver=le # Enable redirection for HTTP and HTTPS - traefik.http.routers.${STACK_NAME?Variable not set}-frontend-http.middlewares=https-redirect volumes: app-db-data: networks: traefik-public: # Allow setting it to false for testing external: true ================================================ FILE: copier.yml ================================================ project_name: type: str help: The name of the project, shown to API users (in .env) default: FastAPI Project stack_name: type: str help: The name of the stack used for Docker Compose labels (no spaces) (in .env) default: fastapi-project secret_key: type: str help: | 'The secret key for the project, used for security, stored in .env, you can generate one with: python -c "import secrets; print(secrets.token_urlsafe(32))"' default: changethis first_superuser: type: str help: The email of the first superuser (in .env) default: admin@example.com first_superuser_password: type: str help: The password of the first superuser (in .env) default: changethis smtp_host: type: str help: The SMTP server host to send emails, you can set it later in .env default: "" smtp_user: type: str help: The SMTP server user to send emails, you can set it later in .env default: "" smtp_password: type: str help: The SMTP server password to send emails, you can set it later in .env default: "" emails_from_email: type: str help: The email account to send emails from, you can set it later in .env default: info@example.com postgres_password: type: str help: | 'The password for the PostgreSQL database, stored in .env, you can generate one with: python -c "import secrets; print(secrets.token_urlsafe(32))"' default: changethis sentry_dsn: type: str help: The DSN for Sentry, if you are using it, you can set it later in .env default: "" _exclude: # Global - .vscode - .mypy_cache # Python - __pycache__ - app.egg-info - "*.pyc" - .mypy_cache - .coverage - htmlcov - .cache - .venv # Frontend # Logs - logs - "*.log" - npm-debug.log* - yarn-debug.log* - yarn-error.log* - pnpm-debug.log* - lerna-debug.log* - node_modules - dist - dist-ssr - "*.local" # Editor directories and files - .idea - .DS_Store - "*.suo" - "*.ntvs*" - "*.njsproj" - "*.sln" - "*.sw?" _answers_file: .copier/.copier-answers.yml _tasks: - ["{{ _copier_python }}", .copier/update_dotenv.py] ================================================ FILE: deployment.md ================================================ # FastAPI Project - Deployment You can deploy the project using Docker Compose to a remote server. This project expects you to have a Traefik proxy handling communication to the outside world and HTTPS certificates. You can use CI/CD (continuous integration and continuous deployment) systems to deploy automatically, there are already configurations to do it with GitHub Actions. But you have to configure a couple things first. 🤓 ## Preparation * Have a remote server ready and available. * Configure the DNS records of your domain to point to the IP of the server you just created. * Configure a wildcard subdomain for your domain, so that you can have multiple subdomains for different services, e.g. `*.fastapi-project.example.com`. This will be useful for accessing different components, like `dashboard.fastapi-project.example.com`, `api.fastapi-project.example.com`, `traefik.fastapi-project.example.com`, `adminer.fastapi-project.example.com`, etc. And also for `staging`, like `dashboard.staging.fastapi-project.example.com`, `adminer.staging.fastapi-project.example.com`, etc. * Install and configure [Docker](https://docs.docker.com/engine/install/) on the remote server (Docker Engine, not Docker Desktop). ## Public Traefik We need a Traefik proxy to handle incoming connections and HTTPS certificates. You need to do these next steps only once. ### Traefik Docker Compose * Create a remote directory to store your Traefik Docker Compose file: ```bash mkdir -p /root/code/traefik-public/ ``` Copy the Traefik Docker Compose file to your server. You could do it by running the command `rsync` in your local terminal: ```bash rsync -a compose.traefik.yml root@your-server.example.com:/root/code/traefik-public/ ``` ### Traefik Public Network This Traefik will expect a Docker "public network" named `traefik-public` to communicate with your stack(s). This way, there will be a single public Traefik proxy that handles the communication (HTTP and HTTPS) with the outside world, and then behind that, you could have one or more stacks with different domains, even if they are on the same single server. To create a Docker "public network" named `traefik-public` run the following command in your remote server: ```bash docker network create traefik-public ``` ### Traefik Environment Variables The Traefik Docker Compose file expects some environment variables to be set in your terminal before starting it. You can do it by running the following commands in your remote server. * Create the username for HTTP Basic Auth, e.g.: ```bash export USERNAME=admin ``` * Create an environment variable with the password for HTTP Basic Auth, e.g.: ```bash export PASSWORD=changethis ``` * Use openssl to generate the "hashed" version of the password for HTTP Basic Auth and store it in an environment variable: ```bash export HASHED_PASSWORD=$(openssl passwd -apr1 $PASSWORD) ``` To verify that the hashed password is correct, you can print it: ```bash echo $HASHED_PASSWORD ``` * Create an environment variable with the domain name for your server, e.g.: ```bash export DOMAIN=fastapi-project.example.com ``` * Create an environment variable with the email for Let's Encrypt, e.g.: ```bash export EMAIL=admin@example.com ``` **Note**: you need to set a different email, an email `@example.com` won't work. ### Start the Traefik Docker Compose Go to the directory where you copied the Traefik Docker Compose file in your remote server: ```bash cd /root/code/traefik-public/ ``` Now with the environment variables set and the `compose.traefik.yml` in place, you can start the Traefik Docker Compose running the following command: ```bash docker compose -f compose.traefik.yml up -d ``` ## Deploy the FastAPI Project Now that you have Traefik in place you can deploy your FastAPI project with Docker Compose. **Note**: You might want to jump ahead to the section about Continuous Deployment with GitHub Actions. ## Copy the Code ```bash rsync -av --filter=":- .gitignore" ./ root@your-server.example.com:/root/code/app/ ``` Note: `--filter=":- .gitignore"` tells `rsync` to use the same rules as git, ignore files ignored by git, like the Python virtual environment. ## Environment Variables You need to set some environment variables first. ### Generate secret keys Some environment variables in the `.env` file have a default value of `changethis`. You have to change them with a secret key, to generate secret keys you can run the following command: ```bash python -c "import secrets; print(secrets.token_urlsafe(32))" ``` Copy the content and use that as password / secret key. And run that again to generate another secure key. ### Required Environment Variables Set the `ENVIRONMENT`, by default `local` (for development), but when deploying to a server you would put something like `staging` or `production`: ```bash export ENVIRONMENT=production ``` Set the `DOMAIN`, by default `localhost` (for development), but when deploying you would use your own domain, for example: ```bash export DOMAIN=fastapi-project.example.com ``` Set the `POSTGRES_PASSWORD` to something different than `changethis`: ```bash export POSTGRES_PASSWORD="changethis" ``` Set the `SECRET_KEY`, used to sign tokens: ```bash export SECRET_KEY="changethis" ``` Note: you can use the Python command above to generate a secure secret key. Set the `FIRST_SUPER_USER_PASSWORD` to something different than `changethis`: ```bash export FIRST_SUPERUSER_PASSWORD="changethis" ``` Set the `BACKEND_CORS_ORIGINS` to include your domain: ```bash export BACKEND_CORS_ORIGINS="https://dashboard.${DOMAIN?Variable not set},https://api.${DOMAIN?Variable not set}" ``` You can set several other environment variables: * `PROJECT_NAME`: The name of the project, used in the API for the docs and emails. * `STACK_NAME`: The name of the stack used for Docker Compose labels and project name, this should be different for `staging`, `production`, etc. You could use the same domain replacing dots with dashes, e.g. `fastapi-project-example-com` and `staging-fastapi-project-example-com`. * `BACKEND_CORS_ORIGINS`: A list of allowed CORS origins separated by commas. * `FIRST_SUPERUSER`: The email of the first superuser, this superuser will be the one that can create new users. * `SMTP_HOST`: The SMTP server host to send emails, this would come from your email provider (E.g. Mailgun, Sparkpost, Sendgrid, etc). * `SMTP_USER`: The SMTP server user to send emails. * `SMTP_PASSWORD`: The SMTP server password to send emails. * `EMAILS_FROM_EMAIL`: The email account to send emails from. * `POSTGRES_SERVER`: The hostname of the PostgreSQL server. You can leave the default of `db`, provided by the same Docker Compose. You normally wouldn't need to change this unless you are using a third-party provider. * `POSTGRES_PORT`: The port of the PostgreSQL server. You can leave the default. You normally wouldn't need to change this unless you are using a third-party provider. * `POSTGRES_USER`: The Postgres user, you can leave the default. * `POSTGRES_DB`: The database name to use for this application. You can leave the default of `app`. * `SENTRY_DSN`: The DSN for Sentry, if you are using it. ## GitHub Actions Environment Variables There are some environment variables only used by GitHub Actions that you can configure: * `LATEST_CHANGES`: Used by the GitHub Action [latest-changes](https://github.com/tiangolo/latest-changes) to automatically add release notes based on the PRs merged. It's a personal access token, read the docs for details. * `SMOKESHOW_AUTH_KEY`: Used to handle and publish the code coverage using [Smokeshow](https://github.com/samuelcolvin/smokeshow), follow their instructions to create a (free) Smokeshow key. ### Deploy with Docker Compose With the environment variables in place, you can deploy with Docker Compose: ```bash cd /root/code/app/ docker compose -f compose.yml build docker compose -f compose.yml up -d ``` For production you wouldn't want to have the overrides in `compose.override.yml`, that's why we explicitly specify `compose.yml` as the file to use. ## Continuous Deployment (CD) You can use GitHub Actions to deploy your project automatically. 😎 You can have multiple environment deployments. There are already two environments configured, `staging` and `production`. 🚀 ### Install GitHub Actions Runner * On your remote server, create a user for your GitHub Actions: ```bash sudo adduser github ``` * Add Docker permissions to the `github` user: ```bash sudo usermod -aG docker github ``` * Temporarily switch to the `github` user: ```bash sudo su - github ``` * Go to the `github` user's home directory: ```bash cd ``` * [Install a GitHub Action self-hosted runner following the official guide](https://docs.github.com/en/actions/hosting-your-own-runners/managing-self-hosted-runners/adding-self-hosted-runners#adding-a-self-hosted-runner-to-a-repository). * When asked about labels, add a label for the environment, e.g. `production`. You can also add labels later. After installing, the guide would tell you to run a command to start the runner. Nevertheless, it would stop once you terminate that process or if your local connection to your server is lost. To make sure it runs on startup and continues running, you can install it as a service. To do that, exit the `github` user and go back to the `root` user: ```bash exit ``` After you do it, you will be on the previous user again. And you will be on the previous directory, belonging to that user. Before being able to go the `github` user directory, you need to become the `root` user (you might already be): ```bash sudo su ``` * As the `root` user, go to the `actions-runner` directory inside of the `github` user's home directory: ```bash cd /home/github/actions-runner ``` * Install the self-hosted runner as a service with the user `github`: ```bash ./svc.sh install github ``` * Start the service: ```bash ./svc.sh start ``` * Check the status of the service: ```bash ./svc.sh status ``` You can read more about it in the official guide: [Configuring the self-hosted runner application as a service](https://docs.github.com/en/actions/hosting-your-own-runners/managing-self-hosted-runners/configuring-the-self-hosted-runner-application-as-a-service). ### Set Secrets On your repository, configure secrets for the environment variables you need, the same ones described above, including `SECRET_KEY`, etc. Follow the [official GitHub guide for setting repository secrets](https://docs.github.com/en/actions/security-guides/using-secrets-in-github-actions#creating-secrets-for-a-repository). The current Github Actions workflows expect these secrets: * `DOMAIN_PRODUCTION` * `DOMAIN_STAGING` * `STACK_NAME_PRODUCTION` * `STACK_NAME_STAGING` * `EMAILS_FROM_EMAIL` * `FIRST_SUPERUSER` * `FIRST_SUPERUSER_PASSWORD` * `POSTGRES_PASSWORD` * `SECRET_KEY` * `LATEST_CHANGES` * `SMOKESHOW_AUTH_KEY` ## GitHub Action Deployment Workflows There are GitHub Action workflows in the `.github/workflows` directory already configured for deploying to the environments (GitHub Actions runners with the labels): * `staging`: after pushing (or merging) to the branch `master`. * `production`: after publishing a release. If you need to add extra environments you could use those as a starting point. ## URLs Replace `fastapi-project.example.com` with your domain. ### Main Traefik Dashboard Traefik UI: `https://traefik.fastapi-project.example.com` ### Production Frontend: `https://dashboard.fastapi-project.example.com` Backend API docs: `https://api.fastapi-project.example.com/docs` Backend API base URL: `https://api.fastapi-project.example.com` Adminer: `https://adminer.fastapi-project.example.com` ### Staging Frontend: `https://dashboard.staging.fastapi-project.example.com` Backend API docs: `https://api.staging.fastapi-project.example.com/docs` Backend API base URL: `https://api.staging.fastapi-project.example.com` Adminer: `https://adminer.staging.fastapi-project.example.com` ================================================ FILE: development.md ================================================ # FastAPI Project - Development ## Docker Compose * Start the local stack with Docker Compose: ```bash docker compose watch ``` * Now you can open your browser and interact with these URLs: Frontend, built with Docker, with routes handled based on the path: Backend, JSON based web API based on OpenAPI: Automatic interactive documentation with Swagger UI (from the OpenAPI backend): Adminer, database web administration: Traefik UI, to see how the routes are being handled by the proxy: **Note**: The first time you start your stack, it might take a minute for it to be ready. While the backend waits for the database to be ready and configures everything. You can check the logs to monitor it. To check the logs, run (in another terminal): ```bash docker compose logs ``` To check the logs of a specific service, add the name of the service, e.g.: ```bash docker compose logs backend ``` ## Mailcatcher Mailcatcher is a simple SMTP server that catches all emails sent by the backend during local development. Instead of sending real emails, they are captured and displayed in a web interface. This is useful for: * Testing email functionality during development * Verifying email content and formatting * Debugging email-related functionality without sending real emails The backend is automatically configured to use Mailcatcher when running with Docker Compose locally (SMTP on port 1025). All captured emails can be viewed at . ## Local Development The Docker Compose files are configured so that each of the services is available in a different port in `localhost`. For the backend and frontend, they use the same port that would be used by their local development server, so, the backend is at `http://localhost:8000` and the frontend at `http://localhost:5173`. This way, you could turn off a Docker Compose service and start its local development service, and everything would keep working, because it all uses the same ports. For example, you can stop that `frontend` service in the Docker Compose, in another terminal, run: ```bash docker compose stop frontend ``` And then start the local frontend development server: ```bash bun run dev ``` Or you could stop the `backend` Docker Compose service: ```bash docker compose stop backend ``` And then you can run the local development server for the backend: ```bash cd backend fastapi dev app/main.py ``` ## Docker Compose in `localhost.tiangolo.com` When you start the Docker Compose stack, it uses `localhost` by default, with different ports for each service (backend, frontend, adminer, etc). When you deploy it to production (or staging), it will deploy each service in a different subdomain, like `api.example.com` for the backend and `dashboard.example.com` for the frontend. In the guide about [deployment](deployment.md) you can read about Traefik, the configured proxy. That's the component in charge of transmitting traffic to each service based on the subdomain. If you want to test that it's all working locally, you can edit the local `.env` file, and change: ```dotenv DOMAIN=localhost.tiangolo.com ``` That will be used by the Docker Compose files to configure the base domain for the services. Traefik will use this to transmit traffic at `api.localhost.tiangolo.com` to the backend, and traffic at `dashboard.localhost.tiangolo.com` to the frontend. The domain `localhost.tiangolo.com` is a special domain that is configured (with all its subdomains) to point to `127.0.0.1`. This way you can use that for your local development. After you update it, run again: ```bash docker compose watch ``` When deploying, for example in production, the main Traefik is configured outside of the Docker Compose files. For local development, there's an included Traefik in `compose.override.yml`, just to let you test that the domains work as expected, for example with `api.localhost.tiangolo.com` and `dashboard.localhost.tiangolo.com`. ## Docker Compose files and env vars There is a main `compose.yml` file with all the configurations that apply to the whole stack, it is used automatically by `docker compose`. And there's also a `compose.override.yml` with overrides for development, for example to mount the source code as a volume. It is used automatically by `docker compose` to apply overrides on top of `compose.yml`. These Docker Compose files use the `.env` file containing configurations to be injected as environment variables in the containers. They also use some additional configurations taken from environment variables set in the scripts before calling the `docker compose` command. After changing variables, make sure you restart the stack: ```bash docker compose watch ``` ## The .env file The `.env` file is the one that contains all your configurations, generated keys and passwords, etc. Depending on your workflow, you could want to exclude it from Git, for example if your project is public. In that case, you would have to make sure to set up a way for your CI tools to obtain it while building or deploying your project. One way to do it could be to add each environment variable to your CI/CD system, and updating the `compose.yml` file to read that specific env var instead of reading the `.env` file. ## Pre-commits and code linting we are using a tool called [prek](https://prek.j178.dev/) (modern alternative to [Pre-commit](https://pre-commit.com/)) for code linting and formatting. When you install it, it runs right before making a commit in git. This way it ensures that the code is consistent and formatted even before it is committed. You can find a file `.pre-commit-config.yaml` with configurations at the root of the project. #### Install prek to run automatically `prek` is already part of the dependencies of the project. After having the `prek` tool installed and available, you need to "install" it in the local repository, so that it runs automatically before each commit. Using `uv`, you could do it with (make sure you are inside `backend` folder): ```bash ❯ uv run prek install -f prek installed at `../.git/hooks/pre-commit` ``` The `-f` flag forces the installation, in case there was already a `pre-commit` hook previously installed. Now whenever you try to commit, e.g. with: ```bash git commit ``` ...prek will run and check and format the code you are about to commit, and will ask you to add that code (stage it) with git again before committing. Then you can `git add` the modified/fixed files again and now you can commit. #### Running prek hooks manually you can also run `prek` manually on all the files, you can do it using `uv` with: ```bash ❯ uv run prek run --all-files check for added large files..............................................Passed check toml...............................................................Passed check yaml...............................................................Passed fix end of files.........................................................Passed trim trailing whitespace.................................................Passed ruff.....................................................................Passed ruff-format..............................................................Passed biome check..............................................................Passed ``` ## URLs The production or staging URLs would use these same paths, but with your own domain. ### Development URLs Development URLs, for local development. Frontend: Backend: Automatic Interactive Docs (Swagger UI): Automatic Alternative Docs (ReDoc): Adminer: Traefik UI: MailCatcher: ### Development URLs with `localhost.tiangolo.com` Configured Development URLs, for local development. Frontend: Backend: Automatic Interactive Docs (Swagger UI): Automatic Alternative Docs (ReDoc): Adminer: Traefik UI: MailCatcher: ================================================ FILE: frontend/.dockerignore ================================================ node_modules dist ================================================ FILE: frontend/.gitignore ================================================ # Logs logs *.log npm-debug.log* yarn-debug.log* yarn-error.log* pnpm-debug.log* lerna-debug.log* node_modules dist dist-ssr *.local openapi.json # Editor directories and files .vscode/* !.vscode/extensions.json .idea .DS_Store *.suo *.ntvs* *.njsproj *.sln *.sw? /test-results/ /playwright-report/ /blob-report/ /playwright/.cache/ /playwright/.auth/ ================================================ FILE: frontend/Dockerfile ================================================ # Stage 0, "build-stage", based on Bun, to build and compile the frontend FROM oven/bun:1 AS build-stage WORKDIR /app COPY package.json bun.lock /app/ COPY frontend/package.json /app/frontend/ WORKDIR /app/frontend RUN bun install COPY ./frontend /app/frontend ARG VITE_API_URL RUN bun run build # Stage 1, based on Nginx, to have only the compiled app, ready for production with Nginx FROM nginx:1 COPY --from=build-stage /app/frontend/dist/ /usr/share/nginx/html COPY ./frontend/nginx.conf /etc/nginx/conf.d/default.conf COPY ./frontend/nginx-backend-not-found.conf /etc/nginx/extra-conf.d/backend-not-found.conf ================================================ FILE: frontend/Dockerfile.playwright ================================================ FROM mcr.microsoft.com/playwright:v1.58.2-noble WORKDIR /app RUN apt-get update && apt-get install -y unzip \ && rm -rf /var/lib/apt/lists/* RUN curl -fsSL https://bun.sh/install | bash ENV PATH="/root/.bun/bin:$PATH" COPY package.json bun.lock /app/ COPY frontend/package.json /app/frontend/ WORKDIR /app/frontend RUN bun install COPY ./frontend /app/frontend ARG VITE_API_URL ================================================ FILE: frontend/README.md ================================================ # FastAPI Project - Frontend The frontend is built with [Vite](https://vitejs.dev/), [React](https://reactjs.org/), [TypeScript](https://www.typescriptlang.org/), [TanStack Query](https://tanstack.com/query), [TanStack Router](https://tanstack.com/router) and [Tailwind CSS](https://tailwindcss.com/). ## Requirements - [Bun](https://bun.sh/) (recommended) or [Node.js](https://nodejs.org/) ## Quick Start ```bash bun install bun run dev ``` * Then open your browser at http://localhost:5173/. Notice that this live server is not running inside Docker, it's for local development, and that is the recommended workflow. Once you are happy with your frontend, you can build the frontend Docker image and start it, to test it in a production-like environment. But building the image at every change will not be as productive as running the local development server with live reload. Check the file `package.json` to see other available options. ### Removing the frontend If you are developing an API-only app and want to remove the frontend, you can do it easily: * Remove the `./frontend` directory. * In the `compose.yml` file, remove the whole service / section `frontend`. * In the `compose.override.yml` file, remove the whole service / section `frontend` and `playwright`. Done, you have a frontend-less (api-only) app. 🤓 --- If you want, you can also remove the `FRONTEND` environment variables from: * `.env` * `./scripts/*.sh` But it would be only to clean them up, leaving them won't really have any effect either way. ## Generate Client ### Automatically * Activate the backend virtual environment. * From the top level project directory, run the script: ```bash bash ./scripts/generate-client.sh ``` * Commit the changes. ### Manually * Start the Docker Compose stack. * Download the OpenAPI JSON file from `http://localhost/api/v1/openapi.json` and copy it to a new file `openapi.json` at the root of the `frontend` directory. * To generate the frontend client, run: ```bash bun run generate-client ``` * Commit the changes. Notice that everytime the backend changes (changing the OpenAPI schema), you should follow these steps again to update the frontend client. ## Using a Remote API If you want to use a remote API, you can set the environment variable `VITE_API_URL` to the URL of the remote API. For example, you can set it in the `frontend/.env` file: ```env VITE_API_URL=https://api.my-domain.example.com ``` Then, when you run the frontend, it will use that URL as the base URL for the API. ## Code Structure The frontend code is structured as follows: * `frontend/src` - The main frontend code. * `frontend/src/assets` - Static assets. * `frontend/src/client` - The generated OpenAPI client. * `frontend/src/components` - The different components of the frontend. * `frontend/src/hooks` - Custom hooks. * `frontend/src/routes` - The different routes of the frontend which include the pages. ## End-to-End Testing with Playwright The frontend includes initial end-to-end tests using Playwright. To run the tests, you need to have the Docker Compose stack running. Start the stack with the following command: ```bash docker compose up -d --wait backend ``` Then, you can run the tests with the following command: ```bash bunx playwright test ``` You can also run your tests in UI mode to see the browser and interact with it running: ```bash bunx playwright test --ui ``` To stop and remove the Docker Compose stack and clean the data created in tests, use the following command: ```bash docker compose down -v ``` To update the tests, navigate to the tests directory and modify the existing test files or add new ones as needed. For more information on writing and running Playwright tests, refer to the official [Playwright documentation](https://playwright.dev/docs/intro). ================================================ FILE: frontend/biome.json ================================================ { "$schema": "https://biomejs.dev/schemas/2.3.14/schema.json", "assist": { "actions": { "source": { "organizeImports": "on" } } }, "files": { "includes": [ "**", "!**/dist/**/*", "!**/node_modules/**/*", "!**/src/routeTree.gen.ts", "!**/src/client/**/*", "!**/src/components/ui/**/*", "!**/playwright-report", "!**/playwright.config.ts" ] }, "linter": { "enabled": true, "rules": { "recommended": true, "suspicious": { "noExplicitAny": "off", "noArrayIndexKey": "off" }, "style": { "noNonNullAssertion": "off", "noParameterAssign": "error", "useSelfClosingElements": "error", "noUselessElse": "error" } } }, "formatter": { "indentStyle": "space" }, "javascript": { "formatter": { "quoteStyle": "double", "semicolons": "asNeeded" } }, "css": { "parser": { "tailwindDirectives": true } } } ================================================ FILE: frontend/components.json ================================================ { "$schema": "https://ui.shadcn.com/schema.json", "style": "new-york", "rsc": false, "tsx": true, "tailwind": { "config": "", "css": "src/index.css", "baseColor": "neutral", "cssVariables": true, "prefix": "" }, "iconLibrary": "lucide", "aliases": { "components": "@/components", "utils": "@/lib/utils", "ui": "@/components/ui", "lib": "@/lib", "hooks": "@/hooks" }, "registries": {} } ================================================ FILE: frontend/index.html ================================================ Full Stack FastAPI Project
================================================ FILE: frontend/nginx-backend-not-found.conf ================================================ location /api { return 404; } location /docs { return 404; } location /redoc { return 404; } ================================================ FILE: frontend/nginx.conf ================================================ server { listen 80; location / { root /usr/share/nginx/html; index index.html index.htm; try_files $uri /index.html =404; } include /etc/nginx/extra-conf.d/*.conf; } ================================================ FILE: frontend/openapi-ts.config.ts ================================================ import { defineConfig } from "@hey-api/openapi-ts" export default defineConfig({ input: "./openapi.json", output: "./src/client", plugins: [ "legacy/axios", { name: "@hey-api/sdk", // NOTE: this doesn't allow tree-shaking asClass: true, operationId: true, classNameBuilder: "{{name}}Service", methodNameBuilder: (operation) => { // @ts-expect-error let name: string = operation.name // @ts-expect-error const service: string = operation.service if (service && name.toLowerCase().startsWith(service.toLowerCase())) { name = name.slice(service.length) } return name.charAt(0).toLowerCase() + name.slice(1) }, }, { name: "@hey-api/schemas", type: "json", }, ], }) ================================================ FILE: frontend/package.json ================================================ { "name": "frontend", "private": true, "version": "0.0.0", "type": "module", "scripts": { "dev": "vite", "build": "tsc -p tsconfig.build.json && vite build", "lint": "biome check --write --unsafe --no-errors-on-unmatched --files-ignore-unknown=true ./", "preview": "vite preview", "generate-client": "openapi-ts", "test": "bunx playwright test", "test:ui": "bunx playwright test --ui" }, "dependencies": { "@hookform/resolvers": "^5.2.2", "@radix-ui/react-avatar": "^1.1.11", "@radix-ui/react-checkbox": "^1.3.3", "@radix-ui/react-dialog": "^1.1.15", "@radix-ui/react-dropdown-menu": "^2.1.16", "@radix-ui/react-label": "^2.1.8", "@radix-ui/react-radio-group": "^1.3.8", "@radix-ui/react-scroll-area": "^1.2.10", "@radix-ui/react-select": "^2.2.6", "@radix-ui/react-separator": "^1.1.8", "@radix-ui/react-slot": "^1.2.4", "@radix-ui/react-tabs": "^1.1.13", "@radix-ui/react-tooltip": "^1.2.8", "@tailwindcss/vite": "^4.1.18", "@tanstack/react-query": "^5.90.21", "@tanstack/react-query-devtools": "^5.91.1", "@tanstack/react-router": "^1.163.3", "@tanstack/react-router-devtools": "^1.163.3", "@tanstack/react-table": "^8.21.3", "axios": "1.13.5", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "form-data": "4.0.5", "lucide-react": "^0.563.0", "next-themes": "^0.4.6", "react": "^19.1.1", "react-dom": "^19.2.3", "react-error-boundary": "^6.0.0", "react-hook-form": "^7.68.0", "react-icons": "^5.5.0", "sonner": "^2.0.7", "tailwind-merge": "^3.4.0", "tailwindcss": "^4.2.1", "zod": "^4.3.6" }, "devDependencies": { "@biomejs/biome": "^2.3.14", "@hey-api/openapi-ts": "0.73.0", "@playwright/test": "1.58.2", "@tanstack/router-devtools": "^1.166.7", "@tanstack/router-plugin": "^1.140.0", "@types/node": "^25.5.0", "@types/react": "^19.2.7", "@types/react-dom": "^19.2.3", "@vitejs/plugin-react-swc": "^4.2.3", "dotenv": "^17.3.1", "tw-animate-css": "^1.4.0", "typescript": "^5.9.3", "vite": "^7.3.0" } } ================================================ FILE: frontend/playwright.config.ts ================================================ import { defineConfig, devices } from '@playwright/test'; import 'dotenv/config' /** * Read environment variables from file. * https://github.com/motdotla/dotenv */ /** * See https://playwright.dev/docs/test-configuration. */ export default defineConfig({ testDir: './tests', /* Run tests in files in parallel */ fullyParallel: true, /* Fail the build on CI if you accidentally left test.only in the source code. */ forbidOnly: !!process.env.CI, /* Retry on CI only */ retries: process.env.CI ? 2 : 0, /* Opt out of parallel tests on CI. */ workers: process.env.CI ? 1 : undefined, /* Reporter to use. See https://playwright.dev/docs/test-reporters */ reporter: process.env.CI ? 'blob' : 'html', /* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */ use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL: 'http://localhost:5173', /* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */ trace: 'on-first-retry', }, /* Configure projects for major browsers */ projects: [ { name: 'setup', testMatch: /.*\.setup\.ts/ }, { name: 'chromium', use: { ...devices['Desktop Chrome'], storageState: 'playwright/.auth/user.json', }, dependencies: ['setup'], }, // { // name: 'firefox', // use: { // ...devices['Desktop Firefox'], // storageState: 'playwright/.auth/user.json', // }, // dependencies: ['setup'], // }, // { // name: 'webkit', // use: { // ...devices['Desktop Safari'], // storageState: 'playwright/.auth/user.json', // }, // dependencies: ['setup'], // }, /* Test against mobile viewports. */ // { // name: 'Mobile Chrome', // use: { ...devices['Pixel 5'] }, // }, // { // name: 'Mobile Safari', // use: { ...devices['iPhone 12'] }, // }, /* Test against branded browsers. */ // { // name: 'Microsoft Edge', // use: { ...devices['Desktop Edge'], channel: 'msedge' }, // }, // { // name: 'Google Chrome', // use: { ...devices['Desktop Chrome'], channel: 'chrome' }, // }, ], /* Run your local dev server before starting the tests */ webServer: { command: 'bun run dev', url: 'http://localhost:5173', reuseExistingServer: !process.env.CI, }, }); ================================================ FILE: frontend/src/client/core/ApiError.ts ================================================ import type { ApiRequestOptions } from './ApiRequestOptions'; import type { ApiResult } from './ApiResult'; export class ApiError extends Error { public readonly url: string; public readonly status: number; public readonly statusText: string; public readonly body: unknown; public readonly request: ApiRequestOptions; constructor(request: ApiRequestOptions, response: ApiResult, message: string) { super(message); this.name = 'ApiError'; this.url = response.url; this.status = response.status; this.statusText = response.statusText; this.body = response.body; this.request = request; } } ================================================ FILE: frontend/src/client/core/ApiRequestOptions.ts ================================================ export type ApiRequestOptions = { readonly body?: any; readonly cookies?: Record; readonly errors?: Record; readonly formData?: Record | any[] | Blob | File; readonly headers?: Record; readonly mediaType?: string; readonly method: | 'DELETE' | 'GET' | 'HEAD' | 'OPTIONS' | 'PATCH' | 'POST' | 'PUT'; readonly path?: Record; readonly query?: Record; readonly responseHeader?: string; readonly responseTransformer?: (data: unknown) => Promise; readonly url: string; }; ================================================ FILE: frontend/src/client/core/ApiResult.ts ================================================ export type ApiResult = { readonly body: TData; readonly ok: boolean; readonly status: number; readonly statusText: string; readonly url: string; }; ================================================ FILE: frontend/src/client/core/CancelablePromise.ts ================================================ export class CancelError extends Error { constructor(message: string) { super(message); this.name = 'CancelError'; } public get isCancelled(): boolean { return true; } } export interface OnCancel { readonly isResolved: boolean; readonly isRejected: boolean; readonly isCancelled: boolean; (cancelHandler: () => void): void; } export class CancelablePromise implements Promise { private _isResolved: boolean; private _isRejected: boolean; private _isCancelled: boolean; readonly cancelHandlers: (() => void)[]; readonly promise: Promise; private _resolve?: (value: T | PromiseLike) => void; private _reject?: (reason?: unknown) => void; constructor( executor: ( resolve: (value: T | PromiseLike) => void, reject: (reason?: unknown) => void, onCancel: OnCancel ) => void ) { this._isResolved = false; this._isRejected = false; this._isCancelled = false; this.cancelHandlers = []; this.promise = new Promise((resolve, reject) => { this._resolve = resolve; this._reject = reject; const onResolve = (value: T | PromiseLike): void => { if (this._isResolved || this._isRejected || this._isCancelled) { return; } this._isResolved = true; if (this._resolve) this._resolve(value); }; const onReject = (reason?: unknown): void => { if (this._isResolved || this._isRejected || this._isCancelled) { return; } this._isRejected = true; if (this._reject) this._reject(reason); }; const onCancel = (cancelHandler: () => void): void => { if (this._isResolved || this._isRejected || this._isCancelled) { return; } this.cancelHandlers.push(cancelHandler); }; Object.defineProperty(onCancel, 'isResolved', { get: (): boolean => this._isResolved, }); Object.defineProperty(onCancel, 'isRejected', { get: (): boolean => this._isRejected, }); Object.defineProperty(onCancel, 'isCancelled', { get: (): boolean => this._isCancelled, }); return executor(onResolve, onReject, onCancel as OnCancel); }); } get [Symbol.toStringTag]() { return "Cancellable Promise"; } public then( onFulfilled?: ((value: T) => TResult1 | PromiseLike) | null, onRejected?: ((reason: unknown) => TResult2 | PromiseLike) | null ): Promise { return this.promise.then(onFulfilled, onRejected); } public catch( onRejected?: ((reason: unknown) => TResult | PromiseLike) | null ): Promise { return this.promise.catch(onRejected); } public finally(onFinally?: (() => void) | null): Promise { return this.promise.finally(onFinally); } public cancel(): void { if (this._isResolved || this._isRejected || this._isCancelled) { return; } this._isCancelled = true; if (this.cancelHandlers.length) { try { for (const cancelHandler of this.cancelHandlers) { cancelHandler(); } } catch (error) { console.warn('Cancellation threw an error', error); return; } } this.cancelHandlers.length = 0; if (this._reject) this._reject(new CancelError('Request aborted')); } public get isCancelled(): boolean { return this._isCancelled; } } ================================================ FILE: frontend/src/client/core/OpenAPI.ts ================================================ import type { AxiosRequestConfig, AxiosResponse } from 'axios'; import type { ApiRequestOptions } from './ApiRequestOptions'; type Headers = Record; type Middleware = (value: T) => T | Promise; type Resolver = (options: ApiRequestOptions) => Promise; export class Interceptors { _fns: Middleware[]; constructor() { this._fns = []; } eject(fn: Middleware): void { const index = this._fns.indexOf(fn); if (index !== -1) { this._fns = [...this._fns.slice(0, index), ...this._fns.slice(index + 1)]; } } use(fn: Middleware): void { this._fns = [...this._fns, fn]; } } export type OpenAPIConfig = { BASE: string; CREDENTIALS: 'include' | 'omit' | 'same-origin'; ENCODE_PATH?: ((path: string) => string) | undefined; HEADERS?: Headers | Resolver | undefined; PASSWORD?: string | Resolver | undefined; TOKEN?: string | Resolver | undefined; USERNAME?: string | Resolver | undefined; VERSION: string; WITH_CREDENTIALS: boolean; interceptors: { request: Interceptors; response: Interceptors; }; }; export const OpenAPI: OpenAPIConfig = { BASE: '', CREDENTIALS: 'include', ENCODE_PATH: undefined, HEADERS: undefined, PASSWORD: undefined, TOKEN: undefined, USERNAME: undefined, VERSION: '0.1.0', WITH_CREDENTIALS: false, interceptors: { request: new Interceptors(), response: new Interceptors(), }, }; ================================================ FILE: frontend/src/client/core/request.ts ================================================ import axios from 'axios'; import type { AxiosError, AxiosRequestConfig, AxiosResponse, AxiosInstance } from 'axios'; import { ApiError } from './ApiError'; import type { ApiRequestOptions } from './ApiRequestOptions'; import type { ApiResult } from './ApiResult'; import { CancelablePromise } from './CancelablePromise'; import type { OnCancel } from './CancelablePromise'; import type { OpenAPIConfig } from './OpenAPI'; export const isString = (value: unknown): value is string => { return typeof value === 'string'; }; export const isStringWithValue = (value: unknown): value is string => { return isString(value) && value !== ''; }; export const isBlob = (value: any): value is Blob => { return value instanceof Blob; }; export const isFormData = (value: unknown): value is FormData => { return value instanceof FormData; }; export const isSuccess = (status: number): boolean => { return status >= 200 && status < 300; }; export const base64 = (str: string): string => { try { return btoa(str); } catch (err) { // @ts-ignore return Buffer.from(str).toString('base64'); } }; export const getQueryString = (params: Record): string => { const qs: string[] = []; const append = (key: string, value: unknown) => { qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`); }; const encodePair = (key: string, value: unknown) => { if (value === undefined || value === null) { return; } if (value instanceof Date) { append(key, value.toISOString()); } else if (Array.isArray(value)) { value.forEach(v => encodePair(key, v)); } else if (typeof value === 'object') { Object.entries(value).forEach(([k, v]) => encodePair(`${key}[${k}]`, v)); } else { append(key, value); } }; Object.entries(params).forEach(([key, value]) => encodePair(key, value)); return qs.length ? `?${qs.join('&')}` : ''; }; const getUrl = (config: OpenAPIConfig, options: ApiRequestOptions): string => { const encoder = config.ENCODE_PATH || encodeURI; const path = options.url .replace('{api-version}', config.VERSION) .replace(/{(.*?)}/g, (substring: string, group: string) => { if (options.path?.hasOwnProperty(group)) { return encoder(String(options.path[group])); } return substring; }); const url = config.BASE + path; return options.query ? url + getQueryString(options.query) : url; }; export const getFormData = (options: ApiRequestOptions): FormData | undefined => { if (options.formData) { const formData = new FormData(); const process = (key: string, value: unknown) => { if (isString(value) || isBlob(value)) { formData.append(key, value); } else { formData.append(key, JSON.stringify(value)); } }; Object.entries(options.formData) .filter(([, value]) => value !== undefined && value !== null) .forEach(([key, value]) => { if (Array.isArray(value)) { value.forEach(v => process(key, v)); } else { process(key, value); } }); return formData; } return undefined; }; type Resolver = (options: ApiRequestOptions) => Promise; export const resolve = async (options: ApiRequestOptions, resolver?: T | Resolver): Promise => { if (typeof resolver === 'function') { return (resolver as Resolver)(options); } return resolver; }; export const getHeaders = async (config: OpenAPIConfig, options: ApiRequestOptions): Promise> => { const [token, username, password, additionalHeaders] = await Promise.all([ // @ts-ignore resolve(options, config.TOKEN), // @ts-ignore resolve(options, config.USERNAME), // @ts-ignore resolve(options, config.PASSWORD), // @ts-ignore resolve(options, config.HEADERS), ]); const headers = Object.entries({ Accept: 'application/json', ...additionalHeaders, ...options.headers, }) .filter(([, value]) => value !== undefined && value !== null) .reduce((headers, [key, value]) => ({ ...headers, [key]: String(value), }), {} as Record); if (isStringWithValue(token)) { headers['Authorization'] = `Bearer ${token}`; } if (isStringWithValue(username) && isStringWithValue(password)) { const credentials = base64(`${username}:${password}`); headers['Authorization'] = `Basic ${credentials}`; } if (options.body !== undefined) { if (options.mediaType) { headers['Content-Type'] = options.mediaType; } else if (isBlob(options.body)) { headers['Content-Type'] = options.body.type || 'application/octet-stream'; } else if (isString(options.body)) { headers['Content-Type'] = 'text/plain'; } else if (!isFormData(options.body)) { headers['Content-Type'] = 'application/json'; } } else if (options.formData !== undefined) { if (options.mediaType) { headers['Content-Type'] = options.mediaType; } } return headers; }; export const getRequestBody = (options: ApiRequestOptions): unknown => { if (options.body) { return options.body; } return undefined; }; export const sendRequest = async ( config: OpenAPIConfig, options: ApiRequestOptions, url: string, body: unknown, formData: FormData | undefined, headers: Record, onCancel: OnCancel, axiosClient: AxiosInstance ): Promise> => { const controller = new AbortController(); let requestConfig: AxiosRequestConfig = { data: body ?? formData, headers, method: options.method, signal: controller.signal, url, withCredentials: config.WITH_CREDENTIALS, }; onCancel(() => controller.abort()); for (const fn of config.interceptors.request._fns) { requestConfig = await fn(requestConfig); } try { return await axiosClient.request(requestConfig); } catch (error) { const axiosError = error as AxiosError; if (axiosError.response) { return axiosError.response; } throw error; } }; export const getResponseHeader = (response: AxiosResponse, responseHeader?: string): string | undefined => { if (responseHeader) { const content = response.headers[responseHeader]; if (isString(content)) { return content; } } return undefined; }; export const getResponseBody = (response: AxiosResponse): unknown => { if (response.status !== 204) { return response.data; } return undefined; }; export const catchErrorCodes = (options: ApiRequestOptions, result: ApiResult): void => { const errors: Record = { 400: 'Bad Request', 401: 'Unauthorized', 402: 'Payment Required', 403: 'Forbidden', 404: 'Not Found', 405: 'Method Not Allowed', 406: 'Not Acceptable', 407: 'Proxy Authentication Required', 408: 'Request Timeout', 409: 'Conflict', 410: 'Gone', 411: 'Length Required', 412: 'Precondition Failed', 413: 'Payload Too Large', 414: 'URI Too Long', 415: 'Unsupported Media Type', 416: 'Range Not Satisfiable', 417: 'Expectation Failed', 418: 'Im a teapot', 421: 'Misdirected Request', 422: 'Unprocessable Content', 423: 'Locked', 424: 'Failed Dependency', 425: 'Too Early', 426: 'Upgrade Required', 428: 'Precondition Required', 429: 'Too Many Requests', 431: 'Request Header Fields Too Large', 451: 'Unavailable For Legal Reasons', 500: 'Internal Server Error', 501: 'Not Implemented', 502: 'Bad Gateway', 503: 'Service Unavailable', 504: 'Gateway Timeout', 505: 'HTTP Version Not Supported', 506: 'Variant Also Negotiates', 507: 'Insufficient Storage', 508: 'Loop Detected', 510: 'Not Extended', 511: 'Network Authentication Required', ...options.errors, } const error = errors[result.status]; if (error) { throw new ApiError(options, result, error); } if (!result.ok) { const errorStatus = result.status ?? 'unknown'; const errorStatusText = result.statusText ?? 'unknown'; const errorBody = (() => { try { return JSON.stringify(result.body, null, 2); } catch (e) { return undefined; } })(); throw new ApiError(options, result, `Generic Error: status: ${errorStatus}; status text: ${errorStatusText}; body: ${errorBody}` ); } }; /** * Request method * @param config The OpenAPI configuration object * @param options The request options from the service * @param axiosClient The axios client instance to use * @returns CancelablePromise * @throws ApiError */ export const request = (config: OpenAPIConfig, options: ApiRequestOptions, axiosClient: AxiosInstance = axios): CancelablePromise => { return new CancelablePromise(async (resolve, reject, onCancel) => { try { const url = getUrl(config, options); const formData = getFormData(options); const body = getRequestBody(options); const headers = await getHeaders(config, options); if (!onCancel.isCancelled) { let response = await sendRequest(config, options, url, body, formData, headers, onCancel, axiosClient); for (const fn of config.interceptors.response._fns) { response = await fn(response); } const responseBody = getResponseBody(response); const responseHeader = getResponseHeader(response, options.responseHeader); let transformedBody = responseBody; if (options.responseTransformer && isSuccess(response.status)) { transformedBody = await options.responseTransformer(responseBody) } const result: ApiResult = { url, ok: isSuccess(response.status), status: response.status, statusText: response.statusText, body: responseHeader ?? transformedBody, }; catchErrorCodes(options, result); resolve(result.body); } } catch (error) { reject(error); } }); }; ================================================ FILE: frontend/src/client/index.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export { ApiError } from './core/ApiError'; export { CancelablePromise, CancelError } from './core/CancelablePromise'; export { OpenAPI, type OpenAPIConfig } from './core/OpenAPI'; export * from './sdk.gen'; export * from './types.gen'; ================================================ FILE: frontend/src/client/schemas.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export const Body_login_login_access_tokenSchema = { properties: { grant_type: { anyOf: [ { type: 'string', pattern: '^password$' }, { type: 'null' } ], title: 'Grant Type' }, username: { type: 'string', title: 'Username' }, password: { type: 'string', format: 'password', title: 'Password' }, scope: { type: 'string', title: 'Scope', default: '' }, client_id: { anyOf: [ { type: 'string' }, { type: 'null' } ], title: 'Client Id' }, client_secret: { anyOf: [ { type: 'string' }, { type: 'null' } ], format: 'password', title: 'Client Secret' } }, type: 'object', required: ['username', 'password'], title: 'Body_login-login_access_token' } as const; export const HTTPValidationErrorSchema = { properties: { detail: { items: { '$ref': '#/components/schemas/ValidationError' }, type: 'array', title: 'Detail' } }, type: 'object', title: 'HTTPValidationError' } as const; export const ItemCreateSchema = { properties: { title: { type: 'string', maxLength: 255, minLength: 1, title: 'Title' }, description: { anyOf: [ { type: 'string', maxLength: 255 }, { type: 'null' } ], title: 'Description' } }, type: 'object', required: ['title'], title: 'ItemCreate' } as const; export const ItemPublicSchema = { properties: { title: { type: 'string', maxLength: 255, minLength: 1, title: 'Title' }, description: { anyOf: [ { type: 'string', maxLength: 255 }, { type: 'null' } ], title: 'Description' }, id: { type: 'string', format: 'uuid', title: 'Id' }, owner_id: { type: 'string', format: 'uuid', title: 'Owner Id' }, created_at: { anyOf: [ { type: 'string', format: 'date-time' }, { type: 'null' } ], title: 'Created At' } }, type: 'object', required: ['title', 'id', 'owner_id'], title: 'ItemPublic' } as const; export const ItemUpdateSchema = { properties: { title: { anyOf: [ { type: 'string', maxLength: 255, minLength: 1 }, { type: 'null' } ], title: 'Title' }, description: { anyOf: [ { type: 'string', maxLength: 255 }, { type: 'null' } ], title: 'Description' } }, type: 'object', title: 'ItemUpdate' } as const; export const ItemsPublicSchema = { properties: { data: { items: { '$ref': '#/components/schemas/ItemPublic' }, type: 'array', title: 'Data' }, count: { type: 'integer', title: 'Count' } }, type: 'object', required: ['data', 'count'], title: 'ItemsPublic' } as const; export const MessageSchema = { properties: { message: { type: 'string', title: 'Message' } }, type: 'object', required: ['message'], title: 'Message' } as const; export const NewPasswordSchema = { properties: { token: { type: 'string', title: 'Token' }, new_password: { type: 'string', maxLength: 128, minLength: 8, title: 'New Password' } }, type: 'object', required: ['token', 'new_password'], title: 'NewPassword' } as const; export const PrivateUserCreateSchema = { properties: { email: { type: 'string', title: 'Email' }, password: { type: 'string', title: 'Password' }, full_name: { type: 'string', title: 'Full Name' }, is_verified: { type: 'boolean', title: 'Is Verified', default: false } }, type: 'object', required: ['email', 'password', 'full_name'], title: 'PrivateUserCreate' } as const; export const TokenSchema = { properties: { access_token: { type: 'string', title: 'Access Token' }, token_type: { type: 'string', title: 'Token Type', default: 'bearer' } }, type: 'object', required: ['access_token'], title: 'Token' } as const; export const UpdatePasswordSchema = { properties: { current_password: { type: 'string', maxLength: 128, minLength: 8, title: 'Current Password' }, new_password: { type: 'string', maxLength: 128, minLength: 8, title: 'New Password' } }, type: 'object', required: ['current_password', 'new_password'], title: 'UpdatePassword' } as const; export const UserCreateSchema = { properties: { email: { type: 'string', maxLength: 255, format: 'email', title: 'Email' }, is_active: { type: 'boolean', title: 'Is Active', default: true }, is_superuser: { type: 'boolean', title: 'Is Superuser', default: false }, full_name: { anyOf: [ { type: 'string', maxLength: 255 }, { type: 'null' } ], title: 'Full Name' }, password: { type: 'string', maxLength: 128, minLength: 8, title: 'Password' } }, type: 'object', required: ['email', 'password'], title: 'UserCreate' } as const; export const UserPublicSchema = { properties: { email: { type: 'string', maxLength: 255, format: 'email', title: 'Email' }, is_active: { type: 'boolean', title: 'Is Active', default: true }, is_superuser: { type: 'boolean', title: 'Is Superuser', default: false }, full_name: { anyOf: [ { type: 'string', maxLength: 255 }, { type: 'null' } ], title: 'Full Name' }, id: { type: 'string', format: 'uuid', title: 'Id' }, created_at: { anyOf: [ { type: 'string', format: 'date-time' }, { type: 'null' } ], title: 'Created At' } }, type: 'object', required: ['email', 'id'], title: 'UserPublic' } as const; export const UserRegisterSchema = { properties: { email: { type: 'string', maxLength: 255, format: 'email', title: 'Email' }, password: { type: 'string', maxLength: 128, minLength: 8, title: 'Password' }, full_name: { anyOf: [ { type: 'string', maxLength: 255 }, { type: 'null' } ], title: 'Full Name' } }, type: 'object', required: ['email', 'password'], title: 'UserRegister' } as const; export const UserUpdateSchema = { properties: { email: { anyOf: [ { type: 'string', maxLength: 255, format: 'email' }, { type: 'null' } ], title: 'Email' }, is_active: { type: 'boolean', title: 'Is Active', default: true }, is_superuser: { type: 'boolean', title: 'Is Superuser', default: false }, full_name: { anyOf: [ { type: 'string', maxLength: 255 }, { type: 'null' } ], title: 'Full Name' }, password: { anyOf: [ { type: 'string', maxLength: 128, minLength: 8 }, { type: 'null' } ], title: 'Password' } }, type: 'object', title: 'UserUpdate' } as const; export const UserUpdateMeSchema = { properties: { full_name: { anyOf: [ { type: 'string', maxLength: 255 }, { type: 'null' } ], title: 'Full Name' }, email: { anyOf: [ { type: 'string', maxLength: 255, format: 'email' }, { type: 'null' } ], title: 'Email' } }, type: 'object', title: 'UserUpdateMe' } as const; export const UsersPublicSchema = { properties: { data: { items: { '$ref': '#/components/schemas/UserPublic' }, type: 'array', title: 'Data' }, count: { type: 'integer', title: 'Count' } }, type: 'object', required: ['data', 'count'], title: 'UsersPublic' } as const; export const ValidationErrorSchema = { properties: { loc: { items: { anyOf: [ { type: 'string' }, { type: 'integer' } ] }, type: 'array', title: 'Location' }, msg: { type: 'string', title: 'Message' }, type: { type: 'string', title: 'Error Type' }, input: { title: 'Input' }, ctx: { type: 'object', title: 'Context' } }, type: 'object', required: ['loc', 'msg', 'type'], title: 'ValidationError' } as const; ================================================ FILE: frontend/src/client/sdk.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts import type { CancelablePromise } from './core/CancelablePromise'; import { OpenAPI } from './core/OpenAPI'; import { request as __request } from './core/request'; import type { ItemsReadItemsData, ItemsReadItemsResponse, ItemsCreateItemData, ItemsCreateItemResponse, ItemsReadItemData, ItemsReadItemResponse, ItemsUpdateItemData, ItemsUpdateItemResponse, ItemsDeleteItemData, ItemsDeleteItemResponse, LoginLoginAccessTokenData, LoginLoginAccessTokenResponse, LoginTestTokenResponse, LoginRecoverPasswordData, LoginRecoverPasswordResponse, LoginResetPasswordData, LoginResetPasswordResponse, LoginRecoverPasswordHtmlContentData, LoginRecoverPasswordHtmlContentResponse, PrivateCreateUserData, PrivateCreateUserResponse, UsersReadUsersData, UsersReadUsersResponse, UsersCreateUserData, UsersCreateUserResponse, UsersReadUserMeResponse, UsersDeleteUserMeResponse, UsersUpdateUserMeData, UsersUpdateUserMeResponse, UsersUpdatePasswordMeData, UsersUpdatePasswordMeResponse, UsersRegisterUserData, UsersRegisterUserResponse, UsersReadUserByIdData, UsersReadUserByIdResponse, UsersUpdateUserData, UsersUpdateUserResponse, UsersDeleteUserData, UsersDeleteUserResponse, UtilsTestEmailData, UtilsTestEmailResponse, UtilsHealthCheckResponse } from './types.gen'; export class ItemsService { /** * Read Items * Retrieve items. * @param data The data for the request. * @param data.skip * @param data.limit * @returns ItemsPublic Successful Response * @throws ApiError */ public static readItems(data: ItemsReadItemsData = {}): CancelablePromise { return __request(OpenAPI, { method: 'GET', url: '/api/v1/items/', query: { skip: data.skip, limit: data.limit }, errors: { 422: 'Validation Error' } }); } /** * Create Item * Create new item. * @param data The data for the request. * @param data.requestBody * @returns ItemPublic Successful Response * @throws ApiError */ public static createItem(data: ItemsCreateItemData): CancelablePromise { return __request(OpenAPI, { method: 'POST', url: '/api/v1/items/', body: data.requestBody, mediaType: 'application/json', errors: { 422: 'Validation Error' } }); } /** * Read Item * Get item by ID. * @param data The data for the request. * @param data.id * @returns ItemPublic Successful Response * @throws ApiError */ public static readItem(data: ItemsReadItemData): CancelablePromise { return __request(OpenAPI, { method: 'GET', url: '/api/v1/items/{id}', path: { id: data.id }, errors: { 422: 'Validation Error' } }); } /** * Update Item * Update an item. * @param data The data for the request. * @param data.id * @param data.requestBody * @returns ItemPublic Successful Response * @throws ApiError */ public static updateItem(data: ItemsUpdateItemData): CancelablePromise { return __request(OpenAPI, { method: 'PUT', url: '/api/v1/items/{id}', path: { id: data.id }, body: data.requestBody, mediaType: 'application/json', errors: { 422: 'Validation Error' } }); } /** * Delete Item * Delete an item. * @param data The data for the request. * @param data.id * @returns Message Successful Response * @throws ApiError */ public static deleteItem(data: ItemsDeleteItemData): CancelablePromise { return __request(OpenAPI, { method: 'DELETE', url: '/api/v1/items/{id}', path: { id: data.id }, errors: { 422: 'Validation Error' } }); } } export class LoginService { /** * Login Access Token * OAuth2 compatible token login, get an access token for future requests * @param data The data for the request. * @param data.formData * @returns Token Successful Response * @throws ApiError */ public static loginAccessToken(data: LoginLoginAccessTokenData): CancelablePromise { return __request(OpenAPI, { method: 'POST', url: '/api/v1/login/access-token', formData: data.formData, mediaType: 'application/x-www-form-urlencoded', errors: { 422: 'Validation Error' } }); } /** * Test Token * Test access token * @returns UserPublic Successful Response * @throws ApiError */ public static testToken(): CancelablePromise { return __request(OpenAPI, { method: 'POST', url: '/api/v1/login/test-token' }); } /** * Recover Password * Password Recovery * @param data The data for the request. * @param data.email * @returns Message Successful Response * @throws ApiError */ public static recoverPassword(data: LoginRecoverPasswordData): CancelablePromise { return __request(OpenAPI, { method: 'POST', url: '/api/v1/password-recovery/{email}', path: { email: data.email }, errors: { 422: 'Validation Error' } }); } /** * Reset Password * Reset password * @param data The data for the request. * @param data.requestBody * @returns Message Successful Response * @throws ApiError */ public static resetPassword(data: LoginResetPasswordData): CancelablePromise { return __request(OpenAPI, { method: 'POST', url: '/api/v1/reset-password/', body: data.requestBody, mediaType: 'application/json', errors: { 422: 'Validation Error' } }); } /** * Recover Password Html Content * HTML Content for Password Recovery * @param data The data for the request. * @param data.email * @returns string Successful Response * @throws ApiError */ public static recoverPasswordHtmlContent(data: LoginRecoverPasswordHtmlContentData): CancelablePromise { return __request(OpenAPI, { method: 'POST', url: '/api/v1/password-recovery-html-content/{email}', path: { email: data.email }, errors: { 422: 'Validation Error' } }); } } export class PrivateService { /** * Create User * Create a new user. * @param data The data for the request. * @param data.requestBody * @returns UserPublic Successful Response * @throws ApiError */ public static createUser(data: PrivateCreateUserData): CancelablePromise { return __request(OpenAPI, { method: 'POST', url: '/api/v1/private/users/', body: data.requestBody, mediaType: 'application/json', errors: { 422: 'Validation Error' } }); } } export class UsersService { /** * Read Users * Retrieve users. * @param data The data for the request. * @param data.skip * @param data.limit * @returns UsersPublic Successful Response * @throws ApiError */ public static readUsers(data: UsersReadUsersData = {}): CancelablePromise { return __request(OpenAPI, { method: 'GET', url: '/api/v1/users/', query: { skip: data.skip, limit: data.limit }, errors: { 422: 'Validation Error' } }); } /** * Create User * Create new user. * @param data The data for the request. * @param data.requestBody * @returns UserPublic Successful Response * @throws ApiError */ public static createUser(data: UsersCreateUserData): CancelablePromise { return __request(OpenAPI, { method: 'POST', url: '/api/v1/users/', body: data.requestBody, mediaType: 'application/json', errors: { 422: 'Validation Error' } }); } /** * Read User Me * Get current user. * @returns UserPublic Successful Response * @throws ApiError */ public static readUserMe(): CancelablePromise { return __request(OpenAPI, { method: 'GET', url: '/api/v1/users/me' }); } /** * Delete User Me * Delete own user. * @returns Message Successful Response * @throws ApiError */ public static deleteUserMe(): CancelablePromise { return __request(OpenAPI, { method: 'DELETE', url: '/api/v1/users/me' }); } /** * Update User Me * Update own user. * @param data The data for the request. * @param data.requestBody * @returns UserPublic Successful Response * @throws ApiError */ public static updateUserMe(data: UsersUpdateUserMeData): CancelablePromise { return __request(OpenAPI, { method: 'PATCH', url: '/api/v1/users/me', body: data.requestBody, mediaType: 'application/json', errors: { 422: 'Validation Error' } }); } /** * Update Password Me * Update own password. * @param data The data for the request. * @param data.requestBody * @returns Message Successful Response * @throws ApiError */ public static updatePasswordMe(data: UsersUpdatePasswordMeData): CancelablePromise { return __request(OpenAPI, { method: 'PATCH', url: '/api/v1/users/me/password', body: data.requestBody, mediaType: 'application/json', errors: { 422: 'Validation Error' } }); } /** * Register User * Create new user without the need to be logged in. * @param data The data for the request. * @param data.requestBody * @returns UserPublic Successful Response * @throws ApiError */ public static registerUser(data: UsersRegisterUserData): CancelablePromise { return __request(OpenAPI, { method: 'POST', url: '/api/v1/users/signup', body: data.requestBody, mediaType: 'application/json', errors: { 422: 'Validation Error' } }); } /** * Read User By Id * Get a specific user by id. * @param data The data for the request. * @param data.userId * @returns UserPublic Successful Response * @throws ApiError */ public static readUserById(data: UsersReadUserByIdData): CancelablePromise { return __request(OpenAPI, { method: 'GET', url: '/api/v1/users/{user_id}', path: { user_id: data.userId }, errors: { 422: 'Validation Error' } }); } /** * Update User * Update a user. * @param data The data for the request. * @param data.userId * @param data.requestBody * @returns UserPublic Successful Response * @throws ApiError */ public static updateUser(data: UsersUpdateUserData): CancelablePromise { return __request(OpenAPI, { method: 'PATCH', url: '/api/v1/users/{user_id}', path: { user_id: data.userId }, body: data.requestBody, mediaType: 'application/json', errors: { 422: 'Validation Error' } }); } /** * Delete User * Delete a user. * @param data The data for the request. * @param data.userId * @returns Message Successful Response * @throws ApiError */ public static deleteUser(data: UsersDeleteUserData): CancelablePromise { return __request(OpenAPI, { method: 'DELETE', url: '/api/v1/users/{user_id}', path: { user_id: data.userId }, errors: { 422: 'Validation Error' } }); } } export class UtilsService { /** * Test Email * Test emails. * @param data The data for the request. * @param data.emailTo * @returns Message Successful Response * @throws ApiError */ public static testEmail(data: UtilsTestEmailData): CancelablePromise { return __request(OpenAPI, { method: 'POST', url: '/api/v1/utils/test-email/', query: { email_to: data.emailTo }, errors: { 422: 'Validation Error' } }); } /** * Health Check * @returns boolean Successful Response * @throws ApiError */ public static healthCheck(): CancelablePromise { return __request(OpenAPI, { method: 'GET', url: '/api/v1/utils/health-check/' }); } } ================================================ FILE: frontend/src/client/types.gen.ts ================================================ // This file is auto-generated by @hey-api/openapi-ts export type Body_login_login_access_token = { grant_type?: (string | null); username: string; password: string; scope?: string; client_id?: (string | null); client_secret?: (string | null); }; export type HTTPValidationError = { detail?: Array; }; export type ItemCreate = { title: string; description?: (string | null); }; export type ItemPublic = { title: string; description?: (string | null); id: string; owner_id: string; created_at?: (string | null); }; export type ItemsPublic = { data: Array; count: number; }; export type ItemUpdate = { title?: (string | null); description?: (string | null); }; export type Message = { message: string; }; export type NewPassword = { token: string; new_password: string; }; export type PrivateUserCreate = { email: string; password: string; full_name: string; is_verified?: boolean; }; export type Token = { access_token: string; token_type?: string; }; export type UpdatePassword = { current_password: string; new_password: string; }; export type UserCreate = { email: string; is_active?: boolean; is_superuser?: boolean; full_name?: (string | null); password: string; }; export type UserPublic = { email: string; is_active?: boolean; is_superuser?: boolean; full_name?: (string | null); id: string; created_at?: (string | null); }; export type UserRegister = { email: string; password: string; full_name?: (string | null); }; export type UsersPublic = { data: Array; count: number; }; export type UserUpdate = { email?: (string | null); is_active?: boolean; is_superuser?: boolean; full_name?: (string | null); password?: (string | null); }; export type UserUpdateMe = { full_name?: (string | null); email?: (string | null); }; export type ValidationError = { loc: Array<(string | number)>; msg: string; type: string; input?: unknown; ctx?: { [key: string]: unknown; }; }; export type ItemsReadItemsData = { limit?: number; skip?: number; }; export type ItemsReadItemsResponse = (ItemsPublic); export type ItemsCreateItemData = { requestBody: ItemCreate; }; export type ItemsCreateItemResponse = (ItemPublic); export type ItemsReadItemData = { id: string; }; export type ItemsReadItemResponse = (ItemPublic); export type ItemsUpdateItemData = { id: string; requestBody: ItemUpdate; }; export type ItemsUpdateItemResponse = (ItemPublic); export type ItemsDeleteItemData = { id: string; }; export type ItemsDeleteItemResponse = (Message); export type LoginLoginAccessTokenData = { formData: Body_login_login_access_token; }; export type LoginLoginAccessTokenResponse = (Token); export type LoginTestTokenResponse = (UserPublic); export type LoginRecoverPasswordData = { email: string; }; export type LoginRecoverPasswordResponse = (Message); export type LoginResetPasswordData = { requestBody: NewPassword; }; export type LoginResetPasswordResponse = (Message); export type LoginRecoverPasswordHtmlContentData = { email: string; }; export type LoginRecoverPasswordHtmlContentResponse = (string); export type PrivateCreateUserData = { requestBody: PrivateUserCreate; }; export type PrivateCreateUserResponse = (UserPublic); export type UsersReadUsersData = { limit?: number; skip?: number; }; export type UsersReadUsersResponse = (UsersPublic); export type UsersCreateUserData = { requestBody: UserCreate; }; export type UsersCreateUserResponse = (UserPublic); export type UsersReadUserMeResponse = (UserPublic); export type UsersDeleteUserMeResponse = (Message); export type UsersUpdateUserMeData = { requestBody: UserUpdateMe; }; export type UsersUpdateUserMeResponse = (UserPublic); export type UsersUpdatePasswordMeData = { requestBody: UpdatePassword; }; export type UsersUpdatePasswordMeResponse = (Message); export type UsersRegisterUserData = { requestBody: UserRegister; }; export type UsersRegisterUserResponse = (UserPublic); export type UsersReadUserByIdData = { userId: string; }; export type UsersReadUserByIdResponse = (UserPublic); export type UsersUpdateUserData = { requestBody: UserUpdate; userId: string; }; export type UsersUpdateUserResponse = (UserPublic); export type UsersDeleteUserData = { userId: string; }; export type UsersDeleteUserResponse = (Message); export type UtilsTestEmailData = { emailTo: string; }; export type UtilsTestEmailResponse = (Message); export type UtilsHealthCheckResponse = (boolean); ================================================ FILE: frontend/src/components/Admin/AddUser.tsx ================================================ import { zodResolver } from "@hookform/resolvers/zod" import { useMutation, useQueryClient } from "@tanstack/react-query" import { Plus } from "lucide-react" import { useState } from "react" import { useForm } from "react-hook-form" import { z } from "zod" import { type UserCreate, UsersService } from "@/client" import { Button } from "@/components/ui/button" import { Checkbox } from "@/components/ui/checkbox" import { Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger, } from "@/components/ui/dialog" import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage, } from "@/components/ui/form" import { Input } from "@/components/ui/input" import { LoadingButton } from "@/components/ui/loading-button" import useCustomToast from "@/hooks/useCustomToast" import { handleError } from "@/utils" const formSchema = z .object({ email: z.email({ message: "Invalid email address" }), full_name: z.string().optional(), password: z .string() .min(1, { message: "Password is required" }) .min(8, { message: "Password must be at least 8 characters" }), confirm_password: z .string() .min(1, { message: "Please confirm your password" }), is_superuser: z.boolean(), is_active: z.boolean(), }) .refine((data) => data.password === data.confirm_password, { message: "The passwords don't match", path: ["confirm_password"], }) type FormData = z.infer const AddUser = () => { const [isOpen, setIsOpen] = useState(false) const queryClient = useQueryClient() const { showSuccessToast, showErrorToast } = useCustomToast() const form = useForm({ resolver: zodResolver(formSchema), mode: "onBlur", criteriaMode: "all", defaultValues: { email: "", full_name: "", password: "", confirm_password: "", is_superuser: false, is_active: false, }, }) const mutation = useMutation({ mutationFn: (data: UserCreate) => UsersService.createUser({ requestBody: data }), onSuccess: () => { showSuccessToast("User created successfully") form.reset() setIsOpen(false) }, onError: handleError.bind(showErrorToast), onSettled: () => { queryClient.invalidateQueries({ queryKey: ["users"] }) }, }) const onSubmit = (data: FormData) => { mutation.mutate(data) } return ( Add User Fill in the form below to add a new user to the system.
( Email * )} /> ( Full Name )} /> ( Set Password * )} /> ( Confirm Password{" "} * )} /> ( Is superuser? )} /> ( Is active? )} />
Save
) } export default AddUser ================================================ FILE: frontend/src/components/Admin/DeleteUser.tsx ================================================ import { useMutation, useQueryClient } from "@tanstack/react-query" import { Trash2 } from "lucide-react" import { useState } from "react" import { useForm } from "react-hook-form" import { UsersService } from "@/client" import { Button } from "@/components/ui/button" import { Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "@/components/ui/dialog" import { DropdownMenuItem } from "@/components/ui/dropdown-menu" import { LoadingButton } from "@/components/ui/loading-button" import useCustomToast from "@/hooks/useCustomToast" import { handleError } from "@/utils" interface DeleteUserProps { id: string onSuccess: () => void } const DeleteUser = ({ id, onSuccess }: DeleteUserProps) => { const [isOpen, setIsOpen] = useState(false) const queryClient = useQueryClient() const { showSuccessToast, showErrorToast } = useCustomToast() const { handleSubmit } = useForm() const deleteUser = async (id: string) => { await UsersService.deleteUser({ userId: id }) } const mutation = useMutation({ mutationFn: deleteUser, onSuccess: () => { showSuccessToast("The user was deleted successfully") setIsOpen(false) onSuccess() }, onError: handleError.bind(showErrorToast), onSettled: () => { queryClient.invalidateQueries() }, }) const onSubmit = async () => { mutation.mutate(id) } return ( e.preventDefault()} onClick={() => setIsOpen(true)} > Delete User
Delete User All items associated with this user will also be{" "} permanently deleted. Are you sure? You will not be able to undo this action. Delete
) } export default DeleteUser ================================================ FILE: frontend/src/components/Admin/EditUser.tsx ================================================ import { zodResolver } from "@hookform/resolvers/zod" import { useMutation, useQueryClient } from "@tanstack/react-query" import { Pencil } from "lucide-react" import { useState } from "react" import { useForm } from "react-hook-form" import { z } from "zod" import { type UserPublic, UsersService } from "@/client" import { Button } from "@/components/ui/button" import { Checkbox } from "@/components/ui/checkbox" import { Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "@/components/ui/dialog" import { DropdownMenuItem } from "@/components/ui/dropdown-menu" import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage, } from "@/components/ui/form" import { Input } from "@/components/ui/input" import { LoadingButton } from "@/components/ui/loading-button" import useCustomToast from "@/hooks/useCustomToast" import { handleError } from "@/utils" const formSchema = z .object({ email: z.email({ message: "Invalid email address" }), full_name: z.string().optional(), password: z .string() .min(8, { message: "Password must be at least 8 characters" }) .optional() .or(z.literal("")), confirm_password: z.string().optional(), is_superuser: z.boolean().optional(), is_active: z.boolean().optional(), }) .refine((data) => !data.password || data.password === data.confirm_password, { message: "The passwords don't match", path: ["confirm_password"], }) type FormData = z.infer interface EditUserProps { user: UserPublic onSuccess: () => void } const EditUser = ({ user, onSuccess }: EditUserProps) => { const [isOpen, setIsOpen] = useState(false) const queryClient = useQueryClient() const { showSuccessToast, showErrorToast } = useCustomToast() const form = useForm({ resolver: zodResolver(formSchema), mode: "onBlur", criteriaMode: "all", defaultValues: { email: user.email, full_name: user.full_name ?? undefined, is_superuser: user.is_superuser, is_active: user.is_active, }, }) const mutation = useMutation({ mutationFn: (data: FormData) => UsersService.updateUser({ userId: user.id, requestBody: data }), onSuccess: () => { showSuccessToast("User updated successfully") setIsOpen(false) onSuccess() }, onError: handleError.bind(showErrorToast), onSettled: () => { queryClient.invalidateQueries({ queryKey: ["users"] }) }, }) const onSubmit = (data: FormData) => { // exclude confirm_password from submission data and remove password if empty const { confirm_password: _, ...submitData } = data if (!submitData.password) { delete submitData.password } mutation.mutate(submitData) } return ( e.preventDefault()} onClick={() => setIsOpen(true)} > Edit User
Edit User Update the user details below.
( Email * )} /> ( Full Name )} /> ( Set Password )} /> ( Confirm Password )} /> ( Is superuser? )} /> ( Is active? )} />
Save
) } export default EditUser ================================================ FILE: frontend/src/components/Admin/UserActionsMenu.tsx ================================================ import { EllipsisVertical } from "lucide-react" import { useState } from "react" import type { UserPublic } from "@/client" import { Button } from "@/components/ui/button" import { DropdownMenu, DropdownMenuContent, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu" import useAuth from "@/hooks/useAuth" import DeleteUser from "./DeleteUser" import EditUser from "./EditUser" interface UserActionsMenuProps { user: UserPublic } export const UserActionsMenu = ({ user }: UserActionsMenuProps) => { const [open, setOpen] = useState(false) const { user: currentUser } = useAuth() if (user.id === currentUser?.id) { return null } return ( setOpen(false)} /> setOpen(false)} /> ) } ================================================ FILE: frontend/src/components/Admin/columns.tsx ================================================ import type { ColumnDef } from "@tanstack/react-table" import type { UserPublic } from "@/client" import { Badge } from "@/components/ui/badge" import { cn } from "@/lib/utils" import { UserActionsMenu } from "./UserActionsMenu" export type UserTableData = UserPublic & { isCurrentUser: boolean } export const columns: ColumnDef[] = [ { accessorKey: "full_name", header: "Full Name", cell: ({ row }) => { const fullName = row.original.full_name return (
{fullName || "N/A"} {row.original.isCurrentUser && ( You )}
) }, }, { accessorKey: "email", header: "Email", cell: ({ row }) => ( {row.original.email} ), }, { accessorKey: "is_superuser", header: "Role", cell: ({ row }) => ( {row.original.is_superuser ? "Superuser" : "User"} ), }, { accessorKey: "is_active", header: "Status", cell: ({ row }) => (
{row.original.is_active ? "Active" : "Inactive"}
), }, { id: "actions", header: () => Actions, cell: ({ row }) => (
), }, ] ================================================ FILE: frontend/src/components/Common/Appearance.tsx ================================================ import { Monitor, Moon, Sun } from "lucide-react" import { type Theme, useTheme } from "@/components/theme-provider" import { Button } from "@/components/ui/button" import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu" import { SidebarMenuButton, SidebarMenuItem, useSidebar, } from "@/components/ui/sidebar" type LucideIcon = React.FC> const ICON_MAP: Record = { system: Monitor, light: Sun, dark: Moon, } export const SidebarAppearance = () => { const { isMobile } = useSidebar() const { setTheme, theme } = useTheme() const Icon = ICON_MAP[theme] return ( Appearance Toggle theme setTheme("light")} > Light setTheme("dark")} > Dark setTheme("system")}> System ) } export const Appearance = () => { const { setTheme } = useTheme() return (
setTheme("light")} > Light setTheme("dark")} > Dark setTheme("system")}> System
) } ================================================ FILE: frontend/src/components/Common/AuthLayout.tsx ================================================ import { Appearance } from "@/components/Common/Appearance" import { Logo } from "@/components/Common/Logo" import { Footer } from "./Footer" interface AuthLayoutProps { children: React.ReactNode } export function AuthLayout({ children }: AuthLayoutProps) { return (
{children}
) } ================================================ FILE: frontend/src/components/Common/DataTable.tsx ================================================ import { type ColumnDef, flexRender, getCoreRowModel, getPaginationRowModel, useReactTable, } from "@tanstack/react-table" import { ChevronLeft, ChevronRight, ChevronsLeft, ChevronsRight, } from "lucide-react" import { Button } from "@/components/ui/button" import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select" import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, } from "@/components/ui/table" interface DataTableProps { columns: ColumnDef[] data: TData[] } export function DataTable({ columns, data, }: DataTableProps) { const table = useReactTable({ data, columns, getCoreRowModel: getCoreRowModel(), getPaginationRowModel: getPaginationRowModel(), }) return (
{table.getHeaderGroups().map((headerGroup) => ( {headerGroup.headers.map((header) => { return ( {header.isPlaceholder ? null : flexRender( header.column.columnDef.header, header.getContext(), )} ) })} ))} {table.getRowModel().rows.length ? ( table.getRowModel().rows.map((row) => ( {row.getVisibleCells().map((cell) => ( {flexRender(cell.column.columnDef.cell, cell.getContext())} ))} )) ) : ( No results found. )}
{table.getPageCount() > 1 && (
Showing{" "} {table.getState().pagination.pageIndex * table.getState().pagination.pageSize + 1}{" "} to{" "} {Math.min( (table.getState().pagination.pageIndex + 1) * table.getState().pagination.pageSize, data.length, )}{" "} of{" "} {data.length}{" "} entries

Rows per page

Page {table.getState().pagination.pageIndex + 1} of {table.getPageCount()}
)}
) } ================================================ FILE: frontend/src/components/Common/ErrorComponent.tsx ================================================ import { Link } from "@tanstack/react-router" import { Button } from "@/components/ui/button" const ErrorComponent = () => { return (
Error Oops!

Something went wrong. Please try again.

) } export default ErrorComponent ================================================ FILE: frontend/src/components/Common/Footer.tsx ================================================ import { FaGithub, FaLinkedinIn } from "react-icons/fa" import { FaXTwitter } from "react-icons/fa6" const socialLinks = [ { icon: FaGithub, href: "https://github.com/fastapi/fastapi", label: "GitHub", }, { icon: FaXTwitter, href: "https://x.com/fastapi", label: "X" }, { icon: FaLinkedinIn, href: "https://linkedin.com/company/fastapi", label: "LinkedIn", }, ] export function Footer() { const currentYear = new Date().getFullYear() return (

Full Stack FastAPI Template - {currentYear}

{socialLinks.map(({ icon: Icon, href, label }) => ( ))}
) } ================================================ FILE: frontend/src/components/Common/Logo.tsx ================================================ import { Link } from "@tanstack/react-router" import { useTheme } from "@/components/theme-provider" import { cn } from "@/lib/utils" import icon from "/assets/images/fastapi-icon.svg" import iconLight from "/assets/images/fastapi-icon-light.svg" import logo from "/assets/images/fastapi-logo.svg" import logoLight from "/assets/images/fastapi-logo-light.svg" interface LogoProps { variant?: "full" | "icon" | "responsive" className?: string asLink?: boolean } export function Logo({ variant = "full", className, asLink = true, }: LogoProps) { const { resolvedTheme } = useTheme() const isDark = resolvedTheme === "dark" const fullLogo = isDark ? logoLight : logo const iconLogo = isDark ? iconLight : icon const content = variant === "responsive" ? ( <> FastAPI ) : ( FastAPI ) if (!asLink) { return content } return {content} } ================================================ FILE: frontend/src/components/Common/NotFound.tsx ================================================ import { Link } from "@tanstack/react-router" import { Button } from "@/components/ui/button" const NotFound = () => { return (
404 Oops!

The page you are looking for was not found.

) } export default NotFound ================================================ FILE: frontend/src/components/Items/AddItem.tsx ================================================ import { zodResolver } from "@hookform/resolvers/zod" import { useMutation, useQueryClient } from "@tanstack/react-query" import { Plus } from "lucide-react" import { useState } from "react" import { useForm } from "react-hook-form" import { z } from "zod" import { type ItemCreate, ItemsService } from "@/client" import { Button } from "@/components/ui/button" import { Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger, } from "@/components/ui/dialog" import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage, } from "@/components/ui/form" import { Input } from "@/components/ui/input" import { LoadingButton } from "@/components/ui/loading-button" import useCustomToast from "@/hooks/useCustomToast" import { handleError } from "@/utils" const formSchema = z.object({ title: z.string().min(1, { message: "Title is required" }), description: z.string().optional(), }) type FormData = z.infer const AddItem = () => { const [isOpen, setIsOpen] = useState(false) const queryClient = useQueryClient() const { showSuccessToast, showErrorToast } = useCustomToast() const form = useForm({ resolver: zodResolver(formSchema), mode: "onBlur", criteriaMode: "all", defaultValues: { title: "", description: "", }, }) const mutation = useMutation({ mutationFn: (data: ItemCreate) => ItemsService.createItem({ requestBody: data }), onSuccess: () => { showSuccessToast("Item created successfully") form.reset() setIsOpen(false) }, onError: handleError.bind(showErrorToast), onSettled: () => { queryClient.invalidateQueries({ queryKey: ["items"] }) }, }) const onSubmit = (data: FormData) => { mutation.mutate(data) } return ( Add Item Fill in the details to add a new item.
( Title * )} /> ( Description )} />
Save
) } export default AddItem ================================================ FILE: frontend/src/components/Items/DeleteItem.tsx ================================================ import { useMutation, useQueryClient } from "@tanstack/react-query" import { Trash2 } from "lucide-react" import { useState } from "react" import { useForm } from "react-hook-form" import { ItemsService } from "@/client" import { Button } from "@/components/ui/button" import { Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "@/components/ui/dialog" import { DropdownMenuItem } from "@/components/ui/dropdown-menu" import { LoadingButton } from "@/components/ui/loading-button" import useCustomToast from "@/hooks/useCustomToast" import { handleError } from "@/utils" interface DeleteItemProps { id: string onSuccess: () => void } const DeleteItem = ({ id, onSuccess }: DeleteItemProps) => { const [isOpen, setIsOpen] = useState(false) const queryClient = useQueryClient() const { showSuccessToast, showErrorToast } = useCustomToast() const { handleSubmit } = useForm() const deleteItem = async (id: string) => { await ItemsService.deleteItem({ id: id }) } const mutation = useMutation({ mutationFn: deleteItem, onSuccess: () => { showSuccessToast("The item was deleted successfully") setIsOpen(false) onSuccess() }, onError: handleError.bind(showErrorToast), onSettled: () => { queryClient.invalidateQueries() }, }) const onSubmit = async () => { mutation.mutate(id) } return ( e.preventDefault()} onClick={() => setIsOpen(true)} > Delete Item
Delete Item This item will be permanently deleted. Are you sure? You will not be able to undo this action. Delete
) } export default DeleteItem ================================================ FILE: frontend/src/components/Items/EditItem.tsx ================================================ import { zodResolver } from "@hookform/resolvers/zod" import { useMutation, useQueryClient } from "@tanstack/react-query" import { Pencil } from "lucide-react" import { useState } from "react" import { useForm } from "react-hook-form" import { z } from "zod" import { type ItemPublic, ItemsService } from "@/client" import { Button } from "@/components/ui/button" import { Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "@/components/ui/dialog" import { DropdownMenuItem } from "@/components/ui/dropdown-menu" import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage, } from "@/components/ui/form" import { Input } from "@/components/ui/input" import { LoadingButton } from "@/components/ui/loading-button" import useCustomToast from "@/hooks/useCustomToast" import { handleError } from "@/utils" const formSchema = z.object({ title: z.string().min(1, { message: "Title is required" }), description: z.string().optional(), }) type FormData = z.infer interface EditItemProps { item: ItemPublic onSuccess: () => void } const EditItem = ({ item, onSuccess }: EditItemProps) => { const [isOpen, setIsOpen] = useState(false) const queryClient = useQueryClient() const { showSuccessToast, showErrorToast } = useCustomToast() const form = useForm({ resolver: zodResolver(formSchema), mode: "onBlur", criteriaMode: "all", defaultValues: { title: item.title, description: item.description ?? undefined, }, }) const mutation = useMutation({ mutationFn: (data: FormData) => ItemsService.updateItem({ id: item.id, requestBody: data }), onSuccess: () => { showSuccessToast("Item updated successfully") setIsOpen(false) onSuccess() }, onError: handleError.bind(showErrorToast), onSettled: () => { queryClient.invalidateQueries({ queryKey: ["items"] }) }, }) const onSubmit = (data: FormData) => { mutation.mutate(data) } return ( e.preventDefault()} onClick={() => setIsOpen(true)} > Edit Item
Edit Item Update the item details below.
( Title * )} /> ( Description )} />
Save
) } export default EditItem ================================================ FILE: frontend/src/components/Items/ItemActionsMenu.tsx ================================================ import { EllipsisVertical } from "lucide-react" import { useState } from "react" import type { ItemPublic } from "@/client" import { Button } from "@/components/ui/button" import { DropdownMenu, DropdownMenuContent, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu" import DeleteItem from "../Items/DeleteItem" import EditItem from "../Items/EditItem" interface ItemActionsMenuProps { item: ItemPublic } export const ItemActionsMenu = ({ item }: ItemActionsMenuProps) => { const [open, setOpen] = useState(false) return ( setOpen(false)} /> setOpen(false)} /> ) } ================================================ FILE: frontend/src/components/Items/columns.tsx ================================================ import type { ColumnDef } from "@tanstack/react-table" import { Check, Copy } from "lucide-react" import type { ItemPublic } from "@/client" import { Button } from "@/components/ui/button" import { useCopyToClipboard } from "@/hooks/useCopyToClipboard" import { cn } from "@/lib/utils" import { ItemActionsMenu } from "./ItemActionsMenu" function CopyId({ id }: { id: string }) { const [copiedText, copy] = useCopyToClipboard() const isCopied = copiedText === id return (
{id}
) } export const columns: ColumnDef[] = [ { accessorKey: "id", header: "ID", cell: ({ row }) => , }, { accessorKey: "title", header: "Title", cell: ({ row }) => ( {row.original.title} ), }, { accessorKey: "description", header: "Description", cell: ({ row }) => { const description = row.original.description return ( {description || "No description"} ) }, }, { id: "actions", header: () => Actions, cell: ({ row }) => (
), }, ] ================================================ FILE: frontend/src/components/Pending/PendingItems.tsx ================================================ import { Skeleton } from "@/components/ui/skeleton" import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, } from "@/components/ui/table" const PendingItems = () => ( ID Title Description Actions {Array.from({ length: 5 }).map((_, index) => (
))}
) export default PendingItems ================================================ FILE: frontend/src/components/Pending/PendingUsers.tsx ================================================ import { Skeleton } from "@/components/ui/skeleton" import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, } from "@/components/ui/table" const PendingUsers = () => ( Full Name Email Role Status Actions {Array.from({ length: 5 }).map((_, index) => (
))}
) export default PendingUsers ================================================ FILE: frontend/src/components/Sidebar/AppSidebar.tsx ================================================ import { Briefcase, Home, Users } from "lucide-react" import { SidebarAppearance } from "@/components/Common/Appearance" import { Logo } from "@/components/Common/Logo" import { Sidebar, SidebarContent, SidebarFooter, SidebarHeader, } from "@/components/ui/sidebar" import useAuth from "@/hooks/useAuth" import { type Item, Main } from "./Main" import { User } from "./User" const baseItems: Item[] = [ { icon: Home, title: "Dashboard", path: "/" }, { icon: Briefcase, title: "Items", path: "/items" }, ] export function AppSidebar() { const { user: currentUser } = useAuth() const items = currentUser?.is_superuser ? [...baseItems, { icon: Users, title: "Admin", path: "/admin" }] : baseItems return (
) } export default AppSidebar ================================================ FILE: frontend/src/components/Sidebar/Main.tsx ================================================ import { Link as RouterLink, useRouterState } from "@tanstack/react-router" import type { LucideIcon } from "lucide-react" import { SidebarGroup, SidebarGroupContent, SidebarMenu, SidebarMenuButton, SidebarMenuItem, useSidebar, } from "@/components/ui/sidebar" export type Item = { icon: LucideIcon title: string path: string } interface MainProps { items: Item[] } export function Main({ items }: MainProps) { const { isMobile, setOpenMobile } = useSidebar() const router = useRouterState() const currentPath = router.location.pathname const handleMenuClick = () => { if (isMobile) { setOpenMobile(false) } } return ( {items.map((item) => { const isActive = currentPath === item.path return ( {item.title} ) })} ) } ================================================ FILE: frontend/src/components/Sidebar/User.tsx ================================================ import { Link as RouterLink } from "@tanstack/react-router" import { ChevronsUpDown, LogOut, Settings } from "lucide-react" import { Avatar, AvatarFallback } from "@/components/ui/avatar" import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu" import { SidebarMenu, SidebarMenuButton, SidebarMenuItem, useSidebar, } from "@/components/ui/sidebar" import useAuth from "@/hooks/useAuth" import { getInitials } from "@/utils" interface UserInfoProps { fullName?: string email?: string } function UserInfo({ fullName, email }: UserInfoProps) { return (
{getInitials(fullName || "User")}

{fullName}

{email}

) } export function User({ user }: { user: any }) { const { logout } = useAuth() const { isMobile, setOpenMobile } = useSidebar() if (!user) return null const handleMenuClick = () => { if (isMobile) { setOpenMobile(false) } } const handleLogout = async () => { logout() } return ( User Settings Log Out ) } ================================================ FILE: frontend/src/components/UserSettings/ChangePassword.tsx ================================================ import { zodResolver } from "@hookform/resolvers/zod" import { useMutation } from "@tanstack/react-query" import { useForm } from "react-hook-form" import { z } from "zod" import { type UpdatePassword, UsersService } from "@/client" import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage, } from "@/components/ui/form" import { LoadingButton } from "@/components/ui/loading-button" import { PasswordInput } from "@/components/ui/password-input" import useCustomToast from "@/hooks/useCustomToast" import { handleError } from "@/utils" const formSchema = z .object({ current_password: z .string() .min(1, { message: "Password is required" }) .min(8, { message: "Password must be at least 8 characters" }), new_password: z .string() .min(1, { message: "Password is required" }) .min(8, { message: "Password must be at least 8 characters" }), confirm_password: z .string() .min(1, { message: "Password confirmation is required" }), }) .refine((data) => data.new_password === data.confirm_password, { message: "The passwords don't match", path: ["confirm_password"], }) type FormData = z.infer const ChangePassword = () => { const { showSuccessToast, showErrorToast } = useCustomToast() const form = useForm({ resolver: zodResolver(formSchema), mode: "onSubmit", criteriaMode: "all", defaultValues: { current_password: "", new_password: "", confirm_password: "", }, }) const mutation = useMutation({ mutationFn: (data: UpdatePassword) => UsersService.updatePasswordMe({ requestBody: data }), onSuccess: () => { showSuccessToast("Password updated successfully") form.reset() }, onError: handleError.bind(showErrorToast), }) const onSubmit = async (data: FormData) => { mutation.mutate(data) } return (

Change Password

( Current Password )} /> ( New Password )} /> ( Confirm Password )} /> Update Password
) } export default ChangePassword ================================================ FILE: frontend/src/components/UserSettings/DeleteAccount.tsx ================================================ import DeleteConfirmation from "./DeleteConfirmation" const DeleteAccount = () => { return (

Delete Account

Permanently delete your account and all associated data.

) } export default DeleteAccount ================================================ FILE: frontend/src/components/UserSettings/DeleteConfirmation.tsx ================================================ import { useMutation, useQueryClient } from "@tanstack/react-query" import { useForm } from "react-hook-form" import { UsersService } from "@/client" import { Button } from "@/components/ui/button" import { Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger, } from "@/components/ui/dialog" import { LoadingButton } from "@/components/ui/loading-button" import useAuth from "@/hooks/useAuth" import useCustomToast from "@/hooks/useCustomToast" import { handleError } from "@/utils" const DeleteConfirmation = () => { const queryClient = useQueryClient() const { showSuccessToast, showErrorToast } = useCustomToast() const { handleSubmit } = useForm() const { logout } = useAuth() const mutation = useMutation({ mutationFn: () => UsersService.deleteUserMe(), onSuccess: () => { showSuccessToast("Your account has been successfully deleted") logout() }, onError: handleError.bind(showErrorToast), onSettled: () => { queryClient.invalidateQueries({ queryKey: ["currentUser"] }) }, }) const onSubmit = async () => { mutation.mutate() } return (
Confirmation Required All your account data will be{" "} permanently deleted. If you are sure, please click "Confirm" to proceed. This action cannot be undone. Delete
) } export default DeleteConfirmation ================================================ FILE: frontend/src/components/UserSettings/UserInformation.tsx ================================================ import { zodResolver } from "@hookform/resolvers/zod" import { useMutation, useQueryClient } from "@tanstack/react-query" import { useState } from "react" import { useForm } from "react-hook-form" import { z } from "zod" import { UsersService, type UserUpdateMe } from "@/client" import { Button } from "@/components/ui/button" import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage, } from "@/components/ui/form" import { Input } from "@/components/ui/input" import { LoadingButton } from "@/components/ui/loading-button" import useAuth from "@/hooks/useAuth" import useCustomToast from "@/hooks/useCustomToast" import { cn } from "@/lib/utils" import { handleError } from "@/utils" const formSchema = z.object({ full_name: z.string().max(30).optional(), email: z.email({ message: "Invalid email address" }), }) type FormData = z.infer const UserInformation = () => { const queryClient = useQueryClient() const { showSuccessToast, showErrorToast } = useCustomToast() const [editMode, setEditMode] = useState(false) const { user: currentUser } = useAuth() const form = useForm({ resolver: zodResolver(formSchema), mode: "onBlur", criteriaMode: "all", defaultValues: { full_name: currentUser?.full_name ?? undefined, email: currentUser?.email, }, }) const toggleEditMode = () => { setEditMode(!editMode) } const mutation = useMutation({ mutationFn: (data: UserUpdateMe) => UsersService.updateUserMe({ requestBody: data }), onSuccess: () => { showSuccessToast("User updated successfully") toggleEditMode() }, onError: handleError.bind(showErrorToast), onSettled: () => { queryClient.invalidateQueries() }, }) const onSubmit = (data: FormData) => { const updateData: UserUpdateMe = {} // only include fields that have changed if (data.full_name !== currentUser?.full_name) { updateData.full_name = data.full_name } if (data.email !== currentUser?.email) { updateData.email = data.email } mutation.mutate(updateData) } const onCancel = () => { form.reset() toggleEditMode() } return (

User Information

editMode ? ( Full name ) : ( Full name

{field.value || "N/A"}

) } /> editMode ? ( Email ) : ( Email

{field.value}

) } />
{editMode ? ( <> Save ) : ( )}
) } export default UserInformation ================================================ FILE: frontend/src/components/theme-provider.tsx ================================================ import { createContext, useCallback, useContext, useEffect, useState, } from "react" export type Theme = "dark" | "light" | "system" type ThemeProviderProps = { children: React.ReactNode defaultTheme?: Theme storageKey?: string } type ThemeProviderState = { theme: Theme resolvedTheme: "dark" | "light" setTheme: (theme: Theme) => void } const initialState: ThemeProviderState = { theme: "system", resolvedTheme: "light", setTheme: () => null, } const ThemeProviderContext = createContext(initialState) export function ThemeProvider({ children, defaultTheme = "system", storageKey = "vite-ui-theme", ...props }: ThemeProviderProps) { const [theme, setTheme] = useState( () => (localStorage.getItem(storageKey) as Theme) || defaultTheme, ) const getResolvedTheme = useCallback((theme: Theme): "dark" | "light" => { if (theme === "system") { return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light" } return theme }, []) const [resolvedTheme, setResolvedTheme] = useState<"dark" | "light">(() => getResolvedTheme(theme), ) const updateTheme = useCallback((newTheme: Theme) => { const root = window.document.documentElement root.classList.remove("light", "dark") if (newTheme === "system") { const systemTheme = window.matchMedia("(prefers-color-scheme: dark)") .matches ? "dark" : "light" root.classList.add(systemTheme) return } root.classList.add(newTheme) }, []) useEffect(() => { updateTheme(theme) setResolvedTheme(getResolvedTheme(theme)) const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)") const handleChange = () => { if (theme === "system") { updateTheme("system") setResolvedTheme(getResolvedTheme("system")) } } mediaQuery.addEventListener("change", handleChange) return () => { mediaQuery.removeEventListener("change", handleChange) } }, [theme, updateTheme, getResolvedTheme]) const value = { theme, resolvedTheme, setTheme: (theme: Theme) => { localStorage.setItem(storageKey, theme) setTheme(theme) }, } return ( {children} ) } export const useTheme = () => { const context = useContext(ThemeProviderContext) if (context === undefined) throw new Error("useTheme must be used within a ThemeProvider") return context } ================================================ FILE: frontend/src/components/ui/alert.tsx ================================================ import * as React from "react" import { cva, type VariantProps } from "class-variance-authority" import { cn } from "@/lib/utils" const alertVariants = cva( "relative w-full rounded-lg border px-4 py-3 text-sm grid has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] grid-cols-[0_1fr] has-[>svg]:gap-x-3 gap-y-0.5 items-start [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current", { variants: { variant: { default: "bg-card text-card-foreground", destructive: "text-destructive bg-card [&>svg]:text-current *:data-[slot=alert-description]:text-destructive/90", }, }, defaultVariants: { variant: "default", }, } ) function Alert({ className, variant, ...props }: React.ComponentProps<"div"> & VariantProps) { return (
) } function AlertTitle({ className, ...props }: React.ComponentProps<"div">) { return (
) } function AlertDescription({ className, ...props }: React.ComponentProps<"div">) { return (
) } export { Alert, AlertTitle, AlertDescription } ================================================ FILE: frontend/src/components/ui/avatar.tsx ================================================ import * as React from "react" import * as AvatarPrimitive from "@radix-ui/react-avatar" import { cn } from "@/lib/utils" function Avatar({ className, ...props }: React.ComponentProps) { return ( ) } function AvatarImage({ className, ...props }: React.ComponentProps) { return ( ) } function AvatarFallback({ className, ...props }: React.ComponentProps) { return ( ) } export { Avatar, AvatarImage, AvatarFallback } ================================================ FILE: frontend/src/components/ui/badge.tsx ================================================ import * as React from "react" import { Slot } from "@radix-ui/react-slot" import { cva, type VariantProps } from "class-variance-authority" import { cn } from "@/lib/utils" const badgeVariants = cva( "inline-flex items-center justify-center rounded-full border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden", { variants: { variant: { default: "border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90", secondary: "border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90", destructive: "border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60", outline: "text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground", }, }, defaultVariants: { variant: "default", }, } ) function Badge({ className, variant, asChild = false, ...props }: React.ComponentProps<"span"> & VariantProps & { asChild?: boolean }) { const Comp = asChild ? Slot : "span" return ( ) } export { Badge, badgeVariants } ================================================ FILE: frontend/src/components/ui/button-group.tsx ================================================ import { Slot } from "@radix-ui/react-slot" import { cva, type VariantProps } from "class-variance-authority" import { cn } from "@/lib/utils" import { Separator } from "@/components/ui/separator" const buttonGroupVariants = cva( "flex w-fit items-stretch [&>*]:focus-visible:z-10 [&>*]:focus-visible:relative [&>[data-slot=select-trigger]:not([class*='w-'])]:w-fit [&>input]:flex-1 has-[select[aria-hidden=true]:last-child]:[&>[data-slot=select-trigger]:last-of-type]:rounded-r-md has-[>[data-slot=button-group]]:gap-2", { variants: { orientation: { horizontal: "[&>*:not(:first-child)]:rounded-l-none [&>*:not(:first-child)]:border-l-0 [&>*:not(:last-child)]:rounded-r-none", vertical: "flex-col [&>*:not(:first-child)]:rounded-t-none [&>*:not(:first-child)]:border-t-0 [&>*:not(:last-child)]:rounded-b-none", }, }, defaultVariants: { orientation: "horizontal", }, } ) function ButtonGroup({ className, orientation, ...props }: React.ComponentProps<"div"> & VariantProps) { return (
) } function ButtonGroupText({ className, asChild = false, ...props }: React.ComponentProps<"div"> & { asChild?: boolean }) { const Comp = asChild ? Slot : "div" return ( ) } function ButtonGroupSeparator({ className, orientation = "vertical", ...props }: React.ComponentProps) { return ( ) } export { ButtonGroup, ButtonGroupSeparator, ButtonGroupText, buttonGroupVariants, } ================================================ FILE: frontend/src/components/ui/button.tsx ================================================ import * as React from "react" import { Slot } from "@radix-ui/react-slot" import { cva, type VariantProps } from "class-variance-authority" import { cn } from "@/lib/utils" const buttonVariants = cva( "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive", { variants: { variant: { default: "bg-primary text-primary-foreground hover:bg-primary/90", destructive: "bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60", outline: "border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50", secondary: "bg-secondary text-secondary-foreground hover:bg-secondary/80", ghost: "hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50", link: "text-primary underline-offset-4 hover:underline", }, size: { default: "h-9 px-4 py-2 has-[>svg]:px-3", sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5", lg: "h-10 rounded-md px-6 has-[>svg]:px-4", icon: "size-9", "icon-sm": "size-8", "icon-lg": "size-10", }, }, defaultVariants: { variant: "default", size: "default", }, } ) function Button({ className, variant, size, asChild = false, ...props }: React.ComponentProps<"button"> & VariantProps & { asChild?: boolean }) { const Comp = asChild ? Slot : "button" return ( ) } export { Button, buttonVariants } ================================================ FILE: frontend/src/components/ui/card.tsx ================================================ import * as React from "react" import { cn } from "@/lib/utils" function Card({ className, ...props }: React.ComponentProps<"div">) { return (
) } function CardHeader({ className, ...props }: React.ComponentProps<"div">) { return (
) } function CardTitle({ className, ...props }: React.ComponentProps<"div">) { return (
) } function CardDescription({ className, ...props }: React.ComponentProps<"div">) { return (
) } function CardAction({ className, ...props }: React.ComponentProps<"div">) { return (
) } function CardContent({ className, ...props }: React.ComponentProps<"div">) { return (
) } function CardFooter({ className, ...props }: React.ComponentProps<"div">) { return (
) } export { Card, CardHeader, CardFooter, CardTitle, CardAction, CardDescription, CardContent, } ================================================ FILE: frontend/src/components/ui/checkbox.tsx ================================================ import * as React from "react" import * as CheckboxPrimitive from "@radix-ui/react-checkbox" import { CheckIcon } from "lucide-react" import { cn } from "@/lib/utils" function Checkbox({ className, ...props }: React.ComponentProps) { return ( ) } export { Checkbox } ================================================ FILE: frontend/src/components/ui/dialog.tsx ================================================ import * as React from "react" import * as DialogPrimitive from "@radix-ui/react-dialog" import { XIcon } from "lucide-react" import { cn } from "@/lib/utils" function Dialog({ ...props }: React.ComponentProps) { return } function DialogTrigger({ ...props }: React.ComponentProps) { return } function DialogPortal({ ...props }: React.ComponentProps) { return } function DialogClose({ ...props }: React.ComponentProps) { return } function DialogOverlay({ className, ...props }: React.ComponentProps) { return ( ) } function DialogContent({ className, children, showCloseButton = true, ...props }: React.ComponentProps & { showCloseButton?: boolean }) { return ( {children} {showCloseButton && ( Close )} ) } function DialogHeader({ className, ...props }: React.ComponentProps<"div">) { return (
) } function DialogFooter({ className, ...props }: React.ComponentProps<"div">) { return (
) } function DialogTitle({ className, ...props }: React.ComponentProps) { return ( ) } function DialogDescription({ className, ...props }: React.ComponentProps) { return ( ) } export { Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogOverlay, DialogPortal, DialogTitle, DialogTrigger, } ================================================ FILE: frontend/src/components/ui/dropdown-menu.tsx ================================================ "use client" import * as React from "react" import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu" import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react" import { cn } from "@/lib/utils" function DropdownMenu({ ...props }: React.ComponentProps) { return } function DropdownMenuPortal({ ...props }: React.ComponentProps) { return ( ) } function DropdownMenuTrigger({ ...props }: React.ComponentProps) { return ( ) } function DropdownMenuContent({ className, sideOffset = 4, ...props }: React.ComponentProps) { return ( ) } function DropdownMenuGroup({ ...props }: React.ComponentProps) { return ( ) } function DropdownMenuItem({ className, inset, variant = "default", ...props }: React.ComponentProps & { inset?: boolean variant?: "default" | "destructive" }) { return ( ) } function DropdownMenuCheckboxItem({ className, children, checked, ...props }: React.ComponentProps) { return ( {children} ) } function DropdownMenuRadioGroup({ ...props }: React.ComponentProps) { return ( ) } function DropdownMenuRadioItem({ className, children, ...props }: React.ComponentProps) { return ( {children} ) } function DropdownMenuLabel({ className, inset, ...props }: React.ComponentProps & { inset?: boolean }) { return ( ) } function DropdownMenuSeparator({ className, ...props }: React.ComponentProps) { return ( ) } function DropdownMenuShortcut({ className, ...props }: React.ComponentProps<"span">) { return ( ) } function DropdownMenuSub({ ...props }: React.ComponentProps) { return } function DropdownMenuSubTrigger({ className, inset, children, ...props }: React.ComponentProps & { inset?: boolean }) { return ( {children} ) } function DropdownMenuSubContent({ className, ...props }: React.ComponentProps) { return ( ) } export { DropdownMenu, DropdownMenuPortal, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuCheckboxItem, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuShortcut, DropdownMenuSub, DropdownMenuSubTrigger, DropdownMenuSubContent, } ================================================ FILE: frontend/src/components/ui/form.tsx ================================================ import * as React from "react" import * as LabelPrimitive from "@radix-ui/react-label" import { Slot } from "@radix-ui/react-slot" import { Controller, FormProvider, useFormContext, useFormState, type ControllerProps, type FieldPath, type FieldValues, } from "react-hook-form" import { cn } from "@/lib/utils" import { Label } from "@/components/ui/label" const Form = FormProvider type FormFieldContextValue< TFieldValues extends FieldValues = FieldValues, TName extends FieldPath = FieldPath, > = { name: TName } const FormFieldContext = React.createContext( {} as FormFieldContextValue ) const FormField = < TFieldValues extends FieldValues = FieldValues, TName extends FieldPath = FieldPath, >({ ...props }: ControllerProps) => { return ( ) } const useFormField = () => { const fieldContext = React.useContext(FormFieldContext) const itemContext = React.useContext(FormItemContext) const { getFieldState } = useFormContext() const formState = useFormState({ name: fieldContext.name }) const fieldState = getFieldState(fieldContext.name, formState) if (!fieldContext) { throw new Error("useFormField should be used within ") } const { id } = itemContext return { id, name: fieldContext.name, formItemId: `${id}-form-item`, formDescriptionId: `${id}-form-item-description`, formMessageId: `${id}-form-item-message`, ...fieldState, } } type FormItemContextValue = { id: string } const FormItemContext = React.createContext( {} as FormItemContextValue ) function FormItem({ className, ...props }: React.ComponentProps<"div">) { const id = React.useId() return (
) } function FormLabel({ className, ...props }: React.ComponentProps) { const { error, formItemId } = useFormField() return (