master 8bf00250399b cached
215 files
593.3 KB
162.1k tokens
486 symbols
1 requests
Download .txt
Showing preview only (645K chars total). Download the full file or copy to clipboard to get everything.
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

<a href="https://github.com/fastapi/full-stack-fastapi-template/actions?query=workflow%3A%22Test+Docker+Compose%22" target="_blank"><img src="https://github.com/fastapi/full-stack-fastapi-template/workflows/Test%20Docker%20Compose/badge.svg" alt="Test Docker Compose"></a>
<a href="https://github.com/fastapi/full-stack-fastapi-template/actions?query=workflow%3A%22Test+Backend%22" target="_blank"><img src="https://github.com/fastapi/full-stack-fastapi-template/workflows/Test%20Backend/badge.svg" alt="Test Backend"></a>
<a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/fastapi/full-stack-fastapi-template" target="_blank"><img src="https://coverage-badge.samuelcolvin.workers.dev/fastapi/full-stack-fastapi-template.svg" alt="Coverage"></a>

## 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
================================================
<!doctype html><html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office"><head><title></title><!--[if !mso]><!-- --><meta http-equiv="X-UA-Compatible" content="IE=edge"><!--<![endif]--><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><style type="text/css">#outlook a { padding:0; }
          .ReadMsgBody { width:100%; }
          .ExternalClass { width:100%; }
          .ExternalClass * { line-height:100%; }
          body { margin:0;padding:0;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%; }
          table, td { border-collapse:collapse;mso-table-lspace:0pt;mso-table-rspace:0pt; }
          img { border:0;height:auto;line-height:100%; outline:none;text-decoration:none;-ms-interpolation-mode:bicubic; }
          p { display:block;margin:13px 0; }</style><!--[if !mso]><!--><style type="text/css">@media only screen and (max-width:480px) {
            @-ms-viewport { width:320px; }
            @viewport { width:320px; }
          }</style><!--<![endif]--><!--[if mso]>
        <xml>
        <o:OfficeDocumentSettings>
          <o:AllowPNG/>
          <o:PixelsPerInch>96</o:PixelsPerInch>
        </o:OfficeDocumentSettings>
        </xml>
        <![endif]--><!--[if lte mso 11]>
        <style type="text/css">
          .outlook-group-fix { width:100% !important; }
        </style>
        <![endif]--><!--[if !mso]><!--><link href="https://fonts.googleapis.com/css?family=Ubuntu:300,400,500,700" rel="stylesheet" type="text/css"><style type="text/css">@import url(https://fonts.googleapis.com/css?family=Ubuntu:300,400,500,700);</style><!--<![endif]--><style type="text/css">@media only screen and (min-width:480px) {
        .mj-column-per-100 { width:100% !important; max-width: 100%; }
      }</style><style type="text/css"></style></head><body style="background-color:#fafbfc;"><div style="background-color:#fafbfc;"><!--[if mso | IE]><table align="center" border="0" cellpadding="0" cellspacing="0" class="" style="width:600px;" width="600" ><tr><td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;"><![endif]--><div style="background:#ffffff;background-color:#ffffff;Margin:0px auto;max-width:600px;"><table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="background:#ffffff;background-color:#ffffff;width:100%;"><tbody><tr><td style="direction:ltr;font-size:0px;padding:40px 20px;text-align:center;vertical-align:top;"><!--[if mso | IE]><table role="presentation" border="0" cellpadding="0" cellspacing="0"><tr><td class="" style="vertical-align:middle;width:560px;" ><![endif]--><div class="mj-column-per-100 outlook-group-fix" style="font-size:13px;text-align:left;direction:ltr;display:inline-block;vertical-align:middle;width:100%;"><table border="0" cellpadding="0" cellspacing="0" role="presentation" style="vertical-align:middle;" width="100%"><tr><td align="center" style="font-size:0px;padding:35px;word-break:break-word;"><div style="font-family:Ubuntu, Helvetica, Arial, sans-serif;font-size:20px;line-height:1;text-align:center;color:#333333;">{{ project_name }} - New Account</div></td></tr><tr><td align="center" style="font-size:0px;padding:10px 25px;padding-right:25px;padding-left:25px;word-break:break-word;"><div style="font-family:Arial, Helvetica, sans-serif;font-size:16px;line-height:1;text-align:center;color:#555555;"><span>Welcome to your new account!</span></div></td></tr><tr><td align="center" style="font-size:0px;padding:10px 25px;padding-right:25px;padding-left:25px;word-break:break-word;"><div style="font-family:Arial, Helvetica, sans-serif;font-size:16px;line-height:1;text-align:center;color:#555555;">Here are your account details:</div></td></tr><tr><td align="center" style="font-size:0px;padding:10px 25px;padding-right:25px;padding-left:25px;word-break:break-word;"><div style="font-family:Arial, Helvetica, sans-serif;font-size:16px;line-height:1;text-align:center;color:#555555;">Username: {{ username }}</div></td></tr><tr><td align="center" style="font-size:0px;padding:10px 25px;padding-right:25px;padding-left:25px;word-break:break-word;"><div style="font-family:Arial, Helvetica, sans-serif;font-size:16px;line-height:1;text-align:center;color:#555555;">Password: {{ password }}</div></td></tr><tr><td align="center" vertical-align="middle" style="font-size:0px;padding:15px 30px;word-break:break-word;"><table border="0" cellpadding="0" cellspacing="0" role="presentation" style="border-collapse:separate;line-height:100%;"><tr><td align="center" bgcolor="#009688" role="presentation" style="border:none;border-radius:8px;cursor:auto;padding:10px 25px;background:#009688;" valign="middle"><a href="{{ link }}" style="background:#009688;color:#ffffff;font-family:Ubuntu, Helvetica, Arial, sans-serif;font-size:18px;font-weight:normal;line-height:120%;Margin:0;text-decoration:none;text-transform:none;" target="_blank">Go to Dashboard</a></td></tr></table></td></tr><tr><td style="font-size:0px;padding:10px 25px;word-break:break-word;"><p style="border-top:solid 2px #cccccc;font-size:1;margin:0px auto;width:100%;"></p><!--[if mso | IE]><table align="center" border="0" cellpadding="0" cellspacing="0" style="border-top:solid 2px #cccccc;font-size:1;margin:0px auto;width:510px;" role="presentation" width="510px" ><tr><td style="height:0;line-height:0;"> &nbsp;
</td></tr></table><![endif]--></td></tr></table></div><!--[if mso | IE]></td></tr></table><![endif]--></td></tr></tbody></table></div><!--[if mso | IE]></td></tr></table><![endif]--></div></body></html>

================================================
FILE: backend/app/email-templates/build/reset_password.html
================================================
<!doctype html><html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office"><head><title></title><!--[if !mso]><!-- --><meta http-equiv="X-UA-Compatible" content="IE=edge"><!--<![endif]--><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><style type="text/css">#outlook a { padding:0; }
          .ReadMsgBody { width:100%; }
          .ExternalClass { width:100%; }
          .ExternalClass * { line-height:100%; }
          body { margin:0;padding:0;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%; }
          table, td { border-collapse:collapse;mso-table-lspace:0pt;mso-table-rspace:0pt; }
          img { border:0;height:auto;line-height:100%; outline:none;text-decoration:none;-ms-interpolation-mode:bicubic; }
          p { display:block;margin:13px 0; }</style><!--[if !mso]><!--><style type="text/css">@media only screen and (max-width:480px) {
            @-ms-viewport { width:320px; }
            @viewport { width:320px; }
          }</style><!--<![endif]--><!--[if mso]>
        <xml>
        <o:OfficeDocumentSettings>
          <o:AllowPNG/>
          <o:PixelsPerInch>96</o:PixelsPerInch>
        </o:OfficeDocumentSettings>
        </xml>
        <![endif]--><!--[if lte mso 11]>
        <style type="text/css">
          .outlook-group-fix { width:100% !important; }
        </style>
        <![endif]--><!--[if !mso]><!--><link href="https://fonts.googleapis.com/css?family=Ubuntu:300,400,500,700" rel="stylesheet" type="text/css"><style type="text/css">@import url(https://fonts.googleapis.com/css?family=Ubuntu:300,400,500,700);</style><!--<![endif]--><style type="text/css">@media only screen and (min-width:480px) {
        .mj-column-per-100 { width:100% !important; max-width: 100%; }
      }</style><style type="text/css"></style></head><body style="background-color:#fafbfc;"><div style="background-color:#fafbfc;"><!--[if mso | IE]><table align="center" border="0" cellpadding="0" cellspacing="0" class="" style="width:600px;" width="600" ><tr><td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;"><![endif]--><div style="background:#ffffff;background-color:#ffffff;Margin:0px auto;max-width:600px;"><table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="background:#ffffff;background-color:#ffffff;width:100%;"><tbody><tr><td style="direction:ltr;font-size:0px;padding:40px 20px;text-align:center;vertical-align:top;"><!--[if mso | IE]><table role="presentation" border="0" cellpadding="0" cellspacing="0"><tr><td class="" style="vertical-align:middle;width:560px;" ><![endif]--><div class="mj-column-per-100 outlook-group-fix" style="font-size:13px;text-align:left;direction:ltr;display:inline-block;vertical-align:middle;width:100%;"><table border="0" cellpadding="0" cellspacing="0" role="presentation" style="vertical-align:middle;" width="100%"><tr><td align="center" style="font-size:0px;padding:35px;word-break:break-word;"><div style="font-family:Arial, Helvetica, sans-serif;font-size:20px;line-height:1;text-align:center;color:#333333;">{{ project_name }} - Password Recovery</div></td></tr><tr><td align="center" style="font-size:0px;padding:10px 25px;padding-right:25px;padding-left:25px;word-break:break-word;"><div style="font-family:Arial, Helvetica, sans-serif;font-size:16px;line-height:1;text-align:center;color:#555555;"><span>Hello {{ username }}</span></div></td></tr><tr><td align="center" style="font-size:0px;padding:10px 25px;padding-right:25px;padding-left:25px;word-break:break-word;"><div style="font-family:Arial, Helvetica, sans-serif;font-size:16px;line-height:1;text-align:center;color:#555555;">We've received a request to reset your password. You can do it by clicking the button below:</div></td></tr><tr><td align="center" vertical-align="middle" style="font-size:0px;padding:15px 30px;word-break:break-word;"><table border="0" cellpadding="0" cellspacing="0" role="presentation" style="border-collapse:separate;line-height:100%;"><tr><td align="center" bgcolor="#009688" role="presentation" style="border:none;border-radius:8px;cursor:auto;padding:10px 25px;background:#009688;" valign="middle"><a href="{{ link }}" style="background:#009688;color:#ffffff;font-family:Ubuntu, Helvetica, Arial, sans-serif;font-size:18px;font-weight:normal;line-height:120%;Margin:0;text-decoration:none;text-transform:none;" target="_blank">Reset password</a></td></tr></table></td></tr><tr><td align="center" style="font-size:0px;padding:10px 25px;padding-right:25px;padding-left:25px;word-break:break-word;"><div style="font-family:Arial, Helvetica, sans-serif;font-size:16px;line-height:1;text-align:center;color:#555555;">Or copy and paste the following link into your browser:</div></td></tr><tr><td align="center" style="font-size:0px;padding:10px 25px;padding-right:25px;padding-left:25px;word-break:break-word;"><div style="font-family:Arial, Helvetica, sans-serif;font-size:16px;line-height:1;text-align:center;color:#555555;"><a href="{{ link }}">{{ link }}</a></div></td></tr><tr><td align="center" style="font-size:0px;padding:10px 25px;padding-right:25px;padding-left:25px;word-break:break-word;"><div style="font-family:Arial, Helvetica, sans-serif;font-size:16px;line-height:1;text-align:center;color:#555555;">This password will expire in {{ valid_hours }} hours.</div></td></tr><tr><td style="font-size:0px;padding:10px 25px;word-break:break-word;"><p style="border-top:solid 2px #cccccc;font-size:1;margin:0px auto;width:100%;"></p><!--[if mso | IE]><table align="center" border="0" cellpadding="0" cellspacing="0" style="border-top:solid 2px #cccccc;font-size:1;margin:0px auto;width:510px;" role="presentation" width="510px" ><tr><td style="height:0;line-height:0;"> &nbsp;
</td></tr></table><![endif]--></td></tr><tr><td align="center" style="font-size:0px;padding:10px 25px;padding-right:25px;padding-left:25px;word-break:break-word;"><div style="font-family:Arial, Helvetica, sans-serif;font-size:14px;line-height:1;text-align:center;color:#555555;">If you didn't request a password recovery you can disregard this email.</div></td></tr></table></div><!--[if mso | IE]></td></tr></table><![endif]--></td></tr></tbody></table></div><!--[if mso | IE]></td></tr></table><![endif]--></div></body></html>

================================================
FILE: backend/app/email-templates/build/test_email.html
================================================
<!doctype html><html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office"><head><title></title><!--[if !mso]><!-- --><meta http-equiv="X-UA-Compatible" content="IE=edge"><!--<![endif]--><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><style type="text/css">#outlook a { padding:0; }
          .ReadMsgBody { width:100%; }
          .ExternalClass { width:100%; }
          .ExternalClass * { line-height:100%; }
          body { margin:0;padding:0;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%; }
          table, td { border-collapse:collapse;mso-table-lspace:0pt;mso-table-rspace:0pt; }
          img { border:0;height:auto;line-height:100%; outline:none;text-decoration:none;-ms-interpolation-mode:bicubic; }
          p { display:block;margin:13px 0; }</style><!--[if !mso]><!--><style type="text/css">@media only screen and (max-width:480px) {
            @-ms-viewport { width:320px; }
            @viewport { width:320px; }
          }</style><!--<![endif]--><!--[if mso]>
        <xml>
        <o:OfficeDocumentSettings>
          <o:AllowPNG/>
          <o:PixelsPerInch>96</o:PixelsPerInch>
        </o:OfficeDocumentSettings>
        </xml>
        <![endif]--><!--[if lte mso 11]>
        <style type="text/css">
          .outlook-group-fix { width:100% !important; }
        </style>
        <![endif]--><style type="text/css">@media only screen and (min-width:480px) {
        .mj-column-per-100 { width:100% !important; max-width: 100%; }
      }</style><style type="text/css"></style></head><body style="background-color:#fafbfc;"><div style="background-color:#fafbfc;"><!--[if mso | IE]><table align="center" border="0" cellpadding="0" cellspacing="0" class="" style="width:600px;" width="600" ><tr><td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;"><![endif]--><div style="background:#ffffff;background-color:#ffffff;Margin:0px auto;max-width:600px;"><table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="background:#ffffff;background-color:#ffffff;width:100%;"><tbody><tr><td style="direction:ltr;font-size:0px;padding:40px 20px;text-align:center;vertical-align:top;"><!--[if mso | IE]><table role="presentation" border="0" cellpadding="0" cellspacing="0"><tr><td class="" style="vertical-align:middle;width:560px;" ><![endif]--><div class="mj-column-per-100 outlook-group-fix" style="font-size:13px;text-align:left;direction:ltr;display:inline-block;vertical-align:middle;width:100%;"><table border="0" cellpadding="0" cellspacing="0" role="presentation" style="vertical-align:middle;" width="100%"><tr><td align="center" style="font-size:0px;padding:35px;word-break:break-word;"><div style="font-family:Arial, Helvetica, sans-serif;font-size:20px;line-height:1;text-align:center;color:#333333;">{{ project_name }}</div></td></tr><tr><td align="center" style="font-size:0px;padding:10px 25px;padding-right:25px;padding-left:25px;word-break:break-word;"><div style="font-family:, sans-serif;font-size:16px;line-height:1;text-align:center;color:#555555;"><span>Test email for: {{ email }}</span></div></td></tr><tr><td style="font-size:0px;padding:10px 25px;word-break:break-word;"><p style="border-top:solid 2px #cccccc;font-size:1;margin:0px auto;width:100%;"></p><!--[if mso | IE]><table align="center" border="0" cellpadding="0" cellspacing="0" style="border-top:solid 2px #cccccc;font-size:1;margin:0px auto;width:510px;" role="presentation" width="510px" ><tr><td style="height:0;line-height:0;"> &nbsp;
</td></tr></table><![endif]--></td></tr></table></div><!--[if mso | IE]></td></tr></table><![endif]--></td></tr></tbody></table></div><!--[if mso | IE]></td></tr></table><![endif]--></div></body></html>

================================================
FILE: backend/app/email-templates/src/new_account.mjml
================================================
<mjml>
  <mj-body background-color="#fafbfc">
    <mj-section background-color="#fff" padding="40px 20px">
      <mj-column vertical-align="middle" width="100%">
        <mj-text align="center" padding="35px" font-size="20px" color="#333">{{ project_name }} - New Account</mj-text>
        <mj-text align="center" font-size="16px" padding-left="25px" padding-right="25px" font-family="Arial, Helvetica, sans-serif" color="#555"><span>Welcome to your new account!</span></mj-text>
        <mj-text align="center" font-size="16px" padding-left="25px" padding-right="25px" font-family="Arial, Helvetica, sans-serif" color="#555">Here are your account details:</mj-text>
        <mj-text align="center" font-size="16px" padding-left="25px" padding-right="25px" font-family="Arial, Helvetica, sans-serif" color="#555">Username: {{ username }}</mj-text>
        <mj-text align="center" font-size="16px" padding-left="25px" padding-right="25px" font-family="Arial, Helvetica, sans-serif" color="#555">Password: {{ password }}</mj-text>
        <mj-button align="center" font-size="18px" background-color="#009688" border-radius="8px" color="#fff" href="{{ link }}" padding="15px 30px">Go to Dashboard</mj-button>
        <mj-divider border-color="#ccc" border-width="2px"></mj-divider>
      </mj-column>
    </mj-section>
  </mj-body>
</mjml>


================================================
FILE: backend/app/email-templates/src/reset_password.mjml
================================================
<mjml>
  <mj-body background-color="#fafbfc">
    <mj-section background-color="#fff" padding="40px 20px">
      <mj-column vertical-align="middle" width="100%">
        <mj-text align="center" padding="35px" font-size="20px" font-family="Arial, Helvetica, sans-serif" color="#333">{{ project_name }} - Password Recovery</mj-text>
        <mj-text align="center" font-size="16px" padding-left="25px" padding-right="25px" font-family="Arial, Helvetica, sans-serif" color="#555"><span>Hello {{ username }}</span></mj-text>
        <mj-text align="center" font-size="16px" padding-left="25px" padding-right="25px" font-family="Arial, Helvetica, sans-serif" color="#555">We've received a request to reset your password. You can do it by clicking the button below:</mj-text>
        <mj-button align="center" font-size="18px" background-color="#009688" border-radius="8px" color="#fff" href="{{ link }}" padding="15px 30px">Reset password</mj-button>
        <mj-text align="center" font-size="16px" padding-left="25px" padding-right="25px" font-family="Arial, Helvetica, sans-serif" color="#555">Or copy and paste the following link into your browser:</mj-text>
        <mj-text align="center" font-size="16px" padding-left="25px" padding-right="25px" font-family="Arial, Helvetica, sans-serif" color="#555"><a href="{{ link }}">{{ link }}</a></mj-text>
        <mj-text align="center" font-size="16px" padding-left="25px" padding-right="25px" font-family="Arial, Helvetica, sans-serif" color="#555">This password will expire in {{ valid_hours }} hours.</mj-text>
        <mj-divider border-color="#ccc" border-width="2px"></mj-divider>
        <mj-text align="center" font-size="14px" padding-left="25px" padding-right="25px" font-family="Arial, Helvetica, sans-serif" color="#555">If you didn't request a password recovery you can disregard this email.</mj-text>
      </mj-column>
    </mj-section>
  </mj-body>
</mjml>


================================================
FILE: backend/app/email-templates/src/test_email.mjml
================================================
<mjml>
  <mj-body background-color="#fafbfc">
    <mj-section background-color="#fff" padding="40px 20px">
      <mj-column vertical-align="middle" width="100%">
        <mj-text align="center" padding="35px" font-size="20px" font-family="Arial, Helvetica, sans-serif" color="#333">{{ project_name }}</mj-text>
        <mj-text align="center" font-size="16px" padding-left="25px" padding-right="25px" font-family=", sans-serif" color="#555"><span>Test email for: {{ email }}</span></mj-text>
        <mj-divider border-color="#ccc" border-width="2px"></mj-divider>
      </mj-column>
    </mj-section>
  </mj-body>
</mjml>


================================================
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 nee
Download .txt
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
Download .txt
SYMBOL INDEX (486 symbols across 104 files)

FILE: backend/app/alembic/env.py
  function get_url (line 33) | def get_url():
  function run_migrations_offline (line 37) | def run_migrations_offline():
  function run_migrations_online (line 58) | def run_migrations_online():

FILE: backend/app/alembic/versions/1a31ce608336_add_cascade_delete_relationships.py
  function upgrade (line 20) | def upgrade():
  function downgrade (line 30) | def downgrade():

FILE: backend/app/alembic/versions/9c0a54914c78_add_max_length_for_string_varchar_.py
  function upgrade (line 20) | def upgrade():
  function downgrade (line 46) | def downgrade():

FILE: backend/app/alembic/versions/d98dd8ec85a3_edit_replace_id_integers_in_all_models_.py
  function upgrade (line 21) | def upgrade():
  function downgrade (line 57) | def downgrade():

FILE: backend/app/alembic/versions/e2412789c190_initialize_models.py
  function upgrade (line 19) | def upgrade():
  function downgrade (line 49) | def downgrade():

FILE: backend/app/alembic/versions/fe56fa70289e_add_created_at_to_user_and_item.py
  function upgrade (line 20) | def upgrade():
  function downgrade (line 27) | def downgrade():

FILE: backend/app/api/deps.py
  function get_db (line 21) | def get_db() -> Generator[Session, None, None]:
  function get_current_user (line 30) | def get_current_user(session: SessionDep, token: TokenDep) -> User:
  function get_current_active_superuser (line 52) | def get_current_active_superuser(current_user: CurrentUser) -> User:

FILE: backend/app/api/routes/items.py
  function read_items (line 14) | def read_items(
  function read_item (line 48) | def read_item(session: SessionDep, current_user: CurrentUser, id: uuid.U...
  function create_item (line 61) | def create_item(
  function update_item (line 75) | def update_item(
  function delete_item (line 99) | def delete_item(

FILE: backend/app/api/routes/login.py
  function login_access_token (line 24) | def login_access_token(
  function test_token (line 46) | def test_token(current_user: CurrentUser) -> Any:
  function recover_password (line 54) | def recover_password(email: str, session: SessionDep) -> Message:
  function reset_password (line 78) | def reset_password(session: SessionDep, body: NewPassword) -> Message:
  function recover_password_html_content (line 105) | def recover_password_html_content(email: str, session: SessionDep) -> Any:

FILE: backend/app/api/routes/private.py
  class PrivateUserCreate (line 16) | class PrivateUserCreate(BaseModel):
  function create_user (line 24) | def create_user(user_in: PrivateUserCreate, session: SessionDep) -> Any:

FILE: backend/app/api/routes/users.py
  function read_users (line 37) | def read_users(session: SessionDep, skip: int = 0, limit: int = 100) -> ...
  function create_user (line 56) | def create_user(*, session: SessionDep, user_in: UserCreate) -> Any:
  function update_user_me (line 81) | def update_user_me(
  function update_password_me (line 103) | def update_password_me(
  function read_user_me (line 124) | def read_user_me(current_user: CurrentUser) -> Any:
  function delete_user_me (line 132) | def delete_user_me(session: SessionDep, current_user: CurrentUser) -> Any:
  function register_user (line 146) | def register_user(session: SessionDep, user_in: UserRegister) -> Any:
  function read_user_by_id (line 162) | def read_user_by_id(
  function update_user (line 186) | def update_user(
  function delete_user (line 214) | def delete_user(

FILE: backend/app/api/routes/utils.py
  function test_email (line 16) | def test_email(email_to: EmailStr) -> Message:
  function health_check (line 30) | async def health_check() -> bool:

FILE: backend/app/backend_pre_start.py
  function init (line 22) | def init(db_engine: Engine) -> None:
  function main (line 32) | def main() -> None:

FILE: backend/app/core/config.py
  function parse_cors (line 18) | def parse_cors(v: Any) -> list[str] | str:
  class Settings (line 26) | class Settings(BaseSettings):
    method all_cors_origins (line 46) | def all_cors_origins(self) -> list[str]:
    method SQLALCHEMY_DATABASE_URI (line 61) | def SQLALCHEMY_DATABASE_URI(self) -> PostgresDsn:
    method _set_default_emails_from (line 81) | def _set_default_emails_from(self) -> Self:
    method emails_enabled (line 90) | def emails_enabled(self) -> bool:
    method _check_default_secret (line 97) | def _check_default_secret(self, var_name: str, value: str | None) -> N...
    method _enforce_non_default_secrets (line 109) | def _enforce_non_default_secrets(self) -> Self:

FILE: backend/app/core/db.py
  function init_db (line 15) | def init_db(session: Session) -> None:

FILE: backend/app/core/security.py
  function create_access_token (line 22) | def create_access_token(subject: str | Any, expires_delta: timedelta) ->...
  function verify_password (line 29) | def verify_password(
  function get_password_hash (line 35) | def get_password_hash(password: str) -> str:

FILE: backend/app/crud.py
  function create_user (line 10) | def create_user(*, session: Session, user_create: UserCreate) -> User:
  function update_user (line 20) | def update_user(*, session: Session, db_user: User, user_in: UserUpdate)...
  function get_user_by_email (line 34) | def get_user_by_email(*, session: Session, email: str) -> User | None:
  function authenticate (line 45) | def authenticate(*, session: Session, email: str, password: str) -> User...
  function create_item (line 63) | def create_item(*, session: Session, item_in: ItemCreate, owner_id: uuid...

FILE: backend/app/initial_data.py
  function init (line 11) | def init() -> None:
  function main (line 16) | def main() -> None:

FILE: backend/app/main.py
  function custom_generate_unique_id (line 10) | def custom_generate_unique_id(route: APIRoute) -> str:

FILE: backend/app/models.py
  function get_datetime_utc (line 9) | def get_datetime_utc() -> datetime:
  class UserBase (line 14) | class UserBase(SQLModel):
  class UserCreate (line 22) | class UserCreate(UserBase):
  class UserRegister (line 26) | class UserRegister(SQLModel):
  class UserUpdate (line 33) | class UserUpdate(UserBase):
  class UserUpdateMe (line 38) | class UserUpdateMe(SQLModel):
  class UpdatePassword (line 43) | class UpdatePassword(SQLModel):
  class User (line 49) | class User(UserBase, table=True):
  class UserPublic (line 60) | class UserPublic(UserBase):
  class UsersPublic (line 65) | class UsersPublic(SQLModel):
  class ItemBase (line 71) | class ItemBase(SQLModel):
  class ItemCreate (line 77) | class ItemCreate(ItemBase):
  class ItemUpdate (line 82) | class ItemUpdate(ItemBase):
  class Item (line 87) | class Item(ItemBase, table=True):
  class ItemPublic (line 100) | class ItemPublic(ItemBase):
  class ItemsPublic (line 106) | class ItemsPublic(SQLModel):
  class Message (line 112) | class Message(SQLModel):
  class Token (line 117) | class Token(SQLModel):
  class TokenPayload (line 123) | class TokenPayload(SQLModel):
  class NewPassword (line 127) | class NewPassword(SQLModel):

FILE: backend/app/tests_pre_start.py
  function init (line 22) | def init(db_engine: Engine) -> None:
  function main (line 32) | def main() -> None:

FILE: backend/app/utils.py
  class EmailData (line 20) | class EmailData:
  function render_email_template (line 25) | def render_email_template(*, template_name: str, context: dict[str, Any]...
  function send_email (line 33) | def send_email(
  function generate_test_email (line 58) | def generate_test_email(email_to: str) -> EmailData:
  function generate_reset_password_email (line 68) | def generate_reset_password_email(email_to: str, email: str, token: str)...
  function generate_new_account_email (line 85) | def generate_new_account_email(
  function generate_password_reset_token (line 103) | def generate_password_reset_token(email: str) -> str:
  function verify_password_reset_token (line 116) | def verify_password_reset_token(token: str) -> str | None:

FILE: backend/tests/api/routes/test_items.py
  function test_create_item (line 10) | def test_create_item(
  function test_read_item (line 27) | def test_read_item(
  function test_read_item_not_found (line 43) | def test_read_item_not_found(
  function test_read_item_not_enough_permissions (line 55) | def test_read_item_not_enough_permissions(
  function test_read_items (line 68) | def test_read_items(
  function test_update_item (line 82) | def test_update_item(
  function test_update_item_not_found (line 100) | def test_update_item_not_found(
  function test_update_item_not_enough_permissions (line 114) | def test_update_item_not_enough_permissions(
  function test_delete_item (line 129) | def test_delete_item(
  function test_delete_item_not_found (line 142) | def test_delete_item_not_found(
  function test_delete_item_not_enough_permissions (line 154) | def test_delete_item_not_enough_permissions(

FILE: backend/tests/api/routes/test_login.py
  function test_get_access_token (line 16) | def test_get_access_token(client: TestClient) -> None:
  function test_get_access_token_incorrect_password (line 28) | def test_get_access_token_incorrect_password(client: TestClient) -> None:
  function test_use_access_token (line 37) | def test_use_access_token(
  function test_recovery_password (line 49) | def test_recovery_password(
  function test_recovery_password_user_not_exits (line 67) | def test_recovery_password_user_not_exits(
  function test_reset_password (line 82) | def test_reset_password(client: TestClient, db: Session) -> None:
  function test_reset_password_invalid_token (line 113) | def test_reset_password_invalid_token(
  function test_login_with_bcrypt_password_upgrades_to_argon2 (line 129) | def test_login_with_bcrypt_password_upgrades_to_argon2(
  function test_login_with_argon2_password_keeps_hash (line 165) | def test_login_with_argon2_password_keeps_hash(client: TestClient, db: S...

FILE: backend/tests/api/routes/test_private.py
  function test_create_user (line 8) | def test_create_user(client: TestClient, db: Session) -> None:

FILE: backend/tests/api/routes/test_users.py
  function test_get_users_superuser_me (line 15) | def test_get_users_superuser_me(
  function test_get_users_normal_user_me (line 26) | def test_get_users_normal_user_me(
  function test_create_user_new_email (line 37) | def test_create_user_new_email(
  function test_get_existing_user_as_superuser (line 60) | def test_get_existing_user_as_superuser(
  function test_get_non_existing_user_as_superuser (line 79) | def test_get_non_existing_user_as_superuser(
  function test_get_existing_user_current_user (line 90) | def test_get_existing_user_current_user(client: TestClient, db: Session)...
  function test_get_existing_user_permissions_error (line 117) | def test_get_existing_user_permissions_error(
  function test_get_non_existing_user_permissions_error (line 132) | def test_get_non_existing_user_permissions_error(
  function test_create_user_existing_username (line 146) | def test_create_user_existing_username(
  function test_create_user_by_normal_user (line 165) | def test_create_user_by_normal_user(
  function test_retrieve_users (line 179) | def test_retrieve_users(
  function test_update_user_me (line 201) | def test_update_user_me(
  function test_update_password_me (line 224) | def test_update_password_me(
  function test_update_password_me_incorrect_password (line 267) | def test_update_password_me_incorrect_password(
  function test_update_user_me_email_exists (line 282) | def test_update_user_me_email_exists(
  function test_update_password_me_same_password_error (line 300) | def test_update_password_me_same_password_error(
  function test_register_user (line 319) | def test_register_user(client: TestClient, db: Session) -> None:
  function test_register_user_already_exists_error (line 342) | def test_register_user_already_exists_error(client: TestClient) -> None:
  function test_update_user (line 358) | def test_update_user(
  function test_update_user_not_exists (line 384) | def test_update_user_not_exists(
  function test_update_user_email_exists (line 397) | def test_update_user_email_exists(
  function test_delete_user_me (line 420) | def test_delete_user_me(client: TestClient, db: Session) -> None:
  function test_delete_user_me_as_superuser (line 451) | def test_delete_user_me_as_superuser(
  function test_delete_user_super_user (line 463) | def test_delete_user_super_user(
  function test_delete_user_not_found (line 482) | def test_delete_user_not_found(
  function test_delete_user_current_super_user_error (line 493) | def test_delete_user_current_super_user_error(
  function test_delete_user_without_privileges (line 508) | def test_delete_user_without_privileges(

FILE: backend/tests/conftest.py
  function db (line 16) | def db() -> Generator[Session, None, None]:
  function client (line 28) | def client() -> Generator[TestClient, None, None]:
  function superuser_token_headers (line 34) | def superuser_token_headers(client: TestClient) -> dict[str, str]:
  function normal_user_token_headers (line 39) | def normal_user_token_headers(client: TestClient, db: Session) -> dict[s...

FILE: backend/tests/crud/test_user.py
  function test_create_user (line 11) | def test_create_user(db: Session) -> None:
  function test_authenticate_user (line 20) | def test_authenticate_user(db: Session) -> None:
  function test_not_authenticate_user (line 30) | def test_not_authenticate_user(db: Session) -> None:
  function test_check_if_user_is_active (line 37) | def test_check_if_user_is_active(db: Session) -> None:
  function test_check_if_user_is_active_inactive (line 45) | def test_check_if_user_is_active_inactive(db: Session) -> None:
  function test_check_if_user_is_superuser (line 53) | def test_check_if_user_is_superuser(db: Session) -> None:
  function test_check_if_user_is_superuser_normal_user (line 61) | def test_check_if_user_is_superuser_normal_user(db: Session) -> None:
  function test_get_user (line 69) | def test_get_user(db: Session) -> None:
  function test_update_user (line 80) | def test_update_user(db: Session) -> None:
  function test_authenticate_user_with_bcrypt_upgrades_to_argon2 (line 96) | def test_authenticate_user_with_bcrypt_upgrades_to_argon2(db: Session) -...

FILE: backend/tests/scripts/test_backend_pre_start.py
  function test_init_successful_connection (line 8) | def test_init_successful_connection() -> None:

FILE: backend/tests/scripts/test_test_pre_start.py
  function test_init_successful_connection (line 8) | def test_init_successful_connection() -> None:

FILE: backend/tests/utils/item.py
  function create_random_item (line 9) | def create_random_item(db: Session) -> Item:

FILE: backend/tests/utils/user.py
  function user_authentication_headers (line 10) | def user_authentication_headers(
  function create_random_user (line 22) | def create_random_user(db: Session) -> User:
  function authentication_token_from_email (line 30) | def authentication_token_from_email(

FILE: backend/tests/utils/utils.py
  function random_lower_string (line 9) | def random_lower_string() -> str:
  function random_email (line 13) | def random_email() -> str:
  function get_superuser_token_headers (line 17) | def get_superuser_token_headers(client: TestClient) -> dict[str, str]:

FILE: frontend/src/client/core/ApiError.ts
  class ApiError (line 4) | class ApiError extends Error {
    method constructor (line 11) | constructor(request: ApiRequestOptions, response: ApiResult, message: ...

FILE: frontend/src/client/core/ApiRequestOptions.ts
  type ApiRequestOptions (line 1) | type ApiRequestOptions<T = unknown> = {

FILE: frontend/src/client/core/ApiResult.ts
  type ApiResult (line 1) | type ApiResult<TData = any> = {

FILE: frontend/src/client/core/CancelablePromise.ts
  class CancelError (line 1) | class CancelError extends Error {
    method constructor (line 2) | constructor(message: string) {
    method isCancelled (line 7) | public get isCancelled(): boolean {
  type OnCancel (line 12) | interface OnCancel {
  class CancelablePromise (line 20) | class CancelablePromise<T> implements Promise<T> {
    method constructor (line 29) | constructor(
    method then (line 87) | public then<TResult1 = T, TResult2 = never>(
    method catch (line 94) | public catch<TResult = never>(
    method finally (line 100) | public finally(onFinally?: (() => void) | null): Promise<T> {
    method cancel (line 104) | public cancel(): void {
    method isCancelled (line 123) | public get isCancelled(): boolean {
  method [Symbol.toStringTag] (line 83) | get [Symbol.toStringTag]() {

FILE: frontend/src/client/core/OpenAPI.ts
  type Headers (line 4) | type Headers = Record<string, string>;
  type Middleware (line 5) | type Middleware<T> = (value: T) => T | Promise<T>;
  type Resolver (line 6) | type Resolver<T> = (options: ApiRequestOptions<T>) => Promise<T>;
  class Interceptors (line 8) | class Interceptors<T> {
    method constructor (line 11) | constructor() {
    method eject (line 15) | eject(fn: Middleware<T>): void {
    method use (line 22) | use(fn: Middleware<T>): void {
  type OpenAPIConfig (line 27) | type OpenAPIConfig = {

FILE: frontend/src/client/core/request.ts
  type Resolver (line 111) | type Resolver<T> = (options: ApiRequestOptions<T>) => Promise<T>;

FILE: frontend/src/client/sdk.gen.ts
  class ItemsService (line 8) | class ItemsService {
    method readItems (line 18) | public static readItems(data: ItemsReadItemsData = {}): CancelableProm...
    method createItem (line 40) | public static createItem(data: ItemsCreateItemData): CancelablePromise...
    method readItem (line 60) | public static readItem(data: ItemsReadItemData): CancelablePromise<Ite...
    method updateItem (line 82) | public static updateItem(data: ItemsUpdateItemData): CancelablePromise...
    method deleteItem (line 105) | public static deleteItem(data: ItemsDeleteItemData): CancelablePromise...
  class LoginService (line 119) | class LoginService {
    method loginAccessToken (line 128) | public static loginAccessToken(data: LoginLoginAccessTokenData): Cance...
    method testToken (line 146) | public static testToken(): CancelablePromise<LoginTestTokenResponse> {
    method recoverPassword (line 161) | public static recoverPassword(data: LoginRecoverPasswordData): Cancela...
    method resetPassword (line 182) | public static resetPassword(data: LoginResetPasswordData): CancelableP...
    method recoverPasswordHtmlContent (line 202) | public static recoverPasswordHtmlContent(data: LoginRecoverPasswordHtm...
  class PrivateService (line 216) | class PrivateService {
    method createUser (line 225) | public static createUser(data: PrivateCreateUserData): CancelablePromi...
  class UsersService (line 238) | class UsersService {
    method readUsers (line 248) | public static readUsers(data: UsersReadUsersData = {}): CancelableProm...
    method createUser (line 270) | public static createUser(data: UsersCreateUserData): CancelablePromise...
    method readUserMe (line 288) | public static readUserMe(): CancelablePromise<UsersReadUserMeResponse> {
    method deleteUserMe (line 301) | public static deleteUserMe(): CancelablePromise<UsersDeleteUserMeRespo...
    method updateUserMe (line 316) | public static updateUserMe(data: UsersUpdateUserMeData): CancelablePro...
    method updatePasswordMe (line 336) | public static updatePasswordMe(data: UsersUpdatePasswordMeData): Cance...
    method registerUser (line 356) | public static registerUser(data: UsersRegisterUserData): CancelablePro...
    method readUserById (line 376) | public static readUserById(data: UsersReadUserByIdData): CancelablePro...
    method updateUser (line 398) | public static updateUser(data: UsersUpdateUserData): CancelablePromise...
    method deleteUser (line 421) | public static deleteUser(data: UsersDeleteUserData): CancelablePromise...
  class UtilsService (line 435) | class UtilsService {
    method testEmail (line 444) | public static testEmail(data: UtilsTestEmailData): CancelablePromise<U...
    method healthCheck (line 462) | public static healthCheck(): CancelablePromise<UtilsHealthCheckRespons...

FILE: frontend/src/client/types.gen.ts
  type Body_login_login_access_token (line 3) | type Body_login_login_access_token = {
  type HTTPValidationError (line 12) | type HTTPValidationError = {
  type ItemCreate (line 16) | type ItemCreate = {
  type ItemPublic (line 21) | type ItemPublic = {
  type ItemsPublic (line 29) | type ItemsPublic = {
  type ItemUpdate (line 34) | type ItemUpdate = {
  type Message (line 39) | type Message = {
  type NewPassword (line 43) | type NewPassword = {
  type PrivateUserCreate (line 48) | type PrivateUserCreate = {
  type Token (line 55) | type Token = {
  type UpdatePassword (line 60) | type UpdatePassword = {
  type UserCreate (line 65) | type UserCreate = {
  type UserPublic (line 73) | type UserPublic = {
  type UserRegister (line 82) | type UserRegister = {
  type UsersPublic (line 88) | type UsersPublic = {
  type UserUpdate (line 93) | type UserUpdate = {
  type UserUpdateMe (line 101) | type UserUpdateMe = {
  type ValidationError (line 106) | type ValidationError = {
  type ItemsReadItemsData (line 116) | type ItemsReadItemsData = {
  type ItemsReadItemsResponse (line 121) | type ItemsReadItemsResponse = (ItemsPublic);
  type ItemsCreateItemData (line 123) | type ItemsCreateItemData = {
  type ItemsCreateItemResponse (line 127) | type ItemsCreateItemResponse = (ItemPublic);
  type ItemsReadItemData (line 129) | type ItemsReadItemData = {
  type ItemsReadItemResponse (line 133) | type ItemsReadItemResponse = (ItemPublic);
  type ItemsUpdateItemData (line 135) | type ItemsUpdateItemData = {
  type ItemsUpdateItemResponse (line 140) | type ItemsUpdateItemResponse = (ItemPublic);
  type ItemsDeleteItemData (line 142) | type ItemsDeleteItemData = {
  type ItemsDeleteItemResponse (line 146) | type ItemsDeleteItemResponse = (Message);
  type LoginLoginAccessTokenData (line 148) | type LoginLoginAccessTokenData = {
  type LoginLoginAccessTokenResponse (line 152) | type LoginLoginAccessTokenResponse = (Token);
  type LoginTestTokenResponse (line 154) | type LoginTestTokenResponse = (UserPublic);
  type LoginRecoverPasswordData (line 156) | type LoginRecoverPasswordData = {
  type LoginRecoverPasswordResponse (line 160) | type LoginRecoverPasswordResponse = (Message);
  type LoginResetPasswordData (line 162) | type LoginResetPasswordData = {
  type LoginResetPasswordResponse (line 166) | type LoginResetPasswordResponse = (Message);
  type LoginRecoverPasswordHtmlContentData (line 168) | type LoginRecoverPasswordHtmlContentData = {
  type LoginRecoverPasswordHtmlContentResponse (line 172) | type LoginRecoverPasswordHtmlContentResponse = (string);
  type PrivateCreateUserData (line 174) | type PrivateCreateUserData = {
  type PrivateCreateUserResponse (line 178) | type PrivateCreateUserResponse = (UserPublic);
  type UsersReadUsersData (line 180) | type UsersReadUsersData = {
  type UsersReadUsersResponse (line 185) | type UsersReadUsersResponse = (UsersPublic);
  type UsersCreateUserData (line 187) | type UsersCreateUserData = {
  type UsersCreateUserResponse (line 191) | type UsersCreateUserResponse = (UserPublic);
  type UsersReadUserMeResponse (line 193) | type UsersReadUserMeResponse = (UserPublic);
  type UsersDeleteUserMeResponse (line 195) | type UsersDeleteUserMeResponse = (Message);
  type UsersUpdateUserMeData (line 197) | type UsersUpdateUserMeData = {
  type UsersUpdateUserMeResponse (line 201) | type UsersUpdateUserMeResponse = (UserPublic);
  type UsersUpdatePasswordMeData (line 203) | type UsersUpdatePasswordMeData = {
  type UsersUpdatePasswordMeResponse (line 207) | type UsersUpdatePasswordMeResponse = (Message);
  type UsersRegisterUserData (line 209) | type UsersRegisterUserData = {
  type UsersRegisterUserResponse (line 213) | type UsersRegisterUserResponse = (UserPublic);
  type UsersReadUserByIdData (line 215) | type UsersReadUserByIdData = {
  type UsersReadUserByIdResponse (line 219) | type UsersReadUserByIdResponse = (UserPublic);
  type UsersUpdateUserData (line 221) | type UsersUpdateUserData = {
  type UsersUpdateUserResponse (line 226) | type UsersUpdateUserResponse = (UserPublic);
  type UsersDeleteUserData (line 228) | type UsersDeleteUserData = {
  type UsersDeleteUserResponse (line 232) | type UsersDeleteUserResponse = (Message);
  type UtilsTestEmailData (line 234) | type UtilsTestEmailData = {
  type UtilsTestEmailResponse (line 238) | type UtilsTestEmailResponse = (Message);
  type UtilsHealthCheckResponse (line 240) | type UtilsHealthCheckResponse = (boolean);

FILE: frontend/src/components/Admin/AddUser.tsx
  type FormData (line 53) | type FormData = z.infer<typeof formSchema>

FILE: frontend/src/components/Admin/DeleteUser.tsx
  type DeleteUserProps (line 22) | interface DeleteUserProps {

FILE: frontend/src/components/Admin/EditUser.tsx
  type FormData (line 52) | type FormData = z.infer<typeof formSchema>
  type EditUserProps (line 54) | interface EditUserProps {

FILE: frontend/src/components/Admin/UserActionsMenu.tsx
  type UserActionsMenuProps (line 15) | interface UserActionsMenuProps {

FILE: frontend/src/components/Admin/columns.tsx
  type UserTableData (line 8) | type UserTableData = UserPublic & {

FILE: frontend/src/components/Common/Appearance.tsx
  type LucideIcon (line 17) | type LucideIcon = React.FC<React.SVGProps<SVGSVGElement>>
  constant ICON_MAP (line 19) | const ICON_MAP: Record<Theme, LucideIcon> = {

FILE: frontend/src/components/Common/AuthLayout.tsx
  type AuthLayoutProps (line 5) | interface AuthLayoutProps {
  function AuthLayout (line 9) | function AuthLayout({ children }: AuthLayoutProps) {

FILE: frontend/src/components/Common/DataTable.tsx
  type DataTableProps (line 32) | interface DataTableProps<TData, TValue> {
  function DataTable (line 37) | function DataTable<TData, TValue>({

FILE: frontend/src/components/Common/Footer.tsx
  function Footer (line 18) | function Footer() {

FILE: frontend/src/components/Common/Logo.tsx
  type LogoProps (line 10) | interface LogoProps {
  function Logo (line 16) | function Logo({

FILE: frontend/src/components/Items/AddItem.tsx
  type FormData (line 38) | type FormData = z.infer<typeof formSchema>

FILE: frontend/src/components/Items/DeleteItem.tsx
  type DeleteItemProps (line 22) | interface DeleteItemProps {

FILE: frontend/src/components/Items/EditItem.tsx
  type FormData (line 38) | type FormData = z.infer<typeof formSchema>
  type EditItemProps (line 40) | interface EditItemProps {

FILE: frontend/src/components/Items/ItemActionsMenu.tsx
  type ItemActionsMenuProps (line 14) | interface ItemActionsMenuProps {

FILE: frontend/src/components/Items/columns.tsx
  function CopyId (line 10) | function CopyId({ id }: { id: string }) {

FILE: frontend/src/components/Sidebar/AppSidebar.tsx
  function AppSidebar (line 20) | function AppSidebar() {

FILE: frontend/src/components/Sidebar/Main.tsx
  type Item (line 13) | type Item = {
  type MainProps (line 19) | interface MainProps {
  function Main (line 23) | function Main({ items }: MainProps) {

FILE: frontend/src/components/Sidebar/User.tsx
  type UserInfoProps (line 22) | interface UserInfoProps {
  function UserInfo (line 27) | function UserInfo({ fullName, email }: UserInfoProps) {
  function User (line 43) | function User({ user }: { user: any }) {

FILE: frontend/src/components/UserSettings/ChangePassword.tsx
  type FormData (line 39) | type FormData = z.infer<typeof formSchema>

FILE: frontend/src/components/UserSettings/UserInformation.tsx
  type FormData (line 29) | type FormData = z.infer<typeof formSchema>

FILE: frontend/src/components/theme-provider.tsx
  type Theme (line 9) | type Theme = "dark" | "light" | "system"
  type ThemeProviderProps (line 11) | type ThemeProviderProps = {
  type ThemeProviderState (line 17) | type ThemeProviderState = {
  function ThemeProvider (line 31) | function ThemeProvider({

FILE: frontend/src/components/ui/alert.tsx
  function Alert (line 22) | function Alert({
  function AlertTitle (line 37) | function AlertTitle({ className, ...props }: React.ComponentProps<"div">) {
  function AlertDescription (line 50) | function AlertDescription({

FILE: frontend/src/components/ui/avatar.tsx
  function Avatar (line 6) | function Avatar({
  function AvatarImage (line 22) | function AvatarImage({
  function AvatarFallback (line 35) | function AvatarFallback({

FILE: frontend/src/components/ui/badge.tsx
  function Badge (line 28) | function Badge({

FILE: frontend/src/components/ui/button-group.tsx
  function ButtonGroup (line 24) | function ButtonGroup({
  function ButtonGroupText (line 40) | function ButtonGroupText({
  function ButtonGroupSeparator (line 60) | function ButtonGroupSeparator({

FILE: frontend/src/components/ui/button.tsx
  function Button (line 39) | function Button({

FILE: frontend/src/components/ui/card.tsx
  function Card (line 5) | function Card({ className, ...props }: React.ComponentProps<"div">) {
  function CardHeader (line 18) | function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
  function CardTitle (line 31) | function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
  function CardDescription (line 41) | function CardDescription({ className, ...props }: React.ComponentProps<"...
  function CardAction (line 51) | function CardAction({ className, ...props }: React.ComponentProps<"div">) {
  function CardContent (line 64) | function CardContent({ className, ...props }: React.ComponentProps<"div"...
  function CardFooter (line 74) | function CardFooter({ className, ...props }: React.ComponentProps<"div">) {

FILE: frontend/src/components/ui/checkbox.tsx
  function Checkbox (line 7) | function Checkbox({

FILE: frontend/src/components/ui/dialog.tsx
  function Dialog (line 7) | function Dialog({
  function DialogTrigger (line 13) | function DialogTrigger({
  function DialogPortal (line 19) | function DialogPortal({
  function DialogClose (line 25) | function DialogClose({
  function DialogOverlay (line 31) | function DialogOverlay({
  function DialogContent (line 47) | function DialogContent({
  function DialogHeader (line 81) | function DialogHeader({ className, ...props }: React.ComponentProps<"div...
  function DialogFooter (line 91) | function DialogFooter({ className, ...props }: React.ComponentProps<"div...
  function DialogTitle (line 104) | function DialogTitle({
  function DialogDescription (line 117) | function DialogDescription({

FILE: frontend/src/components/ui/dropdown-menu.tsx
  function DropdownMenu (line 9) | function DropdownMenu({
  function DropdownMenuPortal (line 15) | function DropdownMenuPortal({
  function DropdownMenuTrigger (line 23) | function DropdownMenuTrigger({
  function DropdownMenuContent (line 34) | function DropdownMenuContent({
  function DropdownMenuGroup (line 54) | function DropdownMenuGroup({
  function DropdownMenuItem (line 62) | function DropdownMenuItem({
  function DropdownMenuCheckboxItem (line 85) | function DropdownMenuCheckboxItem({
  function DropdownMenuRadioGroup (line 111) | function DropdownMenuRadioGroup({
  function DropdownMenuRadioItem (line 122) | function DropdownMenuRadioItem({
  function DropdownMenuLabel (line 146) | function DropdownMenuLabel({
  function DropdownMenuSeparator (line 166) | function DropdownMenuSeparator({
  function DropdownMenuShortcut (line 179) | function DropdownMenuShortcut({
  function DropdownMenuSub (line 195) | function DropdownMenuSub({
  function DropdownMenuSubTrigger (line 201) | function DropdownMenuSubTrigger({
  function DropdownMenuSubContent (line 225) | function DropdownMenuSubContent({

FILE: frontend/src/components/ui/form.tsx
  type FormFieldContextValue (line 19) | type FormFieldContextValue<
  type FormItemContextValue (line 66) | type FormItemContextValue = {
  function FormItem (line 74) | function FormItem({ className, ...props }: React.ComponentProps<"div">) {
  function FormLabel (line 88) | function FormLabel({
  function FormControl (line 105) | function FormControl({ ...props }: React.ComponentProps<typeof Slot>) {
  function FormDescription (line 123) | function FormDescription({ className, ...props }: React.ComponentProps<"...
  function FormMessage (line 136) | function FormMessage({ className, ...props }: React.ComponentProps<"p">) {

FILE: frontend/src/components/ui/input.tsx
  function Input (line 5) | function Input({ className, type, ...props }: React.ComponentProps<"inpu...

FILE: frontend/src/components/ui/label.tsx
  function Label (line 8) | function Label({

FILE: frontend/src/components/ui/loading-button.tsx
  type ButtonProps (line 37) | interface ButtonProps
  function LoadingButton (line 44) | function LoadingButton({

FILE: frontend/src/components/ui/pagination.tsx
  function Pagination (line 11) | function Pagination({ className, ...props }: React.ComponentProps<"nav">) {
  function PaginationContent (line 23) | function PaginationContent({
  function PaginationItem (line 36) | function PaginationItem({ ...props }: React.ComponentProps<"li">) {
  type PaginationLinkProps (line 40) | type PaginationLinkProps = {
  function PaginationLink (line 45) | function PaginationLink({
  function PaginationPrevious (line 68) | function PaginationPrevious({
  function PaginationNext (line 85) | function PaginationNext({
  function PaginationEllipsis (line 102) | function PaginationEllipsis({

FILE: frontend/src/components/ui/password-input.tsx
  type PasswordInputProps (line 7) | interface PasswordInputProps extends React.ComponentProps<"input"> {

FILE: frontend/src/components/ui/select.tsx
  function Select (line 7) | function Select({
  function SelectGroup (line 13) | function SelectGroup({
  function SelectValue (line 19) | function SelectValue({
  function SelectTrigger (line 25) | function SelectTrigger({
  function SelectContent (line 51) | function SelectContent({
  function SelectLabel (line 88) | function SelectLabel({
  function SelectItem (line 101) | function SelectItem({
  function SelectSeparator (line 125) | function SelectSeparator({
  function SelectScrollUpButton (line 138) | function SelectScrollUpButton({
  function SelectScrollDownButton (line 156) | function SelectScrollDownButton({

FILE: frontend/src/components/ui/separator.tsx
  function Separator (line 6) | function Separator({

FILE: frontend/src/components/ui/sheet.tsx
  function Sheet (line 9) | function Sheet({ ...props }: React.ComponentProps<typeof SheetPrimitive....
  function SheetTrigger (line 13) | function SheetTrigger({
  function SheetClose (line 19) | function SheetClose({
  function SheetPortal (line 25) | function SheetPortal({
  function SheetOverlay (line 31) | function SheetOverlay({
  function SheetContent (line 47) | function SheetContent({
  function SheetHeader (line 84) | function SheetHeader({ className, ...props }: React.ComponentProps<"div"...
  function SheetFooter (line 94) | function SheetFooter({ className, ...props }: React.ComponentProps<"div"...
  function SheetTitle (line 104) | function SheetTitle({
  function SheetDescription (line 117) | function SheetDescription({

FILE: frontend/src/components/ui/sidebar.tsx
  constant SIDEBAR_COOKIE_NAME (line 26) | const SIDEBAR_COOKIE_NAME = "sidebar_state"
  constant SIDEBAR_COOKIE_MAX_AGE (line 27) | const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7
  constant SIDEBAR_WIDTH (line 28) | const SIDEBAR_WIDTH = "16rem"
  constant SIDEBAR_WIDTH_MOBILE (line 29) | const SIDEBAR_WIDTH_MOBILE = "18rem"
  constant SIDEBAR_WIDTH_ICON (line 30) | const SIDEBAR_WIDTH_ICON = "3rem"
  constant SIDEBAR_KEYBOARD_SHORTCUT (line 31) | const SIDEBAR_KEYBOARD_SHORTCUT = "b"
  type SidebarContextProps (line 33) | type SidebarContextProps = {
  function useSidebar (line 45) | function useSidebar() {
  function SidebarProvider (line 54) | function SidebarProvider({
  function Sidebar (line 164) | function Sidebar({
  function SidebarTrigger (line 266) | function SidebarTrigger({
  function SidebarRail (line 293) | function SidebarRail({ className, ...props }: React.ComponentProps<"butt...
  function SidebarInset (line 318) | function SidebarInset({ className, ...props }: React.ComponentProps<"mai...
  function SidebarInput (line 332) | function SidebarInput({
  function SidebarHeader (line 346) | function SidebarHeader({ className, ...props }: React.ComponentProps<"di...
  function SidebarFooter (line 357) | function SidebarFooter({ className, ...props }: React.ComponentProps<"di...
  function SidebarSeparator (line 368) | function SidebarSeparator({
  function SidebarContent (line 382) | function SidebarContent({ className, ...props }: React.ComponentProps<"d...
  function SidebarGroup (line 396) | function SidebarGroup({ className, ...props }: React.ComponentProps<"div...
  function SidebarGroupLabel (line 407) | function SidebarGroupLabel({
  function SidebarGroupAction (line 428) | function SidebarGroupAction({
  function SidebarGroupContent (line 451) | function SidebarGroupContent({
  function SidebarMenu (line 465) | function SidebarMenu({ className, ...props }: React.ComponentProps<"ul">) {
  function SidebarMenuItem (line 476) | function SidebarMenuItem({ className, ...props }: React.ComponentProps<"...
  function SidebarMenuButton (line 509) | function SidebarMenuButton({
  function SidebarMenuAction (line 559) | function SidebarMenuAction({
  function SidebarMenuBadge (line 591) | function SidebarMenuBadge({
  function SidebarMenuSkeleton (line 613) | function SidebarMenuSkeleton({
  function SidebarMenuSub (line 651) | function SidebarMenuSub({ className, ...props }: React.ComponentProps<"u...
  function SidebarMenuSubItem (line 666) | function SidebarMenuSubItem({
  function SidebarMenuSubButton (line 680) | function SidebarMenuSubButton({

FILE: frontend/src/components/ui/skeleton.tsx
  function Skeleton (line 3) | function Skeleton({ className, ...props }: React.ComponentProps<"div">) {

FILE: frontend/src/components/ui/table.tsx
  function Table (line 5) | function Table({ className, ...props }: React.ComponentProps<"table">) {
  function TableHeader (line 20) | function TableHeader({ className, ...props }: React.ComponentProps<"thea...
  function TableBody (line 30) | function TableBody({ className, ...props }: React.ComponentProps<"tbody"...
  function TableFooter (line 40) | function TableFooter({ className, ...props }: React.ComponentProps<"tfoo...
  function TableRow (line 53) | function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
  function TableHead (line 66) | function TableHead({ className, ...props }: React.ComponentProps<"th">) {
  function TableCell (line 79) | function TableCell({ className, ...props }: React.ComponentProps<"td">) {
  function TableCaption (line 92) | function TableCaption({

FILE: frontend/src/components/ui/tabs.tsx
  function Tabs (line 6) | function Tabs({
  function TabsList (line 19) | function TabsList({
  function TabsTrigger (line 35) | function TabsTrigger({
  function TabsContent (line 51) | function TabsContent({

FILE: frontend/src/components/ui/tooltip.tsx
  function TooltipProvider (line 6) | function TooltipProvider({
  function Tooltip (line 19) | function Tooltip({
  function TooltipTrigger (line 29) | function TooltipTrigger({
  function TooltipContent (line 35) | function TooltipContent({

FILE: frontend/src/hooks/useCopyToClipboard.ts
  type CopiedValue (line 4) | type CopiedValue = string | null
  type CopyFn (line 6) | type CopyFn = (text: string) => Promise<boolean>
  function useCopyToClipboard (line 8) | function useCopyToClipboard(): [CopiedValue, CopyFn] {

FILE: frontend/src/hooks/useMobile.ts
  constant MOBILE_BREAKPOINT (line 3) | const MOBILE_BREAKPOINT = 768
  function useIsMobile (line 5) | function useIsMobile() {

FILE: frontend/src/lib/utils.ts
  function cn (line 4) | function cn(...inputs: ClassValue[]) {

FILE: frontend/src/main.tsx
  type Register (line 38) | interface Register {

FILE: frontend/src/routeTree.gen.ts
  type FileRoutesByFullPath (line 67) | interface FileRoutesByFullPath {
  type FileRoutesByTo (line 77) | interface FileRoutesByTo {
  type FileRoutesById (line 87) | interface FileRoutesById {
  type FileRouteTypes (line 99) | interface FileRouteTypes {
  type RootRouteChildren (line 133) | interface RootRouteChildren {
  type FileRoutesByPath (line 142) | interface FileRoutesByPath {
  type LayoutRouteChildren (line 209) | interface LayoutRouteChildren {

FILE: frontend/src/routes/_layout.tsx
  function Layout (line 23) | function Layout() {

FILE: frontend/src/routes/_layout/admin.tsx
  function getUsersQueryOptions (line 12) | function getUsersQueryOptions() {
  function UsersTableContent (line 38) | function UsersTableContent() {
  function UsersTable (line 50) | function UsersTable() {
  function Admin (line 58) | function Admin() {

FILE: frontend/src/routes/_layout/index.tsx
  function Dashboard (line 16) | function Dashboard() {

FILE: frontend/src/routes/_layout/items.tsx
  function getItemsQueryOptions (line 12) | function getItemsQueryOptions() {
  function ItemsTableContent (line 30) | function ItemsTableContent() {
  function ItemsTable (line 48) | function ItemsTable() {
  function Items (line 56) | function Items() {

FILE: frontend/src/routes/_layout/settings.tsx
  function UserSettings (line 26) | function UserSettings() {

FILE: frontend/src/routes/login.tsx
  type FormData (line 33) | type FormData = z.infer<typeof formSchema>
  function Login (line 53) | function Login() {

FILE: frontend/src/routes/recover-password.tsx
  type FormData (line 31) | type FormData = z.infer<typeof formSchema>
  function RecoverPassword (line 51) | function RecoverPassword() {

FILE: frontend/src/routes/reset-password.tsx
  type FormData (line 47) | type FormData = z.infer<typeof formSchema>
  function ResetPassword (line 69) | function ResetPassword() {

FILE: frontend/src/routes/signup.tsx
  type FormData (line 40) | type FormData = z.infer<typeof formSchema>
  function SignUp (line 60) | function SignUp() {

FILE: frontend/src/utils.ts
  function extractErrorMessage (line 4) | function extractErrorMessage(err: ApiError): string {

FILE: frontend/src/vite-env.d.ts
  type ImportMetaEnv (line 3) | interface ImportMetaEnv {
  type ImportMeta (line 7) | interface ImportMeta {

FILE: frontend/tests/config.ts
  function getEnvVar (line 10) | function getEnvVar(name: string): string {

FILE: frontend/tests/utils/mailcatcher.ts
  type Email (line 3) | type Email = {
  function findEmail (line 9) | async function findEmail({
  function findLastEmail (line 33) | function findLastEmail({

FILE: frontend/tests/utils/user.ts
  function signUpNewUser (line 3) | async function signUpNewUser(
  function logInUser (line 19) | async function logInUser(page: Page, email: string, password: string) {
  function logOutUser (line 31) | async function logOutUser(page: Page) {
Condensed preview — 215 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (646K chars).
[
  {
    "path": ".copier/.copier-answers.yml.jinja",
    "chars": 31,
    "preview": "{{ _copier_answers|to_json -}}\n"
  },
  {
    "path": ".copier/update_dotenv.py",
    "chars": 977,
    "preview": "from pathlib import Path\nimport json\n\n# Update the .env file with the answers from the .copier-answers.yml file\n# withou"
  },
  {
    "path": ".gitattributes",
    "chars": 29,
    "preview": "* text=auto\n*.sh text eol=lf\n"
  },
  {
    "path": ".github/DISCUSSION_TEMPLATE/questions.yml",
    "chars": 4492,
    "preview": "labels: [question]\nbody:\n  - type: markdown\n    attributes:\n      value: |\n        Thanks for your interest in this proj"
  },
  {
    "path": ".github/FUNDING.yml",
    "chars": 19,
    "preview": "github: [tiangolo]\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/config.yml",
    "chars": 628,
    "preview": "blank_issues_enabled: false\ncontact_links:\n  - name: Security Contact\n    about: Please report security vulnerabilities "
  },
  {
    "path": ".github/ISSUE_TEMPLATE/privileged.yml",
    "chars": 908,
    "preview": "name: Privileged\ndescription: You are @tiangolo or he asked you directly to create an issue here. If not, check the othe"
  },
  {
    "path": ".github/dependabot.yml",
    "chars": 978,
    "preview": "version: 2\nupdates:\n  # GitHub Actions\n  - package-ecosystem: github-actions\n    directory: /\n    schedule:\n      interv"
  },
  {
    "path": ".github/labeler.yml",
    "chars": 548,
    "preview": "docs:\n  - all:\n    - changed-files:\n      - any-glob-to-any-file:\n        - '**/*.md'\n      - all-globs-to-all-files:\n  "
  },
  {
    "path": ".github/workflows/add-to-project.yml",
    "chars": 368,
    "preview": "name: Add to Project\n\non:\n  pull_request_target:\n  issues:\n    types:\n      - opened\n      - reopened\n\njobs:\n  add-to-pr"
  },
  {
    "path": ".github/workflows/deploy-production.yml",
    "chars": 1127,
    "preview": "name: Deploy to Production\n\non:\n  release:\n    types:\n      - published\n\njobs:\n  deploy:\n    # Do not deploy in the main"
  },
  {
    "path": ".github/workflows/deploy-staging.yml",
    "chars": 1103,
    "preview": "name: Deploy to Staging\n\non:\n  push:\n    branches:\n      - master\n\njobs:\n  deploy:\n    # Do not deploy in the main repos"
  },
  {
    "path": ".github/workflows/detect-conflicts.yml",
    "chars": 499,
    "preview": "name: \"Conflict detector\"\non:\n  push:\n  pull_request_target:\n    types: [synchronize]\n\njobs:\n  main:\n    permissions:\n  "
  },
  {
    "path": ".github/workflows/issue-manager.yml",
    "chars": 1865,
    "preview": "name: Issue Manager\n\non:\n  schedule:\n    - cron: \"21 17 * * *\"\n  issue_comment:\n    types:\n      - created\n  issues:\n   "
  },
  {
    "path": ".github/workflows/labeler.yml",
    "chars": 828,
    "preview": "name: Labels\non:\n  pull_request_target:\n    types:\n      - opened\n      - synchronize\n      - reopened\n      # For label"
  },
  {
    "path": ".github/workflows/latest-changes.yml",
    "chars": 1099,
    "preview": "name: Latest Changes\n\non:\n  pull_request_target:\n    branches:\n      - master\n    types:\n      - closed\n  workflow_dispa"
  },
  {
    "path": ".github/workflows/playwright.yml",
    "chars": 3796,
    "preview": "name: Playwright Tests\n\non:\n  push:\n    branches:\n    - master\n  pull_request:\n    types:\n    - opened\n    - synchronize"
  },
  {
    "path": ".github/workflows/pre-commit.yml",
    "chars": 3151,
    "preview": "name: pre-commit\n\non:\n  pull_request:\n    types:\n      - opened\n      - synchronize\n\nenv:\n  # Forks and Dependabot don't"
  },
  {
    "path": ".github/workflows/smokeshow.yml",
    "chars": 1027,
    "preview": "name: Smokeshow\n\non:\n  workflow_run:\n    workflows: [Test Backend]\n    types: [completed]\n\njobs:\n  smokeshow:\n    runs-o"
  },
  {
    "path": ".github/workflows/test-backend.yml",
    "chars": 1121,
    "preview": "name: Test Backend\n\non:\n  push:\n    branches:\n      - master\n  pull_request:\n    types:\n      - opened\n      - synchroni"
  },
  {
    "path": ".github/workflows/test-docker-compose.yml",
    "chars": 635,
    "preview": "name: Test Docker Compose\n\non:\n  push:\n    branches:\n      - master\n  pull_request:\n    types:\n      - opened\n      - sy"
  },
  {
    "path": ".gitignore",
    "chars": 118,
    "preview": ".vscode/*\n!.vscode/extensions.json\nnode_modules/\n/test-results/\n/playwright-report/\n/blob-report/\n/playwright/.cache/\n"
  },
  {
    "path": ".pre-commit-config.yaml",
    "chars": 1593,
    "preview": "# See https://pre-commit.com for more information\n# See https://pre-commit.com/hooks.html for more hooks\nrepos:\n  - repo"
  },
  {
    "path": ".vscode/extensions.json",
    "chars": 375,
    "preview": "{\n    \"recommendations\": [\n        \"FastAPILabs.fastapi-vscode\",\n        \"astral-sh.ty\",\n        \"biomejs.biome\",\n      "
  },
  {
    "path": "CONTRIBUTING.md",
    "chars": 2900,
    "preview": "# Contributing\n\nThank you for your interest in contributing to the Full Stack FastAPI Template! 🙇\n\n## Discussions First\n"
  },
  {
    "path": "LICENSE",
    "chars": 1074,
    "preview": "MIT License\n\nCopyright (c) 2019 Sebastián Ramírez\n\nPermission is hereby granted, free of charge, to any person obtaining"
  },
  {
    "path": "README.md",
    "chars": 8960,
    "preview": "# Full Stack FastAPI Template\n\n<a href=\"https://github.com/fastapi/full-stack-fastapi-template/actions?query=workflow%3A"
  },
  {
    "path": "SECURITY.md",
    "chars": 1096,
    "preview": "# Security Policy\n\nSecurity is very important for this project and its community. 🔒\n\nLearn more about it below. 👇\n\n## Ve"
  },
  {
    "path": "backend/.dockerignore",
    "chars": 76,
    "preview": "# Python\n__pycache__\napp.egg-info\n*.pyc\n.mypy_cache\n.coverage\nhtmlcov\n.venv\n"
  },
  {
    "path": "backend/.gitignore",
    "chars": 74,
    "preview": "__pycache__\napp.egg-info\n*.pyc\n.mypy_cache\n.coverage\nhtmlcov\n.cache\n.venv\n"
  },
  {
    "path": "backend/Dockerfile",
    "chars": 1471,
    "preview": "FROM python:3.10\n\nENV PYTHONUNBUFFERED=1\n\n# Install uv\n# Ref: https://docs.astral.sh/uv/guides/integration/docker/#insta"
  },
  {
    "path": "backend/README.md",
    "chars": 7715,
    "preview": "# FastAPI Project - Backend\n\n## Requirements\n\n* [Docker](https://www.docker.com/).\n* [uv](https://docs.astral.sh/uv/) fo"
  },
  {
    "path": "backend/alembic.ini",
    "chars": 1596,
    "preview": "# A generic, single database configuration.\n\n[alembic]\n# path to migration scripts\nscript_location = app/alembic\n\n# temp"
  },
  {
    "path": "backend/app/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "backend/app/alembic/README",
    "chars": 39,
    "preview": "Generic single-database configuration.\n"
  },
  {
    "path": "backend/app/alembic/env.py",
    "chars": 2285,
    "preview": "import os\nfrom logging.config import fileConfig\n\nfrom alembic import context\nfrom sqlalchemy import engine_from_config, "
  },
  {
    "path": "backend/app/alembic/script.py.mako",
    "chars": 523,
    "preview": "\"\"\"${message}\n\nRevision ID: ${up_revision}\nRevises: ${down_revision | comma,n}\nCreate Date: ${create_date}\n\n\"\"\"\nfrom ale"
  },
  {
    "path": "backend/app/alembic/versions/.keep",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "backend/app/alembic/versions/1a31ce608336_add_cascade_delete_relationships.py",
    "chars": 1110,
    "preview": "\"\"\"Add cascade delete relationships\n\nRevision ID: 1a31ce608336\nRevises: d98dd8ec85a3\nCreate Date: 2024-07-31 22:24:34.44"
  },
  {
    "path": "backend/app/alembic/versions/9c0a54914c78_add_max_length_for_string_varchar_.py",
    "chars": 2249,
    "preview": "\"\"\"Add max length for string(varchar) fields in User and Items models\n\nRevision ID: 9c0a54914c78\nRevises: e2412789c190\nC"
  },
  {
    "path": "backend/app/alembic/versions/d98dd8ec85a3_edit_replace_id_integers_in_all_models_.py",
    "chars": 3754,
    "preview": "\"\"\"Edit replace id integers in all models to use UUID instead\n\nRevision ID: d98dd8ec85a3\nRevises: 9c0a54914c78\nCreate Da"
  },
  {
    "path": "backend/app/alembic/versions/e2412789c190_initialize_models.py",
    "chars": 1728,
    "preview": "\"\"\"Initialize models\n\nRevision ID: e2412789c190\nRevises:\nCreate Date: 2023-11-24 22:55:43.195942\n\n\"\"\"\nimport sqlalchemy "
  },
  {
    "path": "backend/app/alembic/versions/fe56fa70289e_add_created_at_to_user_and_item.py",
    "chars": 852,
    "preview": "\"\"\"Add created_at to User and Item\n\nRevision ID: fe56fa70289e\nRevises: 1a31ce608336\nCreate Date: 2026-01-23 15:50:37.171"
  },
  {
    "path": "backend/app/api/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "backend/app/api/deps.py",
    "chars": 1725,
    "preview": "from collections.abc import Generator\nfrom typing import Annotated\n\nimport jwt\nfrom fastapi import Depends, HTTPExceptio"
  },
  {
    "path": "backend/app/api/main.py",
    "chars": 401,
    "preview": "from fastapi import APIRouter\n\nfrom app.api.routes import items, login, private, users, utils\nfrom app.core.config impor"
  },
  {
    "path": "backend/app/api/routes/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "backend/app/api/routes/items.py",
    "chars": 3368,
    "preview": "import uuid\nfrom typing import Any\n\nfrom fastapi import APIRouter, HTTPException\nfrom sqlmodel import col, func, select\n"
  },
  {
    "path": "backend/app/api/routes/login.py",
    "chars": 4088,
    "preview": "from datetime import timedelta\nfrom typing import Annotated, Any\n\nfrom fastapi import APIRouter, Depends, HTTPException\n"
  },
  {
    "path": "backend/app/api/routes/private.py",
    "chars": 777,
    "preview": "from typing import Any\n\nfrom fastapi import APIRouter\nfrom pydantic import BaseModel\n\nfrom app.api.deps import SessionDe"
  },
  {
    "path": "backend/app/api/routes/users.py",
    "chars": 6840,
    "preview": "import uuid\nfrom typing import Any\n\nfrom fastapi import APIRouter, Depends, HTTPException\nfrom sqlmodel import col, dele"
  },
  {
    "path": "backend/app/api/routes/utils.py",
    "chars": 783,
    "preview": "from fastapi import APIRouter, Depends\nfrom pydantic.networks import EmailStr\n\nfrom app.api.deps import get_current_acti"
  },
  {
    "path": "backend/app/backend_pre_start.py",
    "chars": 921,
    "preview": "import logging\n\nfrom sqlalchemy import Engine\nfrom sqlmodel import Session, select\nfrom tenacity import after_log, befor"
  },
  {
    "path": "backend/app/core/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "backend/app/core/config.py",
    "chars": 3665,
    "preview": "import secrets\nimport warnings\nfrom typing import Annotated, Any, Literal\n\nfrom pydantic import (\n    AnyUrl,\n    Before"
  },
  {
    "path": "backend/app/core/db.py",
    "chars": 1181,
    "preview": "from sqlmodel import Session, create_engine, select\n\nfrom app import crud\nfrom app.core.config import settings\nfrom app."
  },
  {
    "path": "backend/app/core/security.py",
    "chars": 921,
    "preview": "from datetime import datetime, timedelta, timezone\nfrom typing import Any\n\nimport jwt\nfrom pwdlib import PasswordHash\nfr"
  },
  {
    "path": "backend/app/crud.py",
    "chars": 2463,
    "preview": "import uuid\nfrom typing import Any\n\nfrom sqlmodel import Session, select\n\nfrom app.core.security import get_password_has"
  },
  {
    "path": "backend/app/email-templates/build/new_account.html",
    "chars": 5665,
    "preview": "<!doctype html><html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:o=\"urn:schemas-m"
  },
  {
    "path": "backend/app/email-templates/build/reset_password.html",
    "chars": 6392,
    "preview": "<!doctype html><html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:o=\"urn:schemas-m"
  },
  {
    "path": "backend/app/email-templates/build/test_email.html",
    "chars": 3860,
    "preview": "<!doctype html><html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:o=\"urn:schemas-m"
  },
  {
    "path": "backend/app/email-templates/src/new_account.mjml",
    "chars": 1337,
    "preview": "<mjml>\n  <mj-body background-color=\"#fafbfc\">\n    <mj-section background-color=\"#fff\" padding=\"40px 20px\">\n      <mj-col"
  },
  {
    "path": "backend/app/email-templates/src/reset_password.mjml",
    "chars": 1919,
    "preview": "<mjml>\n  <mj-body background-color=\"#fafbfc\">\n    <mj-section background-color=\"#fff\" padding=\"40px 20px\">\n      <mj-col"
  },
  {
    "path": "backend/app/email-templates/src/test_email.mjml",
    "chars": 623,
    "preview": "<mjml>\n  <mj-body background-color=\"#fafbfc\">\n    <mj-section background-color=\"#fff\" padding=\"40px 20px\">\n      <mj-col"
  },
  {
    "path": "backend/app/initial_data.py",
    "chars": 402,
    "preview": "import logging\n\nfrom sqlmodel import Session\n\nfrom app.core.db import engine, init_db\n\nlogging.basicConfig(level=logging"
  },
  {
    "path": "backend/app/main.py",
    "chars": 923,
    "preview": "import sentry_sdk\nfrom fastapi import FastAPI\nfrom fastapi.routing import APIRoute\nfrom starlette.middleware.cors import"
  },
  {
    "path": "backend/app/models.py",
    "chars": 3500,
    "preview": "import uuid\nfrom datetime import datetime, timezone\n\nfrom pydantic import EmailStr\nfrom sqlalchemy import DateTime\nfrom "
  },
  {
    "path": "backend/app/tests_pre_start.py",
    "chars": 917,
    "preview": "import logging\n\nfrom sqlalchemy import Engine\nfrom sqlmodel import Session, select\nfrom tenacity import after_log, befor"
  },
  {
    "path": "backend/app/utils.py",
    "chars": 3874,
    "preview": "import logging\nfrom dataclasses import dataclass\nfrom datetime import datetime, timedelta, timezone\nfrom pathlib import "
  },
  {
    "path": "backend/pyproject.toml",
    "chars": 1838,
    "preview": "[project]\nname = \"app\"\nversion = \"0.1.0\"\ndescription = \"\"\nrequires-python = \">=3.10,<4.0\"\ndependencies = [\n    \"fastapi["
  },
  {
    "path": "backend/scripts/format.sh",
    "chars": 74,
    "preview": "#!/bin/sh -e\nset -x\n\nruff check app scripts --fix\nruff format app scripts\n"
  },
  {
    "path": "backend/scripts/lint.sh",
    "chars": 84,
    "preview": "#!/usr/bin/env bash\n\nset -e\nset -x\n\nmypy app\nruff check app\nruff format app --check\n"
  },
  {
    "path": "backend/scripts/prestart.sh",
    "chars": 183,
    "preview": "#! /usr/bin/env bash\n\nset -e\nset -x\n\n# Let the DB start\npython app/backend_pre_start.py\n\n# Run migrations\nalembic upgrad"
  },
  {
    "path": "backend/scripts/test.sh",
    "chars": 120,
    "preview": "#!/usr/bin/env bash\n\nset -e\nset -x\n\ncoverage run -m pytest tests/\ncoverage report\ncoverage html --title \"${@-coverage}\"\n"
  },
  {
    "path": "backend/scripts/tests-start.sh",
    "chars": 93,
    "preview": "#! /usr/bin/env bash\nset -e\nset -x\n\npython app/tests_pre_start.py\n\nbash scripts/test.sh \"$@\"\n"
  },
  {
    "path": "backend/tests/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "backend/tests/api/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "backend/tests/api/routes/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "backend/tests/api/routes/test_items.py",
    "chars": 5165,
    "preview": "import uuid\n\nfrom fastapi.testclient import TestClient\nfrom sqlmodel import Session\n\nfrom app.core.config import setting"
  },
  {
    "path": "backend/tests/api/routes/test_login.py",
    "chars": 6140,
    "preview": "from unittest.mock import patch\n\nfrom fastapi.testclient import TestClient\nfrom pwdlib.hashers.bcrypt import BcryptHashe"
  },
  {
    "path": "backend/tests/api/routes/test_private.py",
    "chars": 659,
    "preview": "from fastapi.testclient import TestClient\nfrom sqlmodel import Session, select\n\nfrom app.core.config import settings\nfro"
  },
  {
    "path": "backend/tests/api/routes/test_users.py",
    "chars": 16867,
    "preview": "import uuid\nfrom unittest.mock import patch\n\nfrom fastapi.testclient import TestClient\nfrom sqlmodel import Session, sel"
  },
  {
    "path": "backend/tests/conftest.py",
    "chars": 1233,
    "preview": "from collections.abc import Generator\n\nimport pytest\nfrom fastapi.testclient import TestClient\nfrom sqlmodel import Sess"
  },
  {
    "path": "backend/tests/crud/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "backend/tests/crud/test_user.py",
    "chars": 4765,
    "preview": "from fastapi.encoders import jsonable_encoder\nfrom pwdlib.hashers.bcrypt import BcryptHasher\nfrom sqlmodel import Sessio"
  },
  {
    "path": "backend/tests/scripts/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "backend/tests/scripts/test_backend_pre_start.py",
    "chars": 939,
    "preview": "from unittest.mock import MagicMock, patch\n\nfrom sqlmodel import select\n\nfrom app.backend_pre_start import init, logger\n"
  },
  {
    "path": "backend/tests/scripts/test_test_pre_start.py",
    "chars": 933,
    "preview": "from unittest.mock import MagicMock, patch\n\nfrom sqlmodel import select\n\nfrom app.tests_pre_start import init, logger\n\n\n"
  },
  {
    "path": "backend/tests/utils/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "backend/tests/utils/item.py",
    "chars": 538,
    "preview": "from sqlmodel import Session\n\nfrom app import crud\nfrom app.models import Item, ItemCreate\nfrom tests.utils.user import "
  },
  {
    "path": "backend/tests/utils/user.py",
    "chars": 1664,
    "preview": "from fastapi.testclient import TestClient\nfrom sqlmodel import Session\n\nfrom app import crud\nfrom app.core.config import"
  },
  {
    "path": "backend/tests/utils/utils.py",
    "chars": 717,
    "preview": "import random\nimport string\n\nfrom fastapi.testclient import TestClient\n\nfrom app.core.config import settings\n\n\ndef rando"
  },
  {
    "path": "compose.override.yml",
    "chars": 3829,
    "preview": "services:\n\n  # Local services are available on their ports, but also available on:\n  # http://api.localhost.tiangolo.com"
  },
  {
    "path": "compose.traefik.yml",
    "chars": 3981,
    "preview": "services:\n  traefik:\n    image: traefik:3.6\n    ports:\n      # Listen on port 80, default for HTTP, necessary to redirec"
  },
  {
    "path": "compose.yml",
    "chars": 6551,
    "preview": "services:\n\n  db:\n    image: postgres:18\n    restart: always\n    healthcheck:\n      test: [\"CMD-SHELL\", \"pg_isready -U ${"
  },
  {
    "path": "copier.yml",
    "chars": 2118,
    "preview": "project_name:\n  type: str\n  help: The name of the project, shown to API users (in .env)\n  default: FastAPI Project\n\nstac"
  },
  {
    "path": "deployment.md",
    "chars": 12078,
    "preview": "# FastAPI Project - Deployment\n\nYou can deploy the project using Docker Compose to a remote server.\n\nThis project expect"
  },
  {
    "path": "development.md",
    "chars": 8452,
    "preview": "# FastAPI Project - Development\n\n## Docker Compose\n\n* Start the local stack with Docker Compose:\n\n```bash\ndocker compose"
  },
  {
    "path": "frontend/.dockerignore",
    "chars": 18,
    "preview": "node_modules\ndist\n"
  },
  {
    "path": "frontend/.gitignore",
    "chars": 354,
    "preview": "# Logs\nlogs\n*.log\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\npnpm-debug.log*\nlerna-debug.log*\n\nnode_modules\ndist\ndis"
  },
  {
    "path": "frontend/Dockerfile",
    "chars": 626,
    "preview": "# Stage 0, \"build-stage\", based on Bun, to build and compile the frontend\nFROM oven/bun:1 AS build-stage\n\nWORKDIR /app\n\n"
  },
  {
    "path": "frontend/Dockerfile.playwright",
    "chars": 391,
    "preview": "FROM mcr.microsoft.com/playwright:v1.58.2-noble\n\nWORKDIR /app\n\nRUN apt-get update && apt-get install -y unzip \\\n    && r"
  },
  {
    "path": "frontend/README.md",
    "chars": 3844,
    "preview": "# FastAPI Project - Frontend\n\nThe frontend is built with [Vite](https://vitejs.dev/), [React](https://reactjs.org/), [Ty"
  },
  {
    "path": "frontend/biome.json",
    "chars": 996,
    "preview": "{\n  \"$schema\": \"https://biomejs.dev/schemas/2.3.14/schema.json\",\n  \"assist\": { \"actions\": { \"source\": { \"organizeImports"
  },
  {
    "path": "frontend/components.json",
    "chars": 446,
    "preview": "{\n  \"$schema\": \"https://ui.shadcn.com/schema.json\",\n  \"style\": \"new-york\",\n  \"rsc\": false,\n  \"tsx\": true,\n  \"tailwind\": "
  },
  {
    "path": "frontend/index.html",
    "chars": 454,
    "preview": "<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"UTF-8\" />\n    <link rel=\"icon\" type=\"image/svg+xml\" href=\"/"
  },
  {
    "path": "frontend/nginx-backend-not-found.conf",
    "chars": 105,
    "preview": "location /api {\n    return 404;\n}\nlocation /docs {\n    return 404;\n}\nlocation /redoc {\n    return 404;\n}\n"
  },
  {
    "path": "frontend/nginx.conf",
    "chars": 188,
    "preview": "server {\n  listen 80;\n\n  location / {\n    root /usr/share/nginx/html;\n    index index.html index.htm;\n    try_files $uri"
  },
  {
    "path": "frontend/openapi-ts.config.ts",
    "chars": 813,
    "preview": "import { defineConfig } from \"@hey-api/openapi-ts\"\n\nexport default defineConfig({\n  input: \"./openapi.json\",\n  output: \""
  },
  {
    "path": "frontend/package.json",
    "chars": 2149,
    "preview": "{\n  \"name\": \"frontend\",\n  \"private\": true,\n  \"version\": \"0.0.0\",\n  \"type\": \"module\",\n  \"scripts\": {\n    \"dev\": \"vite\",\n "
  },
  {
    "path": "frontend/playwright.config.ts",
    "chars": 2480,
    "preview": "import { defineConfig, devices } from '@playwright/test';\nimport 'dotenv/config'\n\n/**\n * Read environment variables from"
  },
  {
    "path": "frontend/src/client/core/ApiError.ts",
    "chars": 611,
    "preview": "import type { ApiRequestOptions } from './ApiRequestOptions';\nimport type { ApiResult } from './ApiResult';\n\nexport clas"
  },
  {
    "path": "frontend/src/client/core/ApiRequestOptions.ts",
    "chars": 617,
    "preview": "export type ApiRequestOptions<T = unknown> = {\n\treadonly body?: any;\n\treadonly cookies?: Record<string, unknown>;\n\treado"
  },
  {
    "path": "frontend/src/client/core/ApiResult.ts",
    "chars": 166,
    "preview": "export type ApiResult<TData = any> = {\n\treadonly body: TData;\n\treadonly ok: boolean;\n\treadonly status: number;\n\treadonly"
  },
  {
    "path": "frontend/src/client/core/CancelablePromise.ts",
    "chars": 3258,
    "preview": "export class CancelError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = 'CancelError';\n"
  },
  {
    "path": "frontend/src/client/core/OpenAPI.ts",
    "chars": 1477,
    "preview": "import type { AxiosRequestConfig, AxiosResponse } from 'axios';\nimport type { ApiRequestOptions } from './ApiRequestOpti"
  },
  {
    "path": "frontend/src/client/core/request.ts",
    "chars": 9598,
    "preview": "import axios from 'axios';\nimport type { AxiosError, AxiosRequestConfig, AxiosResponse, AxiosInstance } from 'axios';\n\ni"
  },
  {
    "path": "frontend/src/client/index.ts",
    "chars": 290,
    "preview": "// This file is auto-generated by @hey-api/openapi-ts\nexport { ApiError } from './core/ApiError';\nexport { CancelablePro"
  },
  {
    "path": "frontend/src/client/schemas.gen.ts",
    "chars": 12475,
    "preview": "// This file is auto-generated by @hey-api/openapi-ts\n\nexport const Body_login_login_access_tokenSchema = {\n    properti"
  },
  {
    "path": "frontend/src/client/sdk.gen.ts",
    "chars": 14443,
    "preview": "// This file is auto-generated by @hey-api/openapi-ts\n\nimport type { CancelablePromise } from './core/CancelablePromise'"
  },
  {
    "path": "frontend/src/client/types.gen.ts",
    "chars": 4765,
    "preview": "// This file is auto-generated by @hey-api/openapi-ts\n\nexport type Body_login_login_access_token = {\n    grant_type?: (s"
  },
  {
    "path": "frontend/src/components/Admin/AddUser.tsx",
    "chars": 7314,
    "preview": "import { zodResolver } from \"@hookform/resolvers/zod\"\nimport { useMutation, useQueryClient } from \"@tanstack/react-query"
  },
  {
    "path": "frontend/src/components/Admin/DeleteUser.tsx",
    "chars": 2690,
    "preview": "import { useMutation, useQueryClient } from \"@tanstack/react-query\"\nimport { Trash2 } from \"lucide-react\"\nimport { useSt"
  },
  {
    "path": "frontend/src/components/Admin/EditUser.tsx",
    "chars": 7435,
    "preview": "import { zodResolver } from \"@hookform/resolvers/zod\"\nimport { useMutation, useQueryClient } from \"@tanstack/react-query"
  },
  {
    "path": "frontend/src/components/Admin/UserActionsMenu.tsx",
    "chars": 1115,
    "preview": "import { EllipsisVertical } from \"lucide-react\"\nimport { useState } from \"react\"\n\nimport type { UserPublic } from \"@/cli"
  },
  {
    "path": "frontend/src/components/Admin/columns.tsx",
    "chars": 2003,
    "preview": "import type { ColumnDef } from \"@tanstack/react-table\"\n\nimport type { UserPublic } from \"@/client\"\nimport { Badge } from"
  },
  {
    "path": "frontend/src/components/Common/Appearance.tsx",
    "chars": 3291,
    "preview": "import { Monitor, Moon, Sun } from \"lucide-react\"\n\nimport { type Theme, useTheme } from \"@/components/theme-provider\"\nim"
  },
  {
    "path": "frontend/src/components/Common/AuthLayout.tsx",
    "chars": 839,
    "preview": "import { Appearance } from \"@/components/Common/Appearance\"\nimport { Logo } from \"@/components/Common/Logo\"\nimport { Foo"
  },
  {
    "path": "frontend/src/components/Common/DataTable.tsx",
    "chars": 6287,
    "preview": "import {\n  type ColumnDef,\n  flexRender,\n  getCoreRowModel,\n  getPaginationRowModel,\n  useReactTable,\n} from \"@tanstack/"
  },
  {
    "path": "frontend/src/components/Common/ErrorComponent.tsx",
    "chars": 845,
    "preview": "import { Link } from \"@tanstack/react-router\"\nimport { Button } from \"@/components/ui/button\"\n\nconst ErrorComponent = ()"
  },
  {
    "path": "frontend/src/components/Common/Footer.tsx",
    "chars": 1240,
    "preview": "import { FaGithub, FaLinkedinIn } from \"react-icons/fa\"\nimport { FaXTwitter } from \"react-icons/fa6\"\n\nconst socialLinks "
  },
  {
    "path": "frontend/src/components/Common/Logo.tsx",
    "chars": 1474,
    "preview": "import { Link } from \"@tanstack/react-router\"\n\nimport { useTheme } from \"@/components/theme-provider\"\nimport { cn } from"
  },
  {
    "path": "frontend/src/components/Common/NotFound.tsx",
    "chars": 894,
    "preview": "import { Link } from \"@tanstack/react-router\"\nimport { Button } from \"@/components/ui/button\"\n\nconst NotFound = () => {\n"
  },
  {
    "path": "frontend/src/components/Items/AddItem.tsx",
    "chars": 4097,
    "preview": "import { zodResolver } from \"@hookform/resolvers/zod\"\nimport { useMutation, useQueryClient } from \"@tanstack/react-query"
  },
  {
    "path": "frontend/src/components/Items/DeleteItem.tsx",
    "chars": 2619,
    "preview": "import { useMutation, useQueryClient } from \"@tanstack/react-query\"\nimport { Trash2 } from \"lucide-react\"\nimport { useSt"
  },
  {
    "path": "frontend/src/components/Items/EditItem.tsx",
    "chars": 4210,
    "preview": "import { zodResolver } from \"@hookform/resolvers/zod\"\nimport { useMutation, useQueryClient } from \"@tanstack/react-query"
  },
  {
    "path": "frontend/src/components/Items/ItemActionsMenu.tsx",
    "chars": 991,
    "preview": "import { EllipsisVertical } from \"lucide-react\"\nimport { useState } from \"react\"\n\nimport type { ItemPublic } from \"@/cli"
  },
  {
    "path": "frontend/src/components/Items/columns.tsx",
    "chars": 1939,
    "preview": "import type { ColumnDef } from \"@tanstack/react-table\"\nimport { Check, Copy } from \"lucide-react\"\n\nimport type { ItemPub"
  },
  {
    "path": "frontend/src/components/Pending/PendingItems.tsx",
    "chars": 1125,
    "preview": "import { Skeleton } from \"@/components/ui/skeleton\"\nimport {\n  Table,\n  TableBody,\n  TableCell,\n  TableHead,\n  TableHead"
  },
  {
    "path": "frontend/src/components/Pending/PendingUsers.tsx",
    "chars": 1391,
    "preview": "import { Skeleton } from \"@/components/ui/skeleton\"\nimport {\n  Table,\n  TableBody,\n  TableCell,\n  TableHead,\n  TableHead"
  },
  {
    "path": "frontend/src/components/Sidebar/AppSidebar.tsx",
    "chars": 1187,
    "preview": "import { Briefcase, Home, Users } from \"lucide-react\"\n\nimport { SidebarAppearance } from \"@/components/Common/Appearance"
  },
  {
    "path": "frontend/src/components/Sidebar/Main.tsx",
    "chars": 1415,
    "preview": "import { Link as RouterLink, useRouterState } from \"@tanstack/react-router\"\nimport type { LucideIcon } from \"lucide-reac"
  },
  {
    "path": "frontend/src/components/Sidebar/User.tsx",
    "chars": 2922,
    "preview": "import { Link as RouterLink } from \"@tanstack/react-router\"\nimport { ChevronsUpDown, LogOut, Settings } from \"lucide-rea"
  },
  {
    "path": "frontend/src/components/UserSettings/ChangePassword.tsx",
    "chars": 4256,
    "preview": "import { zodResolver } from \"@hookform/resolvers/zod\"\nimport { useMutation } from \"@tanstack/react-query\"\nimport { useFo"
  },
  {
    "path": "frontend/src/components/UserSettings/DeleteAccount.tsx",
    "chars": 458,
    "preview": "import DeleteConfirmation from \"./DeleteConfirmation\"\n\nconst DeleteAccount = () => {\n  return (\n    <div className=\"max-"
  },
  {
    "path": "frontend/src/components/UserSettings/DeleteConfirmation.tsx",
    "chars": 2366,
    "preview": "import { useMutation, useQueryClient } from \"@tanstack/react-query\"\nimport { useForm } from \"react-hook-form\"\n\nimport { "
  },
  {
    "path": "frontend/src/components/UserSettings/UserInformation.tsx",
    "chars": 4765,
    "preview": "import { zodResolver } from \"@hookform/resolvers/zod\"\nimport { useMutation, useQueryClient } from \"@tanstack/react-query"
  },
  {
    "path": "frontend/src/components/theme-provider.tsx",
    "chars": 2600,
    "preview": "import {\n  createContext,\n  useCallback,\n  useContext,\n  useEffect,\n  useState,\n} from \"react\"\n\nexport type Theme = \"dar"
  },
  {
    "path": "frontend/src/components/ui/alert.tsx",
    "chars": 1614,
    "preview": "import * as React from \"react\"\nimport { cva, type VariantProps } from \"class-variance-authority\"\n\nimport { cn } from \"@/"
  },
  {
    "path": "frontend/src/components/ui/avatar.tsx",
    "chars": 1083,
    "preview": "import * as React from \"react\"\nimport * as AvatarPrimitive from \"@radix-ui/react-avatar\"\n\nimport { cn } from \"@/lib/util"
  },
  {
    "path": "frontend/src/components/ui/badge.tsx",
    "chars": 1633,
    "preview": "import * as React from \"react\"\nimport { Slot } from \"@radix-ui/react-slot\"\nimport { cva, type VariantProps } from \"class"
  },
  {
    "path": "frontend/src/components/ui/button-group.tsx",
    "chars": 2209,
    "preview": "import { Slot } from \"@radix-ui/react-slot\"\nimport { cva, type VariantProps } from \"class-variance-authority\"\n\nimport { "
  },
  {
    "path": "frontend/src/components/ui/button.tsx",
    "chars": 2142,
    "preview": "import * as React from \"react\"\nimport { Slot } from \"@radix-ui/react-slot\"\nimport { cva, type VariantProps } from \"class"
  },
  {
    "path": "frontend/src/components/ui/card.tsx",
    "chars": 1987,
    "preview": "import * as React from \"react\"\n\nimport { cn } from \"@/lib/utils\"\n\nfunction Card({ className, ...props }: React.Component"
  },
  {
    "path": "frontend/src/components/ui/checkbox.tsx",
    "chars": 1205,
    "preview": "import * as React from \"react\"\nimport * as CheckboxPrimitive from \"@radix-ui/react-checkbox\"\nimport { CheckIcon } from \""
  },
  {
    "path": "frontend/src/components/ui/dialog.tsx",
    "chars": 3968,
    "preview": "import * as React from \"react\"\nimport * as DialogPrimitive from \"@radix-ui/react-dialog\"\nimport { XIcon } from \"lucide-r"
  },
  {
    "path": "frontend/src/components/ui/dropdown-menu.tsx",
    "chars": 8284,
    "preview": "\"use client\"\n\nimport * as React from \"react\"\nimport * as DropdownMenuPrimitive from \"@radix-ui/react-dropdown-menu\"\nimpo"
  },
  {
    "path": "frontend/src/components/ui/form.tsx",
    "chars": 3745,
    "preview": "import * as React from \"react\"\nimport * as LabelPrimitive from \"@radix-ui/react-label\"\nimport { Slot } from \"@radix-ui/r"
  },
  {
    "path": "frontend/src/components/ui/input.tsx",
    "chars": 962,
    "preview": "import * as React from \"react\"\n\nimport { cn } from \"@/lib/utils\"\n\nfunction Input({ className, type, ...props }: React.Co"
  },
  {
    "path": "frontend/src/components/ui/label.tsx",
    "chars": 611,
    "preview": "\"use client\"\n\nimport * as React from \"react\"\nimport * as LabelPrimitive from \"@radix-ui/react-label\"\n\nimport { cn } from"
  },
  {
    "path": "frontend/src/components/ui/loading-button.tsx",
    "chars": 2410,
    "preview": "import { Slot, Slottable } from \"@radix-ui/react-slot\"\nimport { cva, type VariantProps } from \"class-variance-authority\""
  },
  {
    "path": "frontend/src/components/ui/pagination.tsx",
    "chars": 2712,
    "preview": "import * as React from \"react\"\nimport {\n  ChevronLeftIcon,\n  ChevronRightIcon,\n  MoreHorizontalIcon,\n} from \"lucide-reac"
  },
  {
    "path": "frontend/src/components/ui/password-input.tsx",
    "chars": 1994,
    "preview": "import * as React from \"react\"\nimport { Eye, EyeOff } from \"lucide-react\"\n\nimport { cn } from \"@/lib/utils\"\nimport { But"
  },
  {
    "path": "frontend/src/components/ui/select.tsx",
    "chars": 6281,
    "preview": "import * as React from \"react\"\nimport * as SelectPrimitive from \"@radix-ui/react-select\"\nimport { CheckIcon, ChevronDown"
  },
  {
    "path": "frontend/src/components/ui/separator.tsx",
    "chars": 685,
    "preview": "import * as React from \"react\"\nimport * as SeparatorPrimitive from \"@radix-ui/react-separator\"\n\nimport { cn } from \"@/li"
  },
  {
    "path": "frontend/src/components/ui/sheet.tsx",
    "chars": 4090,
    "preview": "\"use client\"\n\nimport * as React from \"react\"\nimport * as SheetPrimitive from \"@radix-ui/react-dialog\"\nimport { XIcon } f"
  },
  {
    "path": "frontend/src/components/ui/sidebar.tsx",
    "chars": 22059,
    "preview": "import { Slot } from \"@radix-ui/react-slot\"\nimport { cva, type VariantProps } from \"class-variance-authority\"\nimport { P"
  },
  {
    "path": "frontend/src/components/ui/skeleton.tsx",
    "chars": 276,
    "preview": "import { cn } from \"@/lib/utils\"\n\nfunction Skeleton({ className, ...props }: React.ComponentProps<\"div\">) {\n  return (\n "
  },
  {
    "path": "frontend/src/components/ui/sonner.tsx",
    "chars": 1034,
    "preview": "\"use client\"\n\nimport {\n  CircleCheckIcon,\n  InfoIcon,\n  Loader2Icon,\n  OctagonXIcon,\n  TriangleAlertIcon,\n} from \"lucide"
  },
  {
    "path": "frontend/src/components/ui/table.tsx",
    "chars": 2511,
    "preview": "import * as React from \"react\"\n\nimport { cn } from \"@/lib/utils\"\n\nfunction Table({ className, ...props }: React.Componen"
  },
  {
    "path": "frontend/src/components/ui/tabs.tsx",
    "chars": 1955,
    "preview": "import * as React from \"react\"\nimport * as TabsPrimitive from \"@radix-ui/react-tabs\"\n\nimport { cn } from \"@/lib/utils\"\n\n"
  },
  {
    "path": "frontend/src/components/ui/tooltip.tsx",
    "chars": 1878,
    "preview": "import * as React from \"react\"\nimport * as TooltipPrimitive from \"@radix-ui/react-tooltip\"\n\nimport { cn } from \"@/lib/ut"
  },
  {
    "path": "frontend/src/hooks/useAuth.ts",
    "chars": 1708,
    "preview": "import { useMutation, useQuery, useQueryClient } from \"@tanstack/react-query\"\nimport { useNavigate } from \"@tanstack/rea"
  },
  {
    "path": "frontend/src/hooks/useCopyToClipboard.ts",
    "chars": 794,
    "preview": "// source: https://usehooks-ts.com/react-hook/use-copy-to-clipboard\nimport { useCallback, useState } from \"react\"\n\ntype "
  },
  {
    "path": "frontend/src/hooks/useCustomToast.ts",
    "chars": 385,
    "preview": "import { toast } from \"sonner\"\n\nconst useCustomToast = () => {\n  const showSuccessToast = (description: string) => {\n   "
  },
  {
    "path": "frontend/src/hooks/useMobile.ts",
    "chars": 565,
    "preview": "import * as React from \"react\"\n\nconst MOBILE_BREAKPOINT = 768\n\nexport function useIsMobile() {\n  const [isMobile, setIsM"
  },
  {
    "path": "frontend/src/index.css",
    "chars": 4187,
    "preview": "@import \"tailwindcss\";\n@import \"tw-animate-css\";\n\n@custom-variant dark (&:is(.dark *));\n\n@theme inline {\n  --radius-sm: "
  },
  {
    "path": "frontend/src/lib/utils.ts",
    "chars": 166,
    "preview": "import { type ClassValue, clsx } from \"clsx\"\nimport { twMerge } from \"tailwind-merge\"\n\nexport function cn(...inputs: Cla"
  },
  {
    "path": "frontend/src/main.tsx",
    "chars": 1473,
    "preview": "import {\n  MutationCache,\n  QueryCache,\n  QueryClient,\n  QueryClientProvider,\n} from \"@tanstack/react-query\"\nimport { cr"
  },
  {
    "path": "frontend/src/routeTree.gen.ts",
    "chars": 7038,
    "preview": "/* eslint-disable */\n\n// @ts-nocheck\n\n// noinspection JSUnusedGlobalSymbols\n\n// This file was automatically generated by"
  },
  {
    "path": "frontend/src/routes/__root.tsx",
    "chars": 651,
    "preview": "import { ReactQueryDevtools } from \"@tanstack/react-query-devtools\"\nimport { createRootRoute, HeadContent, Outlet } from"
  },
  {
    "path": "frontend/src/routes/_layout/admin.tsx",
    "chars": 1879,
    "preview": "import { useSuspenseQuery } from \"@tanstack/react-query\"\nimport { createFileRoute, redirect } from \"@tanstack/react-rout"
  },
  {
    "path": "frontend/src/routes/_layout/index.tsx",
    "chars": 649,
    "preview": "import { createFileRoute } from \"@tanstack/react-router\"\n\nimport useAuth from \"@/hooks/useAuth\"\n\nexport const Route = cr"
  },
  {
    "path": "frontend/src/routes/_layout/items.tsx",
    "chars": 1895,
    "preview": "import { useSuspenseQuery } from \"@tanstack/react-query\"\nimport { createFileRoute } from \"@tanstack/react-router\"\nimport"
  },
  {
    "path": "frontend/src/routes/_layout/settings.tsx",
    "chars": 1735,
    "preview": "import { createFileRoute } from \"@tanstack/react-router\"\n\nimport ChangePassword from \"@/components/UserSettings/ChangePa"
  },
  {
    "path": "frontend/src/routes/_layout.tsx",
    "chars": 1041,
    "preview": "import { createFileRoute, Outlet, redirect } from \"@tanstack/react-router\"\n\nimport { Footer } from \"@/components/Common/"
  },
  {
    "path": "frontend/src/routes/login.tsx",
    "chars": 3950,
    "preview": "import { zodResolver } from \"@hookform/resolvers/zod\"\nimport {\n  createFileRoute,\n  Link as RouterLink,\n  redirect,\n} fr"
  },
  {
    "path": "frontend/src/routes/recover-password.tsx",
    "chars": 3288,
    "preview": "import { zodResolver } from \"@hookform/resolvers/zod\"\nimport { useMutation } from \"@tanstack/react-query\"\nimport {\n  cre"
  },
  {
    "path": "frontend/src/routes/reset-password.tsx",
    "chars": 4576,
    "preview": "import { zodResolver } from \"@hookform/resolvers/zod\"\nimport { useMutation } from \"@tanstack/react-query\"\nimport {\n  cre"
  },
  {
    "path": "frontend/src/routes/signup.tsx",
    "chars": 5223,
    "preview": "import { zodResolver } from \"@hookform/resolvers/zod\"\nimport {\n  createFileRoute,\n  Link as RouterLink,\n  redirect,\n} fr"
  },
  {
    "path": "frontend/src/utils.ts",
    "chars": 706,
    "preview": "import { AxiosError } from \"axios\"\nimport type { ApiError } from \"./client\"\n\nfunction extractErrorMessage(err: ApiError)"
  },
  {
    "path": "frontend/src/vite-env.d.ts",
    "chars": 155,
    "preview": "/// <reference types=\"vite/client\" />\n\ninterface ImportMetaEnv {\n  readonly VITE_API_URL: string\n}\n\ninterface ImportMeta"
  },
  {
    "path": "frontend/tests/admin.spec.ts",
    "chars": 7198,
    "preview": "import { expect, test } from \"@playwright/test\"\nimport { firstSuperuser, firstSuperuserPassword } from \"./config.ts\"\nimp"
  },
  {
    "path": "frontend/tests/auth.setup.ts",
    "chars": 520,
    "preview": "import { test as setup } from \"@playwright/test\"\nimport { firstSuperuser, firstSuperuserPassword } from \"./config.ts\"\n\nc"
  },
  {
    "path": "frontend/tests/config.ts",
    "chars": 569,
    "preview": "import path from \"node:path\"\nimport { fileURLToPath } from \"node:url\"\nimport dotenv from \"dotenv\"\n\nconst __filename = fi"
  },
  {
    "path": "frontend/tests/items.spec.ts",
    "chars": 4676,
    "preview": "import { expect, test } from \"@playwright/test\"\nimport { createUser } from \"./utils/privateApi\"\nimport {\n  randomEmail,\n"
  },
  {
    "path": "frontend/tests/login.spec.ts",
    "chars": 3479,
    "preview": "import { expect, type Page, test } from \"@playwright/test\"\nimport { firstSuperuser, firstSuperuserPassword } from \"./con"
  },
  {
    "path": "frontend/tests/reset-password.spec.ts",
    "chars": 3986,
    "preview": "import { expect, test } from \"@playwright/test\"\nimport { findLastEmail } from \"./utils/mailcatcher\"\nimport { randomEmail"
  },
  {
    "path": "frontend/tests/sign-up.spec.ts",
    "chars": 4551,
    "preview": "import { expect, type Page, test } from \"@playwright/test\"\n\nimport { randomEmail, randomPassword } from \"./utils/random\""
  },
  {
    "path": "frontend/tests/user-settings.spec.ts",
    "chars": 8628,
    "preview": "import { expect, test } from \"@playwright/test\"\nimport { firstSuperuser, firstSuperuserPassword } from \"./config.ts\"\nimp"
  }
]

// ... and 15 more files (download for full content)

About this extraction

This page contains the full source code of the fastapi/full-stack-fastapi-template GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 215 files (593.3 KB), approximately 162.1k tokens, and a symbol index with 486 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!