From ed1a7235df8eed75f6da1d89ca50be629c14b64b Mon Sep 17 00:00:00 2001 From: Phil Leggetter Date: Wed, 22 Apr 2026 19:12:00 +0100 Subject: [PATCH 01/12] feat(outpost): add SaaS examples, CI tests, and skill integration maps - Add full-stack Next.js and FastAPI+React reference apps under skills/outpost/examples - Add integration maps under skills/outpost/references for progressive disclosure - Extend outpost SKILL.md with example pointers and testing notes - Wire test-examples.sh and GitHub Actions for outpost SaaS examples - Document outpost example testing in TESTING.md and CONTRIBUTING.md - Adjust .gitignore for example lockfiles and artifacts Made-with: Cursor --- .github/workflows/test-examples.yml | 24 +- .gitignore | 4 + CONTRIBUTING.md | 6 + TESTING.md | 10 +- scripts/test-examples.sh | 96 +- skills/outpost/SKILL.md | 18 + .../.copier/.copier-answers.yml.jinja | 1 + .../fastapi-saas/.copier/update_dotenv.py | 26 + .../examples/fastapi-saas/.gitattributes | 2 + .../.github/DISCUSSION_TEMPLATE/questions.yml | 118 +++ .../examples/fastapi-saas/.github/FUNDING.yml | 1 + .../.github/ISSUE_TEMPLATE/config.yml | 10 + .../.github/ISSUE_TEMPLATE/privileged.yml | 22 + .../fastapi-saas/.github/dependabot.yml | 46 + .../examples/fastapi-saas/.github/labeler.yml | 25 + .../.github/workflows/add-to-project.yml | 18 + .../.github/workflows/deploy-production.yml | 32 + .../.github/workflows/deploy-staging.yml | 32 + .../.github/workflows/detect-conflicts.yml | 19 + .../.github/workflows/issue-manager.yml | 55 ++ .../.github/workflows/labeler.yml | 33 + .../.github/workflows/latest-changes.yml | 40 + .../.github/workflows/playwright.yml | 121 +++ .../.github/workflows/pre-commit.yml | 94 ++ .../.github/workflows/smokeshow.yml | 34 + .../.github/workflows/test-backend.yml | 41 + .../.github/workflows/test-docker-compose.yml | 26 + .../outpost/examples/fastapi-saas/.gitignore | 7 + .../fastapi-saas/.pre-commit-config.yaml | 69 ++ .../examples/fastapi-saas/CONTRIBUTING.md | 65 ++ skills/outpost/examples/fastapi-saas/LICENSE | 21 + .../outpost/examples/fastapi-saas/README.md | 235 +++++ .../outpost/examples/fastapi-saas/SECURITY.md | 29 + .../fastapi-saas/backend/.dockerignore | 8 + .../examples/fastapi-saas/backend/.gitignore | 8 + .../examples/fastapi-saas/backend/Dockerfile | 45 + .../examples/fastapi-saas/backend/README.md | 172 ++++ .../examples/fastapi-saas/backend/alembic.ini | 71 ++ .../fastapi-saas/backend/app/__init__.py | 0 .../fastapi-saas/backend/app/alembic/README | 1 + .../fastapi-saas/backend/app/alembic/env.py | 86 ++ .../backend/app/alembic/script.py.mako | 25 + .../backend/app/alembic/versions/.keep | 0 ...608336_add_cascade_delete_relationships.py | 37 + ...4c78_add_max_length_for_string_varchar_.py | 69 ++ ...edit_replace_id_integers_in_all_models_.py | 90 ++ .../e2412789c190_initialize_models.py | 54 ++ ...a70289e_add_created_at_to_user_and_item.py | 31 + .../fastapi-saas/backend/app/api/__init__.py | 0 .../fastapi-saas/backend/app/api/deps.py | 57 ++ .../fastapi-saas/backend/app/api/main.py | 15 + .../backend/app/api/routes/__init__.py | 0 .../backend/app/api/routes/items.py | 113 +++ .../backend/app/api/routes/login.py | 123 +++ .../backend/app/api/routes/outpost.py | 319 +++++++ .../backend/app/api/routes/private.py | 38 + .../backend/app/api/routes/users.py | 281 ++++++ .../backend/app/api/routes/utils.py | 31 + .../backend/app/backend_pre_start.py | 39 + .../fastapi-saas/backend/app/core/__init__.py | 0 .../fastapi-saas/backend/app/core/config.py | 123 +++ .../fastapi-saas/backend/app/core/db.py | 33 + .../fastapi-saas/backend/app/core/security.py | 36 + .../examples/fastapi-saas/backend/app/crud.py | 68 ++ .../app/email-templates/src/new_account.mjml | 15 + .../email-templates/src/reset_password.mjml | 17 + .../app/email-templates/src/test_email.mjml | 11 + .../fastapi-saas/backend/app/initial_data.py | 23 + .../examples/fastapi-saas/backend/app/main.py | 33 + .../fastapi-saas/backend/app/models.py | 129 +++ .../backend/app/tests_pre_start.py | 39 + .../fastapi-saas/backend/app/utils.py | 123 +++ .../fastapi-saas/backend/pyproject.toml | 82 ++ .../fastapi-saas/backend/scripts/format.sh | 5 + .../fastapi-saas/backend/scripts/lint.sh | 9 + .../fastapi-saas/backend/scripts/prestart.sh | 13 + .../fastapi-saas/backend/scripts/test.sh | 8 + .../backend/scripts/tests-start.sh | 7 + .../fastapi-saas/backend/test_outpost_wire.py | 42 + .../fastapi-saas/backend/tests/__init__.py | 0 .../backend/tests/api/__init__.py | 0 .../backend/tests/api/routes/__init__.py | 0 .../backend/tests/api/routes/test_items.py | 164 ++++ .../backend/tests/api/routes/test_login.py | 191 ++++ .../backend/tests/api/routes/test_private.py | 26 + .../backend/tests/api/routes/test_users.py | 521 +++++++++++ .../fastapi-saas/backend/tests/conftest.py | 42 + .../backend/tests/crud/__init__.py | 0 .../backend/tests/crud/test_user.py | 130 +++ .../backend/tests/scripts/__init__.py | 0 .../tests/scripts/test_backend_pre_start.py | 33 + .../tests/scripts/test_test_pre_start.py | 33 + .../backend/tests/utils/__init__.py | 0 .../fastapi-saas/backend/tests/utils/item.py | 16 + .../fastapi-saas/backend/tests/utils/user.py | 49 + .../fastapi-saas/backend/tests/utils/utils.py | 26 + .../fastapi-saas/compose.override.yml | 136 +++ .../examples/fastapi-saas/compose.traefik.yml | 77 ++ .../outpost/examples/fastapi-saas/compose.yml | 174 ++++ .../outpost/examples/fastapi-saas/copier.yml | 100 ++ .../examples/fastapi-saas/deployment.md | 344 +++++++ .../examples/fastapi-saas/development.md | 221 +++++ .../fastapi-saas/frontend/.dockerignore | 2 + .../examples/fastapi-saas/frontend/.gitignore | 30 + .../examples/fastapi-saas/frontend/Dockerfile | 26 + .../frontend/Dockerfile.playwright | 21 + .../examples/fastapi-saas/frontend/README.md | 121 +++ .../examples/fastapi-saas/frontend/biome.json | 46 + .../fastapi-saas/frontend/components.json | 22 + .../examples/fastapi-saas/frontend/index.html | 14 + .../frontend/nginx-backend-not-found.conf | 9 + .../examples/fastapi-saas/frontend/nginx.conf | 11 + .../frontend/openapi-ts.config.ts | 33 + .../fastapi-saas/frontend/package.json | 66 ++ .../frontend/playwright.config.ts | 91 ++ .../assets/images/fastapi-icon-light.svg | 77 ++ .../public/assets/images/fastapi-icon.svg | 77 ++ .../assets/images/fastapi-logo-light.svg | 83 ++ .../public/assets/images/fastapi-logo.svg | 91 ++ .../frontend/public/assets/images/favicon.png | Bin 0 -> 5043 bytes .../frontend/src/client/core/ApiError.ts | 21 + .../src/client/core/ApiRequestOptions.ts | 21 + .../frontend/src/client/core/ApiResult.ts | 7 + .../src/client/core/CancelablePromise.ts | 126 +++ .../frontend/src/client/core/OpenAPI.ts | 57 ++ .../frontend/src/client/core/request.ts | 347 +++++++ .../fastapi-saas/frontend/src/client/index.ts | 6 + .../frontend/src/client/schemas.gen.ts | 559 ++++++++++++ .../frontend/src/client/sdk.gen.ts | 468 ++++++++++ .../frontend/src/client/types.gen.ts | 240 +++++ .../frontend/src/components/Admin/AddUser.tsx | 238 +++++ .../src/components/Admin/DeleteUser.tsx | 95 ++ .../src/components/Admin/EditUser.tsx | 239 +++++ .../src/components/Admin/UserActionsMenu.tsx | 40 + .../frontend/src/components/Admin/columns.tsx | 76 ++ .../src/components/Common/Appearance.tsx | 105 +++ .../src/components/Common/AuthLayout.tsx | 26 + .../src/components/Common/DataTable.tsx | 194 ++++ .../src/components/Common/ErrorComponent.tsx | 29 + .../frontend/src/components/Common/Footer.tsx | 44 + .../frontend/src/components/Common/Logo.tsx | 60 ++ .../src/components/Common/NotFound.tsx | 31 + .../Destinations/CreateDestination.tsx | 451 +++++++++ .../frontend/src/components/Items/AddItem.tsx | 144 +++ .../src/components/Items/DeleteItem.tsx | 94 ++ .../src/components/Items/EditItem.tsx | 145 +++ .../src/components/Items/ItemActionsMenu.tsx | 34 + .../frontend/src/components/Items/columns.tsx | 73 ++ .../src/components/Pending/PendingItems.tsx | 46 + .../src/components/Pending/PendingUsers.tsx | 53 ++ .../src/components/Sidebar/AppSidebar.tsx | 44 + .../frontend/src/components/Sidebar/Main.tsx | 64 ++ .../frontend/src/components/Sidebar/User.tsx | 97 ++ .../UserSettings/ChangePassword.tsx | 146 +++ .../components/UserSettings/DeleteAccount.tsx | 15 + .../UserSettings/DeleteConfirmation.tsx | 82 ++ .../UserSettings/UserInformation.tsx | 171 ++++ .../src/components/theme-provider.tsx | 115 +++ .../frontend/src/components/ui/alert.tsx | 66 ++ .../frontend/src/components/ui/avatar.tsx | 51 ++ .../frontend/src/components/ui/badge.tsx | 46 + .../src/components/ui/button-group.tsx | 83 ++ .../frontend/src/components/ui/button.tsx | 60 ++ .../frontend/src/components/ui/card.tsx | 92 ++ .../frontend/src/components/ui/checkbox.tsx | 30 + .../frontend/src/components/ui/dialog.tsx | 141 +++ .../src/components/ui/dropdown-menu.tsx | 257 ++++++ .../frontend/src/components/ui/form.tsx | 165 ++++ .../frontend/src/components/ui/input.tsx | 21 + .../frontend/src/components/ui/label.tsx | 24 + .../src/components/ui/loading-button.tsx | 67 ++ .../frontend/src/components/ui/pagination.tsx | 127 +++ .../src/components/ui/password-input.tsx | 51 ++ .../frontend/src/components/ui/select.tsx | 185 ++++ .../frontend/src/components/ui/separator.tsx | 26 + .../frontend/src/components/ui/sheet.tsx | 139 +++ .../frontend/src/components/ui/sidebar.tsx | 737 +++++++++++++++ .../frontend/src/components/ui/skeleton.tsx | 13 + .../frontend/src/components/ui/sonner.tsx | 40 + .../frontend/src/components/ui/table.tsx | 114 +++ .../frontend/src/components/ui/tabs.tsx | 64 ++ .../frontend/src/components/ui/tooltip.tsx | 59 ++ .../frontend/src/hooks/useAuth.ts | 70 ++ .../frontend/src/hooks/useCopyToClipboard.ts | 32 + .../frontend/src/hooks/useCustomToast.ts | 19 + .../frontend/src/hooks/useMobile.ts | 19 + .../fastapi-saas/frontend/src/index.css | 124 +++ .../frontend/src/lib/outpost-api.ts | 206 +++++ .../fastapi-saas/frontend/src/lib/utils.ts | 6 + .../fastapi-saas/frontend/src/main.tsx | 52 ++ .../frontend/src/routeTree.gen.ts | 310 +++++++ .../frontend/src/routes/__root.tsx | 18 + .../frontend/src/routes/_layout.tsx | 42 + .../frontend/src/routes/_layout/admin.tsx | 73 ++ .../destinations/$destinationId/activity.tsx | 303 ++++++ .../src/routes/_layout/destinations/index.tsx | 356 ++++++++ .../src/routes/_layout/destinations/route.tsx | 6 + .../frontend/src/routes/_layout/index.tsx | 31 + .../frontend/src/routes/_layout/items.tsx | 69 ++ .../frontend/src/routes/_layout/settings.tsx | 61 ++ .../frontend/src/routes/login.tsx | 142 +++ .../frontend/src/routes/recover-password.tsx | 130 +++ .../frontend/src/routes/reset-password.tsx | 166 ++++ .../frontend/src/routes/signup.tsx | 189 ++++ .../fastapi-saas/frontend/src/utils.ts | 31 + .../fastapi-saas/frontend/src/vite-env.d.ts | 9 + .../fastapi-saas/frontend/tests/admin.spec.ts | 205 +++++ .../fastapi-saas/frontend/tests/auth.setup.ts | 13 + .../fastapi-saas/frontend/tests/config.ts | 19 + .../fastapi-saas/frontend/tests/items.spec.ts | 132 +++ .../fastapi-saas/frontend/tests/login.spec.ts | 117 +++ .../frontend/tests/reset-password.spec.ts | 125 +++ .../frontend/tests/sign-up.spec.ts | 159 ++++ .../frontend/tests/user-settings.spec.ts | 256 ++++++ .../frontend/tests/utils/mailcatcher.ts | 62 ++ .../frontend/tests/utils/privateApi.ts | 22 + .../frontend/tests/utils/random.ts | 19 + .../fastapi-saas/frontend/tests/utils/user.ts | 35 + .../fastapi-saas/frontend/tsconfig.build.json | 4 + .../fastapi-saas/frontend/tsconfig.json | 31 + .../fastapi-saas/frontend/tsconfig.node.json | 10 + .../fastapi-saas/frontend/vite.config.ts | 22 + .../fastapi-saas/hooks/post_gen_project.py | 8 + .../fastapi-saas/img/dashboard-dark.png | Bin 0 -> 122439 bytes .../fastapi-saas/img/dashboard-items.png | Bin 0 -> 67602 bytes .../examples/fastapi-saas/img/dashboard.png | Bin 0 -> 121001 bytes .../examples/fastapi-saas/img/docs.png | Bin 0 -> 98515 bytes .../img/github-social-preview.png | Bin 0 -> 44746 bytes .../img/github-social-preview.svg | 100 ++ .../examples/fastapi-saas/img/login.png | Bin 0 -> 51928 bytes .../examples/fastapi-saas/package.json | 13 + .../examples/fastapi-saas/pyproject.toml | 2 + .../examples/fastapi-saas/release-notes.md | 859 ++++++++++++++++++ .../scripts/add_latest_release_date.py | 40 + .../fastapi-saas/scripts/generate-client.sh | 11 + .../fastapi-saas/scripts/test-local.sh | 15 + .../examples/fastapi-saas/scripts/test.sh | 11 + .../outpost/examples/nextjs-saas/.env.example | 11 + .../outpost/examples/nextjs-saas/.gitignore | 41 + skills/outpost/examples/nextjs-saas/LICENSE | 21 + skills/outpost/examples/nextjs-saas/README.md | 200 ++++ .../dashboard/activity/loading.tsx | 17 + .../(dashboard)/dashboard/activity/page.tsx | 126 +++ .../dashboard/destinations/[id]/page.tsx | 286 ++++++ .../dashboard/destinations/page.tsx | 533 +++++++++++ .../(dashboard)/dashboard/general/page.tsx | 121 +++ .../app/(dashboard)/dashboard/layout.tsx | 74 ++ .../app/(dashboard)/dashboard/page.tsx | 287 ++++++ .../(dashboard)/dashboard/security/page.tsx | 167 ++++ .../nextjs-saas/app/(dashboard)/layout.tsx | 106 +++ .../nextjs-saas/app/(dashboard)/page.tsx | 130 +++ .../app/(dashboard)/pricing/page.tsx | 94 ++ .../app/(dashboard)/pricing/submit-button.tsx | 30 + .../nextjs-saas/app/(dashboard)/terminal.tsx | 68 ++ .../nextjs-saas/app/(login)/actions.ts | 502 ++++++++++ .../nextjs-saas/app/(login)/login.tsx | 142 +++ .../nextjs-saas/app/(login)/sign-in/page.tsx | 10 + .../nextjs-saas/app/(login)/sign-up/page.tsx | 10 + .../api/outpost/destination-types/route.ts | 56 ++ .../destinations/[id]/attempts/route.ts | 42 + .../api/outpost/destinations/[id]/route.ts | 42 + .../app/api/outpost/destinations/route.ts | 38 + .../api/outpost/events/[id]/attempts/route.ts | 37 + .../app/api/outpost/events/route.ts | 35 + .../app/api/outpost/retry/route.ts | 25 + .../app/api/outpost/test-publish/route.ts | 36 + .../app/api/outpost/topics/route.ts | 17 + .../app/api/stripe/checkout/route.ts | 97 ++ .../app/api/stripe/webhook/route.ts | 34 + .../nextjs-saas/app/api/team/route.ts | 6 + .../nextjs-saas/app/api/user/route.ts | 6 + .../examples/nextjs-saas/app/favicon.ico | Bin 0 -> 25931 bytes .../examples/nextjs-saas/app/globals.css | 275 ++++++ .../examples/nextjs-saas/app/layout.tsx | 44 + .../examples/nextjs-saas/app/not-found.tsx | 27 + .../examples/nextjs-saas/components.json | 21 + .../nextjs-saas/components/ui/avatar.tsx | 53 ++ .../nextjs-saas/components/ui/button.tsx | 59 ++ .../nextjs-saas/components/ui/card.tsx | 92 ++ .../components/ui/dropdown-menu.tsx | 257 ++++++ .../nextjs-saas/components/ui/input.tsx | 21 + .../nextjs-saas/components/ui/label.tsx | 24 + .../nextjs-saas/components/ui/radio-group.tsx | 45 + .../examples/nextjs-saas/drizzle.config.ts | 10 + .../nextjs-saas/lib/auth/middleware.ts | 75 ++ .../examples/nextjs-saas/lib/auth/session.ts | 59 ++ .../examples/nextjs-saas/lib/db/drizzle.ts | 13 + .../db/migrations/0000_soft_the_anarchist.sql | 88 ++ .../lib/db/migrations/meta/0000_snapshot.json | 389 ++++++++ .../lib/db/migrations/meta/_journal.json | 13 + .../examples/nextjs-saas/lib/db/queries.ts | 130 +++ .../examples/nextjs-saas/lib/db/schema.ts | 142 +++ .../examples/nextjs-saas/lib/db/seed.ts | 89 ++ .../examples/nextjs-saas/lib/db/setup.ts | 216 +++++ .../examples/nextjs-saas/lib/outpost/auth.ts | 18 + .../nextjs-saas/lib/outpost/client.ts | 17 + .../outpost/destination-types-wire.test.ts | 34 + .../lib/outpost/destination-types-wire.ts | 92 ++ .../examples/nextjs-saas/lib/outpost/index.ts | 39 + .../nextjs-saas/lib/payments/actions.ts | 15 + .../nextjs-saas/lib/payments/stripe.ts | 195 ++++ .../outpost/examples/nextjs-saas/lib/utils.ts | 6 + .../examples/nextjs-saas/middleware.ts | 49 + .../examples/nextjs-saas/next.config.ts | 10 + .../outpost/examples/nextjs-saas/package.json | 47 + .../examples/nextjs-saas/postcss.config.mjs | 5 + .../examples/nextjs-saas/tsconfig.json | 42 + .../examples/nextjs-saas/vitest.config.ts | 8 + .../fastapi-saas-integration-map.md | 39 + .../references/nextjs-saas-integration-map.md | 81 ++ 310 files changed, 25509 insertions(+), 4 deletions(-) create mode 100644 skills/outpost/examples/fastapi-saas/.copier/.copier-answers.yml.jinja create mode 100644 skills/outpost/examples/fastapi-saas/.copier/update_dotenv.py create mode 100644 skills/outpost/examples/fastapi-saas/.gitattributes create mode 100644 skills/outpost/examples/fastapi-saas/.github/DISCUSSION_TEMPLATE/questions.yml create mode 100644 skills/outpost/examples/fastapi-saas/.github/FUNDING.yml create mode 100644 skills/outpost/examples/fastapi-saas/.github/ISSUE_TEMPLATE/config.yml create mode 100644 skills/outpost/examples/fastapi-saas/.github/ISSUE_TEMPLATE/privileged.yml create mode 100644 skills/outpost/examples/fastapi-saas/.github/dependabot.yml create mode 100644 skills/outpost/examples/fastapi-saas/.github/labeler.yml create mode 100644 skills/outpost/examples/fastapi-saas/.github/workflows/add-to-project.yml create mode 100644 skills/outpost/examples/fastapi-saas/.github/workflows/deploy-production.yml create mode 100644 skills/outpost/examples/fastapi-saas/.github/workflows/deploy-staging.yml create mode 100644 skills/outpost/examples/fastapi-saas/.github/workflows/detect-conflicts.yml create mode 100644 skills/outpost/examples/fastapi-saas/.github/workflows/issue-manager.yml create mode 100644 skills/outpost/examples/fastapi-saas/.github/workflows/labeler.yml create mode 100644 skills/outpost/examples/fastapi-saas/.github/workflows/latest-changes.yml create mode 100644 skills/outpost/examples/fastapi-saas/.github/workflows/playwright.yml create mode 100644 skills/outpost/examples/fastapi-saas/.github/workflows/pre-commit.yml create mode 100644 skills/outpost/examples/fastapi-saas/.github/workflows/smokeshow.yml create mode 100644 skills/outpost/examples/fastapi-saas/.github/workflows/test-backend.yml create mode 100644 skills/outpost/examples/fastapi-saas/.github/workflows/test-docker-compose.yml create mode 100644 skills/outpost/examples/fastapi-saas/.gitignore create mode 100644 skills/outpost/examples/fastapi-saas/.pre-commit-config.yaml create mode 100644 skills/outpost/examples/fastapi-saas/CONTRIBUTING.md create mode 100644 skills/outpost/examples/fastapi-saas/LICENSE create mode 100644 skills/outpost/examples/fastapi-saas/README.md create mode 100644 skills/outpost/examples/fastapi-saas/SECURITY.md create mode 100644 skills/outpost/examples/fastapi-saas/backend/.dockerignore create mode 100644 skills/outpost/examples/fastapi-saas/backend/.gitignore create mode 100644 skills/outpost/examples/fastapi-saas/backend/Dockerfile create mode 100644 skills/outpost/examples/fastapi-saas/backend/README.md create mode 100755 skills/outpost/examples/fastapi-saas/backend/alembic.ini create mode 100644 skills/outpost/examples/fastapi-saas/backend/app/__init__.py create mode 100755 skills/outpost/examples/fastapi-saas/backend/app/alembic/README create mode 100755 skills/outpost/examples/fastapi-saas/backend/app/alembic/env.py create mode 100755 skills/outpost/examples/fastapi-saas/backend/app/alembic/script.py.mako create mode 100755 skills/outpost/examples/fastapi-saas/backend/app/alembic/versions/.keep create mode 100644 skills/outpost/examples/fastapi-saas/backend/app/alembic/versions/1a31ce608336_add_cascade_delete_relationships.py create mode 100755 skills/outpost/examples/fastapi-saas/backend/app/alembic/versions/9c0a54914c78_add_max_length_for_string_varchar_.py create mode 100755 skills/outpost/examples/fastapi-saas/backend/app/alembic/versions/d98dd8ec85a3_edit_replace_id_integers_in_all_models_.py create mode 100644 skills/outpost/examples/fastapi-saas/backend/app/alembic/versions/e2412789c190_initialize_models.py create mode 100644 skills/outpost/examples/fastapi-saas/backend/app/alembic/versions/fe56fa70289e_add_created_at_to_user_and_item.py create mode 100644 skills/outpost/examples/fastapi-saas/backend/app/api/__init__.py create mode 100644 skills/outpost/examples/fastapi-saas/backend/app/api/deps.py create mode 100644 skills/outpost/examples/fastapi-saas/backend/app/api/main.py create mode 100644 skills/outpost/examples/fastapi-saas/backend/app/api/routes/__init__.py create mode 100644 skills/outpost/examples/fastapi-saas/backend/app/api/routes/items.py create mode 100644 skills/outpost/examples/fastapi-saas/backend/app/api/routes/login.py create mode 100644 skills/outpost/examples/fastapi-saas/backend/app/api/routes/outpost.py create mode 100644 skills/outpost/examples/fastapi-saas/backend/app/api/routes/private.py create mode 100644 skills/outpost/examples/fastapi-saas/backend/app/api/routes/users.py create mode 100644 skills/outpost/examples/fastapi-saas/backend/app/api/routes/utils.py create mode 100644 skills/outpost/examples/fastapi-saas/backend/app/backend_pre_start.py create mode 100644 skills/outpost/examples/fastapi-saas/backend/app/core/__init__.py create mode 100644 skills/outpost/examples/fastapi-saas/backend/app/core/config.py create mode 100644 skills/outpost/examples/fastapi-saas/backend/app/core/db.py create mode 100644 skills/outpost/examples/fastapi-saas/backend/app/core/security.py create mode 100644 skills/outpost/examples/fastapi-saas/backend/app/crud.py create mode 100644 skills/outpost/examples/fastapi-saas/backend/app/email-templates/src/new_account.mjml create mode 100644 skills/outpost/examples/fastapi-saas/backend/app/email-templates/src/reset_password.mjml create mode 100644 skills/outpost/examples/fastapi-saas/backend/app/email-templates/src/test_email.mjml create mode 100644 skills/outpost/examples/fastapi-saas/backend/app/initial_data.py create mode 100644 skills/outpost/examples/fastapi-saas/backend/app/main.py create mode 100644 skills/outpost/examples/fastapi-saas/backend/app/models.py create mode 100644 skills/outpost/examples/fastapi-saas/backend/app/tests_pre_start.py create mode 100644 skills/outpost/examples/fastapi-saas/backend/app/utils.py create mode 100644 skills/outpost/examples/fastapi-saas/backend/pyproject.toml create mode 100755 skills/outpost/examples/fastapi-saas/backend/scripts/format.sh create mode 100644 skills/outpost/examples/fastapi-saas/backend/scripts/lint.sh create mode 100644 skills/outpost/examples/fastapi-saas/backend/scripts/prestart.sh create mode 100755 skills/outpost/examples/fastapi-saas/backend/scripts/test.sh create mode 100644 skills/outpost/examples/fastapi-saas/backend/scripts/tests-start.sh create mode 100644 skills/outpost/examples/fastapi-saas/backend/test_outpost_wire.py create mode 100644 skills/outpost/examples/fastapi-saas/backend/tests/__init__.py create mode 100644 skills/outpost/examples/fastapi-saas/backend/tests/api/__init__.py create mode 100644 skills/outpost/examples/fastapi-saas/backend/tests/api/routes/__init__.py create mode 100644 skills/outpost/examples/fastapi-saas/backend/tests/api/routes/test_items.py create mode 100644 skills/outpost/examples/fastapi-saas/backend/tests/api/routes/test_login.py create mode 100644 skills/outpost/examples/fastapi-saas/backend/tests/api/routes/test_private.py create mode 100644 skills/outpost/examples/fastapi-saas/backend/tests/api/routes/test_users.py create mode 100644 skills/outpost/examples/fastapi-saas/backend/tests/conftest.py create mode 100644 skills/outpost/examples/fastapi-saas/backend/tests/crud/__init__.py create mode 100644 skills/outpost/examples/fastapi-saas/backend/tests/crud/test_user.py create mode 100644 skills/outpost/examples/fastapi-saas/backend/tests/scripts/__init__.py create mode 100644 skills/outpost/examples/fastapi-saas/backend/tests/scripts/test_backend_pre_start.py create mode 100644 skills/outpost/examples/fastapi-saas/backend/tests/scripts/test_test_pre_start.py create mode 100644 skills/outpost/examples/fastapi-saas/backend/tests/utils/__init__.py create mode 100644 skills/outpost/examples/fastapi-saas/backend/tests/utils/item.py create mode 100644 skills/outpost/examples/fastapi-saas/backend/tests/utils/user.py create mode 100644 skills/outpost/examples/fastapi-saas/backend/tests/utils/utils.py create mode 100644 skills/outpost/examples/fastapi-saas/compose.override.yml create mode 100644 skills/outpost/examples/fastapi-saas/compose.traefik.yml create mode 100644 skills/outpost/examples/fastapi-saas/compose.yml create mode 100644 skills/outpost/examples/fastapi-saas/copier.yml create mode 100644 skills/outpost/examples/fastapi-saas/deployment.md create mode 100644 skills/outpost/examples/fastapi-saas/development.md create mode 100644 skills/outpost/examples/fastapi-saas/frontend/.dockerignore create mode 100644 skills/outpost/examples/fastapi-saas/frontend/.gitignore create mode 100644 skills/outpost/examples/fastapi-saas/frontend/Dockerfile create mode 100644 skills/outpost/examples/fastapi-saas/frontend/Dockerfile.playwright create mode 100644 skills/outpost/examples/fastapi-saas/frontend/README.md create mode 100644 skills/outpost/examples/fastapi-saas/frontend/biome.json create mode 100644 skills/outpost/examples/fastapi-saas/frontend/components.json create mode 100644 skills/outpost/examples/fastapi-saas/frontend/index.html create mode 100644 skills/outpost/examples/fastapi-saas/frontend/nginx-backend-not-found.conf create mode 100644 skills/outpost/examples/fastapi-saas/frontend/nginx.conf create mode 100644 skills/outpost/examples/fastapi-saas/frontend/openapi-ts.config.ts create mode 100644 skills/outpost/examples/fastapi-saas/frontend/package.json create mode 100644 skills/outpost/examples/fastapi-saas/frontend/playwright.config.ts create mode 100644 skills/outpost/examples/fastapi-saas/frontend/public/assets/images/fastapi-icon-light.svg create mode 100644 skills/outpost/examples/fastapi-saas/frontend/public/assets/images/fastapi-icon.svg create mode 100644 skills/outpost/examples/fastapi-saas/frontend/public/assets/images/fastapi-logo-light.svg create mode 100644 skills/outpost/examples/fastapi-saas/frontend/public/assets/images/fastapi-logo.svg create mode 100644 skills/outpost/examples/fastapi-saas/frontend/public/assets/images/favicon.png create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/client/core/ApiError.ts create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/client/core/ApiRequestOptions.ts create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/client/core/ApiResult.ts create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/client/core/CancelablePromise.ts create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/client/core/OpenAPI.ts create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/client/core/request.ts create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/client/index.ts create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/client/schemas.gen.ts create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/client/sdk.gen.ts create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/client/types.gen.ts create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/components/Admin/AddUser.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/components/Admin/DeleteUser.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/components/Admin/EditUser.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/components/Admin/UserActionsMenu.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/components/Admin/columns.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/components/Common/Appearance.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/components/Common/AuthLayout.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/components/Common/DataTable.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/components/Common/ErrorComponent.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/components/Common/Footer.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/components/Common/Logo.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/components/Common/NotFound.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/components/Destinations/CreateDestination.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/components/Items/AddItem.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/components/Items/DeleteItem.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/components/Items/EditItem.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/components/Items/ItemActionsMenu.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/components/Items/columns.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/components/Pending/PendingItems.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/components/Pending/PendingUsers.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/components/Sidebar/AppSidebar.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/components/Sidebar/Main.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/components/Sidebar/User.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/components/UserSettings/ChangePassword.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/components/UserSettings/DeleteAccount.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/components/UserSettings/DeleteConfirmation.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/components/UserSettings/UserInformation.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/components/theme-provider.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/components/ui/alert.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/components/ui/avatar.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/components/ui/badge.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/components/ui/button-group.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/components/ui/button.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/components/ui/card.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/components/ui/checkbox.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/components/ui/dialog.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/components/ui/dropdown-menu.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/components/ui/form.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/components/ui/input.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/components/ui/label.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/components/ui/loading-button.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/components/ui/pagination.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/components/ui/password-input.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/components/ui/select.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/components/ui/separator.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/components/ui/sheet.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/components/ui/sidebar.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/components/ui/skeleton.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/components/ui/sonner.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/components/ui/table.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/components/ui/tabs.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/components/ui/tooltip.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/hooks/useAuth.ts create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/hooks/useCopyToClipboard.ts create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/hooks/useCustomToast.ts create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/hooks/useMobile.ts create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/index.css create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/lib/outpost-api.ts create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/lib/utils.ts create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/main.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/routeTree.gen.ts create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/routes/__root.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/routes/_layout.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/routes/_layout/admin.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/routes/_layout/destinations/$destinationId/activity.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/routes/_layout/destinations/index.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/routes/_layout/destinations/route.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/routes/_layout/index.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/routes/_layout/items.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/routes/_layout/settings.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/routes/login.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/routes/recover-password.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/routes/reset-password.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/routes/signup.tsx create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/utils.ts create mode 100644 skills/outpost/examples/fastapi-saas/frontend/src/vite-env.d.ts create mode 100644 skills/outpost/examples/fastapi-saas/frontend/tests/admin.spec.ts create mode 100644 skills/outpost/examples/fastapi-saas/frontend/tests/auth.setup.ts create mode 100644 skills/outpost/examples/fastapi-saas/frontend/tests/config.ts create mode 100644 skills/outpost/examples/fastapi-saas/frontend/tests/items.spec.ts create mode 100644 skills/outpost/examples/fastapi-saas/frontend/tests/login.spec.ts create mode 100644 skills/outpost/examples/fastapi-saas/frontend/tests/reset-password.spec.ts create mode 100644 skills/outpost/examples/fastapi-saas/frontend/tests/sign-up.spec.ts create mode 100644 skills/outpost/examples/fastapi-saas/frontend/tests/user-settings.spec.ts create mode 100644 skills/outpost/examples/fastapi-saas/frontend/tests/utils/mailcatcher.ts create mode 100644 skills/outpost/examples/fastapi-saas/frontend/tests/utils/privateApi.ts create mode 100644 skills/outpost/examples/fastapi-saas/frontend/tests/utils/random.ts create mode 100644 skills/outpost/examples/fastapi-saas/frontend/tests/utils/user.ts create mode 100644 skills/outpost/examples/fastapi-saas/frontend/tsconfig.build.json create mode 100644 skills/outpost/examples/fastapi-saas/frontend/tsconfig.json create mode 100644 skills/outpost/examples/fastapi-saas/frontend/tsconfig.node.json create mode 100644 skills/outpost/examples/fastapi-saas/frontend/vite.config.ts create mode 100644 skills/outpost/examples/fastapi-saas/hooks/post_gen_project.py create mode 100644 skills/outpost/examples/fastapi-saas/img/dashboard-dark.png create mode 100644 skills/outpost/examples/fastapi-saas/img/dashboard-items.png create mode 100644 skills/outpost/examples/fastapi-saas/img/dashboard.png create mode 100644 skills/outpost/examples/fastapi-saas/img/docs.png create mode 100644 skills/outpost/examples/fastapi-saas/img/github-social-preview.png create mode 100644 skills/outpost/examples/fastapi-saas/img/github-social-preview.svg create mode 100644 skills/outpost/examples/fastapi-saas/img/login.png create mode 100644 skills/outpost/examples/fastapi-saas/package.json create mode 100644 skills/outpost/examples/fastapi-saas/pyproject.toml create mode 100644 skills/outpost/examples/fastapi-saas/release-notes.md create mode 100644 skills/outpost/examples/fastapi-saas/scripts/add_latest_release_date.py create mode 100644 skills/outpost/examples/fastapi-saas/scripts/generate-client.sh create mode 100644 skills/outpost/examples/fastapi-saas/scripts/test-local.sh create mode 100644 skills/outpost/examples/fastapi-saas/scripts/test.sh create mode 100644 skills/outpost/examples/nextjs-saas/.env.example create mode 100644 skills/outpost/examples/nextjs-saas/.gitignore create mode 100644 skills/outpost/examples/nextjs-saas/LICENSE create mode 100644 skills/outpost/examples/nextjs-saas/README.md create mode 100644 skills/outpost/examples/nextjs-saas/app/(dashboard)/dashboard/activity/loading.tsx create mode 100644 skills/outpost/examples/nextjs-saas/app/(dashboard)/dashboard/activity/page.tsx create mode 100644 skills/outpost/examples/nextjs-saas/app/(dashboard)/dashboard/destinations/[id]/page.tsx create mode 100644 skills/outpost/examples/nextjs-saas/app/(dashboard)/dashboard/destinations/page.tsx create mode 100644 skills/outpost/examples/nextjs-saas/app/(dashboard)/dashboard/general/page.tsx create mode 100644 skills/outpost/examples/nextjs-saas/app/(dashboard)/dashboard/layout.tsx create mode 100644 skills/outpost/examples/nextjs-saas/app/(dashboard)/dashboard/page.tsx create mode 100644 skills/outpost/examples/nextjs-saas/app/(dashboard)/dashboard/security/page.tsx create mode 100644 skills/outpost/examples/nextjs-saas/app/(dashboard)/layout.tsx create mode 100644 skills/outpost/examples/nextjs-saas/app/(dashboard)/page.tsx create mode 100644 skills/outpost/examples/nextjs-saas/app/(dashboard)/pricing/page.tsx create mode 100644 skills/outpost/examples/nextjs-saas/app/(dashboard)/pricing/submit-button.tsx create mode 100644 skills/outpost/examples/nextjs-saas/app/(dashboard)/terminal.tsx create mode 100644 skills/outpost/examples/nextjs-saas/app/(login)/actions.ts create mode 100644 skills/outpost/examples/nextjs-saas/app/(login)/login.tsx create mode 100644 skills/outpost/examples/nextjs-saas/app/(login)/sign-in/page.tsx create mode 100644 skills/outpost/examples/nextjs-saas/app/(login)/sign-up/page.tsx create mode 100644 skills/outpost/examples/nextjs-saas/app/api/outpost/destination-types/route.ts create mode 100644 skills/outpost/examples/nextjs-saas/app/api/outpost/destinations/[id]/attempts/route.ts create mode 100644 skills/outpost/examples/nextjs-saas/app/api/outpost/destinations/[id]/route.ts create mode 100644 skills/outpost/examples/nextjs-saas/app/api/outpost/destinations/route.ts create mode 100644 skills/outpost/examples/nextjs-saas/app/api/outpost/events/[id]/attempts/route.ts create mode 100644 skills/outpost/examples/nextjs-saas/app/api/outpost/events/route.ts create mode 100644 skills/outpost/examples/nextjs-saas/app/api/outpost/retry/route.ts create mode 100644 skills/outpost/examples/nextjs-saas/app/api/outpost/test-publish/route.ts create mode 100644 skills/outpost/examples/nextjs-saas/app/api/outpost/topics/route.ts create mode 100644 skills/outpost/examples/nextjs-saas/app/api/stripe/checkout/route.ts create mode 100644 skills/outpost/examples/nextjs-saas/app/api/stripe/webhook/route.ts create mode 100644 skills/outpost/examples/nextjs-saas/app/api/team/route.ts create mode 100644 skills/outpost/examples/nextjs-saas/app/api/user/route.ts create mode 100644 skills/outpost/examples/nextjs-saas/app/favicon.ico create mode 100644 skills/outpost/examples/nextjs-saas/app/globals.css create mode 100644 skills/outpost/examples/nextjs-saas/app/layout.tsx create mode 100644 skills/outpost/examples/nextjs-saas/app/not-found.tsx create mode 100644 skills/outpost/examples/nextjs-saas/components.json create mode 100644 skills/outpost/examples/nextjs-saas/components/ui/avatar.tsx create mode 100644 skills/outpost/examples/nextjs-saas/components/ui/button.tsx create mode 100644 skills/outpost/examples/nextjs-saas/components/ui/card.tsx create mode 100644 skills/outpost/examples/nextjs-saas/components/ui/dropdown-menu.tsx create mode 100644 skills/outpost/examples/nextjs-saas/components/ui/input.tsx create mode 100644 skills/outpost/examples/nextjs-saas/components/ui/label.tsx create mode 100644 skills/outpost/examples/nextjs-saas/components/ui/radio-group.tsx create mode 100644 skills/outpost/examples/nextjs-saas/drizzle.config.ts create mode 100644 skills/outpost/examples/nextjs-saas/lib/auth/middleware.ts create mode 100644 skills/outpost/examples/nextjs-saas/lib/auth/session.ts create mode 100644 skills/outpost/examples/nextjs-saas/lib/db/drizzle.ts create mode 100644 skills/outpost/examples/nextjs-saas/lib/db/migrations/0000_soft_the_anarchist.sql create mode 100644 skills/outpost/examples/nextjs-saas/lib/db/migrations/meta/0000_snapshot.json create mode 100644 skills/outpost/examples/nextjs-saas/lib/db/migrations/meta/_journal.json create mode 100644 skills/outpost/examples/nextjs-saas/lib/db/queries.ts create mode 100644 skills/outpost/examples/nextjs-saas/lib/db/schema.ts create mode 100644 skills/outpost/examples/nextjs-saas/lib/db/seed.ts create mode 100644 skills/outpost/examples/nextjs-saas/lib/db/setup.ts create mode 100644 skills/outpost/examples/nextjs-saas/lib/outpost/auth.ts create mode 100644 skills/outpost/examples/nextjs-saas/lib/outpost/client.ts create mode 100644 skills/outpost/examples/nextjs-saas/lib/outpost/destination-types-wire.test.ts create mode 100644 skills/outpost/examples/nextjs-saas/lib/outpost/destination-types-wire.ts create mode 100644 skills/outpost/examples/nextjs-saas/lib/outpost/index.ts create mode 100644 skills/outpost/examples/nextjs-saas/lib/payments/actions.ts create mode 100644 skills/outpost/examples/nextjs-saas/lib/payments/stripe.ts create mode 100644 skills/outpost/examples/nextjs-saas/lib/utils.ts create mode 100644 skills/outpost/examples/nextjs-saas/middleware.ts create mode 100644 skills/outpost/examples/nextjs-saas/next.config.ts create mode 100644 skills/outpost/examples/nextjs-saas/package.json create mode 100644 skills/outpost/examples/nextjs-saas/postcss.config.mjs create mode 100644 skills/outpost/examples/nextjs-saas/tsconfig.json create mode 100644 skills/outpost/examples/nextjs-saas/vitest.config.ts create mode 100644 skills/outpost/references/fastapi-saas-integration-map.md create mode 100644 skills/outpost/references/nextjs-saas-integration-map.md diff --git a/.github/workflows/test-examples.yml b/.github/workflows/test-examples.yml index 9c762ad..c2da44e 100644 --- a/.github/workflows/test-examples.yml +++ b/.github/workflows/test-examples.yml @@ -70,10 +70,29 @@ jobs: working-directory: skills/event-gateway/examples/fastapi run: pytest test_webhook.py -v + test-outpost-saas: + name: Outpost SaaS examples (nextjs-saas + fastapi-saas) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: "20" + + - name: Setup Python + uses: actions/setup-python@v5 + with: + python-version: "3.11" + + - name: Run test-examples.sh outpost + run: ./scripts/test-examples.sh outpost + summary: name: Test Summary runs-on: ubuntu-latest - needs: [test-express, test-nextjs, test-fastapi] + needs: [test-express, test-nextjs, test-fastapi, test-outpost-saas] if: always() steps: - name: Check test results @@ -83,7 +102,8 @@ jobs: if [ "${{ needs.test-express.result }}" == "failure" ] || \ [ "${{ needs.test-nextjs.result }}" == "failure" ] || \ - [ "${{ needs.test-fastapi.result }}" == "failure" ]; then + [ "${{ needs.test-fastapi.result }}" == "failure" ] || \ + [ "${{ needs.test-outpost-saas.result }}" == "failure" ]; then echo "**Result:** Some tests failed" >> $GITHUB_STEP_SUMMARY exit 1 fi diff --git a/.gitignore b/.gitignore index 736a875..9b672e0 100644 --- a/.gitignore +++ b/.gitignore @@ -20,6 +20,7 @@ build/ *.egg-info/ .next/ out/ +.turbo/ # IDE and editor files .idea/ @@ -45,6 +46,9 @@ htmlcov/ # Package lock files (not tracked for example projects) package-lock.json yarn.lock +pnpm-lock.yaml +uv.lock +bun.lock # Agent scenario tester test-results/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index e7d4b6e..d8d9765 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -31,6 +31,12 @@ cd agent-skills cd skills/event-gateway/examples/express && npm install && npm test cd skills/event-gateway/examples/nextjs && npm install && npm test cd skills/event-gateway/examples/fastapi && pip install -r requirements.txt && pytest test_webhook.py -v + +# Outpost SaaS reference (Next.js + Outpost SDK; large tree — npm install may take a minute) +cd skills/outpost/examples/nextjs-saas && npm install && npm test + +# Outpost FastAPI SaaS (backend only — pip install in backend/) +cd skills/outpost/examples/fastapi-saas/backend && python3 -m venv venv && source venv/bin/activate && pip install pytest httpx 'fastapi>=0.114' && pytest test_outpost_wire.py -q ``` **Agent scenario tests** (end-to-end: install skills, run Claude, score report): see [TESTING.md](TESTING.md#agent-scenario-testing-two-layers). From repo root: `./scripts/test-agent-scenario.sh run receive-webhooks express` or `./scripts/test-agent-scenario.sh list`. diff --git a/TESTING.md b/TESTING.md index 5c4e0c2..32396ca 100644 --- a/TESTING.md +++ b/TESTING.md @@ -1,6 +1,6 @@ # Testing Hookdeck Agent Skills -This document covers automated testing for code examples in the `event-gateway` skill. Follows the same patterns as [hookdeck/webhook-skills](https://github.com/hookdeck/webhook-skills/blob/main/TESTING.md). +This document covers automated testing for code examples in the **`event-gateway`** and **`outpost`** skills. Follows the same patterns as [hookdeck/webhook-skills](https://github.com/hookdeck/webhook-skills/blob/main/TESTING.md). ## Code Example Tests @@ -48,8 +48,16 @@ Use the test runner script to discover and run all examples: # Specific skill ./scripts/test-examples.sh event-gateway +./scripts/test-examples.sh outpost ``` +The **outpost** skill includes: + +- [examples/nextjs-saas/](skills/outpost/examples/nextjs-saas/) — `npm test` (Vitest). +- [examples/fastapi-saas/](skills/outpost/examples/fastapi-saas/) — in `backend/`: `pytest test_outpost_wire.py` with minimal deps (no full app install; no live Outpost). + +Both are full apps; installs can take longer than the small event-gateway demos. + ### CI Pipeline Tests run automatically on PR and push to main via GitHub Actions. See `.github/workflows/test-examples.yml`. diff --git a/scripts/test-examples.sh b/scripts/test-examples.sh index 6f95ddb..e7088c8 100755 --- a/scripts/test-examples.sh +++ b/scripts/test-examples.sh @@ -60,6 +60,10 @@ usage() { frameworks+=("$fw") fi done + if [ "$skill_name" = "outpost" ]; then + [ -d "$dir/nextjs-saas" ] && frameworks+=("nextjs-saas") + [ -d "$dir/fastapi-saas" ] && frameworks+=("fastapi-saas") + fi echo " $skill_name (${frameworks[*]})" fi done @@ -262,6 +266,85 @@ run_python_tests() { deactivate } +# Outpost fastapi-saas: full-stack template; backend is a hatchling package under backend/ +run_fastapi_saas_tests() { + local dir=$1 + local name=$2 + local backend="$dir/backend" + + echo -n " Testing $name... " + + if [ ! -f "$backend/pyproject.toml" ]; then + echo -e "${YELLOW}SKIPPED${NC} (no backend/pyproject.toml)" + SKIPPED=$((SKIPPED + 1)) + return + fi + + if [ ! -f "$backend/test_outpost_wire.py" ]; then + echo -e "${YELLOW}SKIPPED${NC} (no backend/test_outpost_wire.py)" + SKIPPED=$((SKIPPED + 1)) + return + fi + + if ! pushd "$backend" >/dev/null; then + echo -e "${RED}FAILED${NC} (cannot cd to backend)" + FAILED=$((FAILED + 1)) + FAILED_TESTS+=("$name: cd backend failed") + return + fi + + if [ ! -d "venv" ]; then + local venv_output + venv_output=$(python3 -m venv venv 2>&1) || { + echo -e "${RED}FAILED${NC} (venv creation failed)" + echo "$venv_output" + FAILED=$((FAILED + 1)) + FAILED_TESTS+=("$name: venv creation failed") + popd >/dev/null + return + } + fi + + # shellcheck disable=SC1091 + source venv/bin/activate + local pip_output + # Standalone wire tests only (no pip install -e . — avoids template DB session fixtures) + pip_output=$(pip install -q pytest httpx 'fastapi>=0.114' 2>&1) || { + echo -e "${RED}FAILED${NC} (pip install test deps failed)" + echo "$pip_output" + FAILED=$((FAILED + 1)) + FAILED_TESTS+=("$name: pip install test deps failed") + deactivate + popd >/dev/null + return + } + + local test_output + test_output=$(python -m pytest test_outpost_wire.py -q 2>&1) + local test_exit_code=$? + + deactivate + popd >/dev/null + + if [ $test_exit_code -eq 0 ]; then + local summary + summary=$(echo "$test_output" | grep -E "passed" | tail -1) + if [ -n "$summary" ]; then + echo -e "${GREEN}PASSED${NC} ($summary)" + else + echo -e "${GREEN}PASSED${NC}" + fi + PASSED=$((PASSED + 1)) + else + echo -e "${RED}FAILED${NC}" + echo "" + echo "$test_output" + echo "" + FAILED=$((FAILED + 1)) + FAILED_TESTS+=("$name") + fi +} + # Run tests for each skill for skill in "${SKILLS[@]}"; do skill_dir="$SKILLS_DIR/$skill" @@ -270,7 +353,13 @@ for skill in "${SKILLS[@]}"; do echo "Testing $skill" echo "----------------------------------------" - for framework in "${FRAMEWORKS[@]}"; do + frameworks_to_test=("${FRAMEWORKS[@]}") + # Outpost: additional example layouts (not express/nextjs/fastapi) + if [ "$skill" = "outpost" ]; then + frameworks_to_test+=("nextjs-saas" "fastapi-saas") + fi + + for framework in "${frameworks_to_test[@]}"; do example_dir="$skill_dir/examples/$framework" test_name="$skill/$framework" @@ -283,9 +372,14 @@ for skill in "${SKILLS[@]}"; do if [ "$framework" = "fastapi" ]; then run_python_tests "$example_dir" "$test_name" + elif [ "$framework" = "fastapi-saas" ]; then + run_fastapi_saas_tests "$example_dir" "$test_name" else run_node_tests "$example_dir" "$test_name" fi + + # Test helpers cd into example dirs; restore cwd so relative paths stay reliable + cd "$ROOT_DIR" || true done done diff --git a/skills/outpost/SKILL.md b/skills/outpost/SKILL.md index 0179827..4161855 100644 --- a/skills/outpost/SKILL.md +++ b/skills/outpost/SKILL.md @@ -39,6 +39,24 @@ For managed, sign up at [hookdeck.com](https://hookdeck.com). For self-hosted, s **Delivery Attempts** -- Records of each attempt to deliver an event to a destination, including request/response data. +## Reference example applications + +Runnable **multi-tenant SaaS** samples that embed Hookdeck Outpost (admin API, per-tenant destinations, publish). They are **pattern references**, not minimal snippets: each tree is a full product baseline (Next.js or FastAPI + React) so you can see realistic auth, DB, and dashboard code. + +**How agents should use them:** Follow [PostHog-style progressive disclosure](https://posthog.com/handbook/engineering/ai/writing-skills) — use this skill’s overview first, then open **only** the files that match the task. + +| Example | Stack | Location | +|--------|--------|----------| +| SaaS (Next.js) | App Router + `@hookdeck/outpost-sdk` + dashboard UI | [examples/nextjs-saas/](examples/nextjs-saas/) — [README](examples/nextjs-saas/README.md) | +| SaaS (FastAPI + React) | FastAPI BFF (`httpx` → Outpost) + full-stack template UI | [examples/fastapi-saas/](examples/fastapi-saas/) — [README](examples/fastapi-saas/README.md) | + +**Integration maps (read before browsing the apps):** + +- Next.js: [references/nextjs-saas-integration-map.md](references/nextjs-saas-integration-map.md) +- FastAPI: [references/fastapi-saas-integration-map.md](references/fastapi-saas-integration-map.md) + +**Tests:** `npm test` in `nextjs-saas` (Vitest); `pytest test_outpost_wire.py` in `fastapi-saas/backend` via `./scripts/test-examples.sh outpost` (standalone file — avoids the template’s Postgres `tests/conftest.py`). The Next.js example uses **npm** (no `pnpm-lock.yaml` in this repo). + ## Self-Hosted Quick Start (Docker) Requires [Docker](https://docs.docker.com/engine/install/). Uses RabbitMQ for message queuing. diff --git a/skills/outpost/examples/fastapi-saas/.copier/.copier-answers.yml.jinja b/skills/outpost/examples/fastapi-saas/.copier/.copier-answers.yml.jinja new file mode 100644 index 0000000..0028a23 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/.copier/.copier-answers.yml.jinja @@ -0,0 +1 @@ +{{ _copier_answers|to_json -}} diff --git a/skills/outpost/examples/fastapi-saas/.copier/update_dotenv.py b/skills/outpost/examples/fastapi-saas/.copier/update_dotenv.py new file mode 100644 index 0000000..6576885 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/.copier/update_dotenv.py @@ -0,0 +1,26 @@ +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)) diff --git a/skills/outpost/examples/fastapi-saas/.gitattributes b/skills/outpost/examples/fastapi-saas/.gitattributes new file mode 100644 index 0000000..efdba87 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/.gitattributes @@ -0,0 +1,2 @@ +* text=auto +*.sh text eol=lf diff --git a/skills/outpost/examples/fastapi-saas/.github/DISCUSSION_TEMPLATE/questions.yml b/skills/outpost/examples/fastapi-saas/.github/DISCUSSION_TEMPLATE/questions.yml new file mode 100644 index 0000000..af6abf4 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/.github/DISCUSSION_TEMPLATE/questions.yml @@ -0,0 +1,118 @@ +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. diff --git a/skills/outpost/examples/fastapi-saas/.github/FUNDING.yml b/skills/outpost/examples/fastapi-saas/.github/FUNDING.yml new file mode 100644 index 0000000..0ffc101 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/.github/FUNDING.yml @@ -0,0 +1 @@ +github: [tiangolo] diff --git a/skills/outpost/examples/fastapi-saas/.github/ISSUE_TEMPLATE/config.yml b/skills/outpost/examples/fastapi-saas/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..50bde36 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,10 @@ +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 diff --git a/skills/outpost/examples/fastapi-saas/.github/ISSUE_TEMPLATE/privileged.yml b/skills/outpost/examples/fastapi-saas/.github/ISSUE_TEMPLATE/privileged.yml new file mode 100644 index 0000000..6438848 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/.github/ISSUE_TEMPLATE/privileged.yml @@ -0,0 +1,22 @@ +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. diff --git a/skills/outpost/examples/fastapi-saas/.github/dependabot.yml b/skills/outpost/examples/fastapi-saas/.github/dependabot.yml new file mode 100644 index 0000000..e83b247 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/.github/dependabot.yml @@ -0,0 +1,46 @@ +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] diff --git a/skills/outpost/examples/fastapi-saas/.github/labeler.yml b/skills/outpost/examples/fastapi-saas/.github/labeler.yml new file mode 100644 index 0000000..ed657c2 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/.github/labeler.yml @@ -0,0 +1,25 @@ +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/**' diff --git a/skills/outpost/examples/fastapi-saas/.github/workflows/add-to-project.yml b/skills/outpost/examples/fastapi-saas/.github/workflows/add-to-project.yml new file mode 100644 index 0000000..dccea83 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/.github/workflows/add-to-project.yml @@ -0,0 +1,18 @@ +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 }} diff --git a/skills/outpost/examples/fastapi-saas/.github/workflows/deploy-production.yml b/skills/outpost/examples/fastapi-saas/.github/workflows/deploy-production.yml new file mode 100644 index 0000000..fd11900 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/.github/workflows/deploy-production.yml @@ -0,0 +1,32 @@ +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 diff --git a/skills/outpost/examples/fastapi-saas/.github/workflows/deploy-staging.yml b/skills/outpost/examples/fastapi-saas/.github/workflows/deploy-staging.yml new file mode 100644 index 0000000..7968f95 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/.github/workflows/deploy-staging.yml @@ -0,0 +1,32 @@ +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 diff --git a/skills/outpost/examples/fastapi-saas/.github/workflows/detect-conflicts.yml b/skills/outpost/examples/fastapi-saas/.github/workflows/detect-conflicts.yml new file mode 100644 index 0000000..aba329d --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/.github/workflows/detect-conflicts.yml @@ -0,0 +1,19 @@ +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." diff --git a/skills/outpost/examples/fastapi-saas/.github/workflows/issue-manager.yml b/skills/outpost/examples/fastapi-saas/.github/workflows/issue-manager.yml new file mode 100644 index 0000000..425c926 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/.github/workflows/issue-manager.yml @@ -0,0 +1,55 @@ +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." + } + } diff --git a/skills/outpost/examples/fastapi-saas/.github/workflows/labeler.yml b/skills/outpost/examples/fastapi-saas/.github/workflows/labeler.yml new file mode 100644 index 0000000..7aeb448 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/.github/workflows/labeler.yml @@ -0,0 +1,33 @@ +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 }} diff --git a/skills/outpost/examples/fastapi-saas/.github/workflows/latest-changes.yml b/skills/outpost/examples/fastapi-saas/.github/workflows/latest-changes.yml new file mode 100644 index 0000000..1f6cde6 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/.github/workflows/latest-changes.yml @@ -0,0 +1,40 @@ +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: "### " diff --git a/skills/outpost/examples/fastapi-saas/.github/workflows/playwright.yml b/skills/outpost/examples/fastapi-saas/.github/workflows/playwright.yml new file mode 100644 index 0000000..d4c6247 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/.github/workflows/playwright.yml @@ -0,0 +1,121 @@ +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 diff --git a/skills/outpost/examples/fastapi-saas/.github/workflows/pre-commit.yml b/skills/outpost/examples/fastapi-saas/.github/workflows/pre-commit.yml new file mode 100644 index 0000000..b609751 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/.github/workflows/pre-commit.yml @@ -0,0 +1,94 @@ +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) }} diff --git a/skills/outpost/examples/fastapi-saas/.github/workflows/smokeshow.yml b/skills/outpost/examples/fastapi-saas/.github/workflows/smokeshow.yml new file mode 100644 index 0000000..353a010 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/.github/workflows/smokeshow.yml @@ -0,0 +1,34 @@ +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 }} diff --git a/skills/outpost/examples/fastapi-saas/.github/workflows/test-backend.yml b/skills/outpost/examples/fastapi-saas/.github/workflows/test-backend.yml new file mode 100644 index 0000000..1517812 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/.github/workflows/test-backend.yml @@ -0,0 +1,41 @@ +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 diff --git a/skills/outpost/examples/fastapi-saas/.github/workflows/test-docker-compose.yml b/skills/outpost/examples/fastapi-saas/.github/workflows/test-docker-compose.yml new file mode 100644 index 0000000..8054e5e --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/.github/workflows/test-docker-compose.yml @@ -0,0 +1,26 @@ +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 diff --git a/skills/outpost/examples/fastapi-saas/.gitignore b/skills/outpost/examples/fastapi-saas/.gitignore new file mode 100644 index 0000000..f903ab6 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/.gitignore @@ -0,0 +1,7 @@ +.vscode/* +!.vscode/extensions.json +node_modules/ +/test-results/ +/playwright-report/ +/blob-report/ +/playwright/.cache/ diff --git a/skills/outpost/examples/fastapi-saas/.pre-commit-config.yaml b/skills/outpost/examples/fastapi-saas/.pre-commit-config.yaml new file mode 100644 index 0000000..a325746 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/.pre-commit-config.yaml @@ -0,0 +1,69 @@ +# 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: local-ty + name: ty check + entry: uv run ty check 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$ + + - id: add-release-date + language: unsupported + name: add date to latest release header + entry: uv run python scripts/add_latest_release_date.py + files: ^release-notes\.md$ + pass_filenames: false diff --git a/skills/outpost/examples/fastapi-saas/CONTRIBUTING.md b/skills/outpost/examples/fastapi-saas/CONTRIBUTING.md new file mode 100644 index 0000000..7e725a3 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/CONTRIBUTING.md @@ -0,0 +1,65 @@ +# 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). diff --git a/skills/outpost/examples/fastapi-saas/LICENSE b/skills/outpost/examples/fastapi-saas/LICENSE new file mode 100644 index 0000000..f11987b --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/LICENSE @@ -0,0 +1,21 @@ +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. diff --git a/skills/outpost/examples/fastapi-saas/README.md b/skills/outpost/examples/fastapi-saas/README.md new file mode 100644 index 0000000..dd4c28e --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/README.md @@ -0,0 +1,235 @@ +# Full Stack FastAPI Template + +> **Reference in [hookdeck/agent-skills](https://github.com/hookdeck/agent-skills):** this tree is copied from the last successful **Outpost agent eval** for [scenario 09](https://github.com/hookdeck/outpost/blob/main/docs/agent-evaluation/scenarios/09-integrate-fastapi-existing.md) (run `2026-04-10T19-54-20-037Z-scenario-09`, baseline [fastapi/full-stack-fastapi-template](https://github.com/fastapi/full-stack-fastapi-template)). **Hookdeck Outpost** is integrated as a **BFF** under `backend/app/api/routes/outpost.py` plus domain publishes in `users.py`. Lockfiles under the template root are **gitignored** in agent-skills where applicable. **CI** runs `pytest backend/test_outpost_wire.py` with minimal deps (no Postgres). **For AI agents:** start with the skill’s [**FastAPI Outpost integration map**](https://github.com/hookdeck/agent-skills/blob/main/skills/outpost/references/fastapi-saas-integration-map.md). + +Test Docker Compose +Test Backend +Coverage + +## Technology Stack and Features + +- ⚡ [**FastAPI**](https://fastapi.tiangolo.com) for the Python backend API. + - 🧰 [SQLModel](https://sqlmodel.tiangolo.com) for the Python SQL database interactions (ORM). + - 🔍 [Pydantic](https://docs.pydantic.dev), used by FastAPI, for the data validation and settings management. + - 💾 [PostgreSQL](https://www.postgresql.org) as the SQL database. +- 🚀 [React](https://react.dev) for the frontend. + - 💃 Using TypeScript, hooks, [Vite](https://vitejs.dev), and other parts of a modern frontend stack. + - 🎨 [Tailwind CSS](https://tailwindcss.com) and [shadcn/ui](https://ui.shadcn.com) for the frontend components. + - 🤖 An automatically generated frontend client. + - 🧪 [Playwright](https://playwright.dev) for End-to-End testing. + - 🦇 Dark mode support. +- 🐋 [Docker Compose](https://www.docker.com) for development and production. +- 🔒 Secure password hashing by default. +- 🔑 JWT (JSON Web Token) authentication. +- 📫 Email based password recovery. +- 📬 [Mailcatcher](https://mailcatcher.me) for local email testing during development. +- ✅ Tests with [Pytest](https://pytest.org). +- 📞 [Traefik](https://traefik.io) as a reverse proxy / load balancer. +- 🚢 Deployment instructions using Docker Compose, including how to set up a frontend Traefik proxy to handle automatic HTTPS certificates. +- 🏭 CI (continuous integration) and CD (continuous deployment) based on GitHub Actions. + +### Dashboard Login + +[![API docs](img/login.png)](https://github.com/fastapi/full-stack-fastapi-template) + +### Dashboard - Admin + +[![API docs](img/dashboard.png)](https://github.com/fastapi/full-stack-fastapi-template) + +### Dashboard - Items + +[![API docs](img/dashboard-items.png)](https://github.com/fastapi/full-stack-fastapi-template) + +### Dashboard - Dark Mode + +[![API docs](img/dashboard-dark.png)](https://github.com/fastapi/full-stack-fastapi-template) + +### Interactive API Documentation + +[![API docs](img/docs.png)](https://github.com/fastapi/full-stack-fastapi-template) + +## How To Use It + +You can **just fork or clone** this repository and use it as is. + +✨ It just works. ✨ + +### How to Use a Private Repository + +If you want to have a private repository, GitHub won't allow you to simply fork it as it doesn't allow changing the visibility of forks. + +But you can do the following: + +- Create a new GitHub repo, for example `my-full-stack`. +- Clone this repository manually, set the name with the name of the project you want to use, for example `my-full-stack`: + +```bash +git clone git@github.com:fastapi/full-stack-fastapi-template.git my-full-stack +``` + +- Enter into the new directory: + +```bash +cd my-full-stack +``` + +- Set the new origin to your new repository, copy it from the GitHub interface, for example: + +```bash +git remote set-url origin git@github.com:octocat/my-full-stack.git +``` + +- Add this repo as another "remote" to allow you to get updates later: + +```bash +git remote add upstream git@github.com:fastapi/full-stack-fastapi-template.git +``` + +- Push the code to your new repository: + +```bash +git push -u origin master +``` + +### Update From the Original Template + +After cloning the repository, and after doing changes, you might want to get the latest changes from this original template. + +- Make sure you added the original repository as a remote, you can check it with: + +```bash +git remote -v + +origin git@github.com:octocat/my-full-stack.git (fetch) +origin git@github.com:octocat/my-full-stack.git (push) +upstream git@github.com:fastapi/full-stack-fastapi-template.git (fetch) +upstream git@github.com:fastapi/full-stack-fastapi-template.git (push) +``` + +- Pull the latest changes without merging: + +```bash +git pull --no-commit upstream master +``` + +This will download the latest changes from this template without committing them, that way you can check everything is right before committing. + +- If there are conflicts, solve them in your editor. + +- Once you are done, commit the changes: + +```bash +git merge --continue +``` + +### Configure + +You can then update configs in the `.env` files to customize your configurations. + +Before deploying it, make sure you change at least the values for: + +- `SECRET_KEY` +- `FIRST_SUPERUSER_PASSWORD` +- `POSTGRES_PASSWORD` + +You can (and should) pass these as environment variables from secrets. + +Read the [deployment.md](./deployment.md) docs for more details. + +### Generate Secret Keys + +Some environment variables in the `.env` file have a default value of `changethis`. + +You have to change them with a secret key, to generate secret keys you can run the following command: + +```bash +python -c "import secrets; print(secrets.token_urlsafe(32))" +``` + +Copy the content and use that as password / secret key. And run that again to generate another secure key. + +## How To Use It - Alternative With Copier + +This repository also supports generating a new project using [Copier](https://copier.readthedocs.io). + +It will copy all the files, ask you configuration questions, and update the `.env` files with your answers. + +### Install Copier + +You can install Copier with: + +```bash +pip install copier +``` + +Or better, if you have [`pipx`](https://pipx.pypa.io/), you can run it with: + +```bash +pipx install copier +``` + +**Note**: If you have `pipx`, installing copier is optional, you could run it directly. + +### Generate a Project With Copier + +Decide a name for your new project's directory, you will use it below. For example, `my-awesome-project`. + +Go to the directory that will be the parent of your project, and run the command with your project's name: + +```bash +copier copy https://github.com/fastapi/full-stack-fastapi-template my-awesome-project --trust +``` + +If you have `pipx` and you didn't install `copier`, you can run it directly: + +```bash +pipx run copier copy https://github.com/fastapi/full-stack-fastapi-template my-awesome-project --trust +``` + +**Note** the `--trust` option is necessary to be able to execute a [post-creation script](https://github.com/fastapi/full-stack-fastapi-template/blob/master/.copier/update_dotenv.py) that updates your `.env` files. + +### Input Variables + +Copier will ask you for some data, you might want to have at hand before generating the project. + +But don't worry, you can just update any of that in the `.env` files afterwards. + +The input variables, with their default values (some auto generated) are: + +- `project_name`: (default: `"FastAPI Project"`) The name of the project, shown to API users (in .env). +- `stack_name`: (default: `"fastapi-project"`) The name of the stack used for Docker Compose labels and project name (no spaces, no periods) (in .env). +- `secret_key`: (default: `"changethis"`) The secret key for the project, used for security, stored in .env, you can generate one with the method above. +- `first_superuser`: (default: `"admin@example.com"`) The email of the first superuser (in .env). +- `first_superuser_password`: (default: `"changethis"`) The password of the first superuser (in .env). +- `smtp_host`: (default: "") The SMTP server host to send emails, you can set it later in .env. +- `smtp_user`: (default: "") The SMTP server user to send emails, you can set it later in .env. +- `smtp_password`: (default: "") The SMTP server password to send emails, you can set it later in .env. +- `emails_from_email`: (default: `"info@example.com"`) The email account to send emails from, you can set it later in .env. +- `postgres_password`: (default: `"changethis"`) The password for the PostgreSQL database, stored in .env, you can generate one with the method above. +- `sentry_dsn`: (default: "") The DSN for Sentry, if you are using it, you can set it later in .env. + +## Backend Development + +Backend docs: [backend/README.md](./backend/README.md). + +## Frontend Development + +Frontend docs: [frontend/README.md](./frontend/README.md). + +## Deployment + +Deployment docs: [deployment.md](./deployment.md). + +## Development + +General development docs: [development.md](./development.md). + +This includes using Docker Compose, custom local domains, `.env` configurations, etc. + +## Release Notes + +Check the file [release-notes.md](./release-notes.md). + +## License + +The Full Stack FastAPI Template is licensed under the terms of the MIT license. diff --git a/skills/outpost/examples/fastapi-saas/SECURITY.md b/skills/outpost/examples/fastapi-saas/SECURITY.md new file mode 100644 index 0000000..0045fb8 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/SECURITY.md @@ -0,0 +1,29 @@ +# 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. 🙇 diff --git a/skills/outpost/examples/fastapi-saas/backend/.dockerignore b/skills/outpost/examples/fastapi-saas/backend/.dockerignore new file mode 100644 index 0000000..c0de4ab --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/backend/.dockerignore @@ -0,0 +1,8 @@ +# Python +__pycache__ +app.egg-info +*.pyc +.mypy_cache +.coverage +htmlcov +.venv diff --git a/skills/outpost/examples/fastapi-saas/backend/.gitignore b/skills/outpost/examples/fastapi-saas/backend/.gitignore new file mode 100644 index 0000000..63f67bc --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/backend/.gitignore @@ -0,0 +1,8 @@ +__pycache__ +app.egg-info +*.pyc +.mypy_cache +.coverage +htmlcov +.cache +.venv diff --git a/skills/outpost/examples/fastapi-saas/backend/Dockerfile b/skills/outpost/examples/fastapi-saas/backend/Dockerfile new file mode 100644 index 0000000..9f31dcd --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/backend/Dockerfile @@ -0,0 +1,45 @@ +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"] diff --git a/skills/outpost/examples/fastapi-saas/backend/README.md b/skills/outpost/examples/fastapi-saas/backend/README.md new file mode 100644 index 0000000..521ee3f --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/backend/README.md @@ -0,0 +1,172 @@ +# 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. diff --git a/skills/outpost/examples/fastapi-saas/backend/alembic.ini b/skills/outpost/examples/fastapi-saas/backend/alembic.ini new file mode 100755 index 0000000..24841c2 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/backend/alembic.ini @@ -0,0 +1,71 @@ +# 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 diff --git a/skills/outpost/examples/fastapi-saas/backend/app/__init__.py b/skills/outpost/examples/fastapi-saas/backend/app/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/skills/outpost/examples/fastapi-saas/backend/app/alembic/README b/skills/outpost/examples/fastapi-saas/backend/app/alembic/README new file mode 100755 index 0000000..2500aa1 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/backend/app/alembic/README @@ -0,0 +1 @@ +Generic single-database configuration. diff --git a/skills/outpost/examples/fastapi-saas/backend/app/alembic/env.py b/skills/outpost/examples/fastapi-saas/backend/app/alembic/env.py new file mode 100755 index 0000000..fb993cf --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/backend/app/alembic/env.py @@ -0,0 +1,86 @@ +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) + assert configuration is not None + 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() diff --git a/skills/outpost/examples/fastapi-saas/backend/app/alembic/script.py.mako b/skills/outpost/examples/fastapi-saas/backend/app/alembic/script.py.mako new file mode 100755 index 0000000..217a9a8 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/backend/app/alembic/script.py.mako @@ -0,0 +1,25 @@ +"""${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"} diff --git a/skills/outpost/examples/fastapi-saas/backend/app/alembic/versions/.keep b/skills/outpost/examples/fastapi-saas/backend/app/alembic/versions/.keep new file mode 100755 index 0000000..e69de29 diff --git a/skills/outpost/examples/fastapi-saas/backend/app/alembic/versions/1a31ce608336_add_cascade_delete_relationships.py b/skills/outpost/examples/fastapi-saas/backend/app/alembic/versions/1a31ce608336_add_cascade_delete_relationships.py new file mode 100644 index 0000000..a524690 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/backend/app/alembic/versions/1a31ce608336_add_cascade_delete_relationships.py @@ -0,0 +1,37 @@ +"""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('item_owner_id_fkey', '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 ### diff --git a/skills/outpost/examples/fastapi-saas/backend/app/alembic/versions/9c0a54914c78_add_max_length_for_string_varchar_.py b/skills/outpost/examples/fastapi-saas/backend/app/alembic/versions/9c0a54914c78_add_max_length_for_string_varchar_.py new file mode 100755 index 0000000..78a4177 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/backend/app/alembic/versions/9c0a54914c78_add_max_length_for_string_varchar_.py @@ -0,0 +1,69 @@ +"""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) diff --git a/skills/outpost/examples/fastapi-saas/backend/app/alembic/versions/d98dd8ec85a3_edit_replace_id_integers_in_all_models_.py b/skills/outpost/examples/fastapi-saas/backend/app/alembic/versions/d98dd8ec85a3_edit_replace_id_integers_in_all_models_.py new file mode 100755 index 0000000..37af1fa --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/backend/app/alembic/versions/d98dd8ec85a3_edit_replace_id_integers_in_all_models_.py @@ -0,0 +1,90 @@ +"""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']) diff --git a/skills/outpost/examples/fastapi-saas/backend/app/alembic/versions/e2412789c190_initialize_models.py b/skills/outpost/examples/fastapi-saas/backend/app/alembic/versions/e2412789c190_initialize_models.py new file mode 100644 index 0000000..7529ea9 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/backend/app/alembic/versions/e2412789c190_initialize_models.py @@ -0,0 +1,54 @@ +"""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 ### diff --git a/skills/outpost/examples/fastapi-saas/backend/app/alembic/versions/fe56fa70289e_add_created_at_to_user_and_item.py b/skills/outpost/examples/fastapi-saas/backend/app/alembic/versions/fe56fa70289e_add_created_at_to_user_and_item.py new file mode 100644 index 0000000..3e15754 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/backend/app/alembic/versions/fe56fa70289e_add_created_at_to_user_and_item.py @@ -0,0 +1,31 @@ +"""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 ### diff --git a/skills/outpost/examples/fastapi-saas/backend/app/api/__init__.py b/skills/outpost/examples/fastapi-saas/backend/app/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/skills/outpost/examples/fastapi-saas/backend/app/api/deps.py b/skills/outpost/examples/fastapi-saas/backend/app/api/deps.py new file mode 100644 index 0000000..c2b83c8 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/backend/app/api/deps.py @@ -0,0 +1,57 @@ +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 diff --git a/skills/outpost/examples/fastapi-saas/backend/app/api/main.py b/skills/outpost/examples/fastapi-saas/backend/app/api/main.py new file mode 100644 index 0000000..14d21f4 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/backend/app/api/main.py @@ -0,0 +1,15 @@ +from fastapi import APIRouter + +from app.api.routes import items, login, outpost, 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) +api_router.include_router(outpost.router) + + +if settings.ENVIRONMENT == "local": + api_router.include_router(private.router) diff --git a/skills/outpost/examples/fastapi-saas/backend/app/api/routes/__init__.py b/skills/outpost/examples/fastapi-saas/backend/app/api/routes/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/skills/outpost/examples/fastapi-saas/backend/app/api/routes/items.py b/skills/outpost/examples/fastapi-saas/backend/app/api/routes/items.py new file mode 100644 index 0000000..f0eb30e --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/backend/app/api/routes/items.py @@ -0,0 +1,113 @@ +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() + + items_public = [ItemPublic.model_validate(item) for item in items] + return ItemsPublic(data=items_public, 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") diff --git a/skills/outpost/examples/fastapi-saas/backend/app/api/routes/login.py b/skills/outpost/examples/fastapi-saas/backend/app/api/routes/login.py new file mode 100644 index 0000000..58441e3 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/backend/app/api/routes/login.py @@ -0,0 +1,123 @@ +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} + ) diff --git a/skills/outpost/examples/fastapi-saas/backend/app/api/routes/outpost.py b/skills/outpost/examples/fastapi-saas/backend/app/api/routes/outpost.py new file mode 100644 index 0000000..f3a7274 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/backend/app/api/routes/outpost.py @@ -0,0 +1,319 @@ +""" +Outpost proxy routes — BFF pattern. + +Each signed-in user is a tenant in Outpost (tenant_id = user.id). +The browser calls these endpoints; the backend forwards to Outpost using the +server-side OUTPOST_API_KEY so the admin key never reaches the client. +""" + +import logging +from typing import Any + +import httpx +from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Request + +from app.api.deps import CurrentUser, get_current_active_superuser +from app.core.config import settings + +logger = logging.getLogger(__name__) + +router = APIRouter(prefix="/outpost", tags=["outpost"]) + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + + +def _outpost_headers() -> dict[str, str]: + if not settings.OUTPOST_API_KEY: + raise HTTPException( + status_code=503, + detail="Outpost integration is not configured (OUTPOST_API_KEY missing).", + ) + return { + "Authorization": f"Bearer {settings.OUTPOST_API_KEY}", + "Content-Type": "application/json", + } + + +def _base() -> str: + return settings.OUTPOST_API_BASE_URL.rstrip("/") + + +def _raise_for_outpost(response: httpx.Response) -> None: + """Re-raise Outpost errors as FastAPI HTTPExceptions.""" + if response.is_success: + return + try: + detail = response.json() + except Exception: + detail = response.text or "Outpost API error" + raise HTTPException(status_code=response.status_code, detail=detail) + + +def _upsert_tenant(tenant_id: str) -> None: + """Best-effort tenant upsert — does not fail the request if Outpost is unavailable.""" + if not settings.OUTPOST_API_KEY: + return + try: + with httpx.Client(timeout=10) as client: + client.put( + f"{_base()}/tenants/{tenant_id}", + json={}, + headers=_outpost_headers(), + ) + except Exception as exc: # noqa: BLE001 + logger.warning("Outpost tenant upsert failed for %s: %s", tenant_id, exc) + + +# --------------------------------------------------------------------------- +# Metadata endpoints (no tenant context needed) +# --------------------------------------------------------------------------- + + +@router.get("/destination-types") +def list_destination_types() -> Any: + """Return available destination types with their config schemas.""" + with httpx.Client(timeout=15) as client: + resp = client.get(f"{_base()}/destination-types", headers=_outpost_headers()) + _raise_for_outpost(resp) + return resp.json() + + +@router.get("/topics") +def list_topics() -> Any: + """Return topics configured in the Outpost project.""" + with httpx.Client(timeout=15) as client: + resp = client.get(f"{_base()}/topics", headers=_outpost_headers()) + _raise_for_outpost(resp) + return resp.json() + + +# --------------------------------------------------------------------------- +# Destination management (tenant-scoped) +# --------------------------------------------------------------------------- + + +@router.get("/destinations") +def list_destinations(current_user: CurrentUser) -> Any: + """List all destinations for the signed-in user's tenant.""" + tenant_id = str(current_user.id) + # No upsert here — the tenant is provisioned at signup (see _publish_user_created). + # create_destination carries a safety-net upsert for accounts created before this + # integration was deployed. + with httpx.Client(timeout=15) as client: + resp = client.get( + f"{_base()}/tenants/{tenant_id}/destinations", + headers=_outpost_headers(), + ) + _raise_for_outpost(resp) + return resp.json() + + +@router.post("/destinations", status_code=201) +def create_destination(request_body: dict[str, Any], current_user: CurrentUser) -> Any: + """Create a new destination for the signed-in user's tenant.""" + tenant_id = str(current_user.id) + _upsert_tenant(tenant_id) + with httpx.Client(timeout=15) as client: + resp = client.post( + f"{_base()}/tenants/{tenant_id}/destinations", + json=request_body, + headers=_outpost_headers(), + ) + _raise_for_outpost(resp) + return resp.json() + + +@router.get("/destinations/{destination_id}") +def get_destination(destination_id: str, current_user: CurrentUser) -> Any: + """Get a specific destination.""" + tenant_id = str(current_user.id) + with httpx.Client(timeout=15) as client: + resp = client.get( + f"{_base()}/tenants/{tenant_id}/destinations/{destination_id}", + headers=_outpost_headers(), + ) + _raise_for_outpost(resp) + return resp.json() + + +@router.put("/destinations/{destination_id}") +def update_destination( + destination_id: str, request_body: dict[str, Any], current_user: CurrentUser +) -> Any: + """Update a destination.""" + tenant_id = str(current_user.id) + with httpx.Client(timeout=15) as client: + resp = client.put( + f"{_base()}/tenants/{tenant_id}/destinations/{destination_id}", + json=request_body, + headers=_outpost_headers(), + ) + _raise_for_outpost(resp) + return resp.json() + + +@router.delete("/destinations/{destination_id}", status_code=200) +def delete_destination(destination_id: str, current_user: CurrentUser) -> Any: + """Delete a destination.""" + tenant_id = str(current_user.id) + with httpx.Client(timeout=15) as client: + resp = client.delete( + f"{_base()}/tenants/{tenant_id}/destinations/{destination_id}", + headers=_outpost_headers(), + ) + _raise_for_outpost(resp) + return resp.json() + + +@router.put("/destinations/{destination_id}/enable") +def enable_destination(destination_id: str, current_user: CurrentUser) -> Any: + """Enable a disabled destination (Outpost uses PUT for enable/disable).""" + tenant_id = str(current_user.id) + with httpx.Client(timeout=15) as client: + resp = client.put( + f"{_base()}/tenants/{tenant_id}/destinations/{destination_id}/enable", + headers=_outpost_headers(), + ) + _raise_for_outpost(resp) + return resp.json() + + +@router.put("/destinations/{destination_id}/disable") +def disable_destination(destination_id: str, current_user: CurrentUser) -> Any: + """Disable a destination (Outpost uses PUT for enable/disable).""" + tenant_id = str(current_user.id) + with httpx.Client(timeout=15) as client: + resp = client.put( + f"{_base()}/tenants/{tenant_id}/destinations/{destination_id}/disable", + headers=_outpost_headers(), + ) + _raise_for_outpost(resp) + return resp.json() + + +# --------------------------------------------------------------------------- +# Activity: events and attempts (tenant + destination scoped) +# --------------------------------------------------------------------------- + + +@router.get("/destinations/{destination_id}/events") +def list_destination_events( + destination_id: str, + current_user: CurrentUser, + limit: int = 50, + next: str | None = None, +) -> Any: + """ + List events for a specific destination. + + Uses the tenant-scoped destination attempts endpoint to derive events, + because the global /events?destination_id filter has a known Outpost API + issue. We call /attempts for the destination (which always works) and + return that data; the frontend activity page uses attempts as its primary + list anyway. + """ + tenant_id = str(current_user.id) + params: dict[str, Any] = {"limit": limit} + if next: + params["next"] = next + with httpx.Client(timeout=15) as client: + resp = client.get( + f"{_base()}/tenants/{tenant_id}/destinations/{destination_id}/attempts", + params=params, + headers=_outpost_headers(), + ) + _raise_for_outpost(resp) + return resp.json() + + +@router.get("/destinations/{destination_id}/attempts") +def list_destination_attempts( + destination_id: str, + current_user: CurrentUser, + limit: int = 50, + next: str | None = None, +) -> Any: + """List delivery attempts for a specific destination.""" + tenant_id = str(current_user.id) + params: dict[str, Any] = {"limit": limit} + if next: + params["next"] = next + with httpx.Client(timeout=15) as client: + resp = client.get( + f"{_base()}/tenants/{tenant_id}/destinations/{destination_id}/attempts", + params=params, + headers=_outpost_headers(), + ) + _raise_for_outpost(resp) + return resp.json() + + +@router.get("/events/{event_id}/attempts") +def list_event_attempts( + event_id: str, + current_user: CurrentUser, +) -> Any: + """List attempts for a specific event.""" + tenant_id = str(current_user.id) + with httpx.Client(timeout=15) as client: + resp = client.get( + f"{_base()}/attempts", + params={"tenant_id": tenant_id, "event_id": event_id}, + headers=_outpost_headers(), + ) + _raise_for_outpost(resp) + return resp.json() + + +# --------------------------------------------------------------------------- +# Retry +# --------------------------------------------------------------------------- + + +@router.post("/retry") +def retry_event(request_body: dict[str, Any], current_user: CurrentUser) -> Any: + """Manually retry a failed event delivery attempt.""" + with httpx.Client(timeout=15) as client: + resp = client.post( + f"{_base()}/retry", + json=request_body, + headers=_outpost_headers(), + ) + _raise_for_outpost(resp) + return resp.json() + + +# --------------------------------------------------------------------------- +# Test publish (separate from domain publishes — lets users verify destinations) +# --------------------------------------------------------------------------- + + +@router.post("/test-publish") +def test_publish(current_user: CurrentUser) -> Any: + """ + Publish a test event to the current user's tenant. + This is a separate control from domain events — only for verifying + destination delivery from the UI. + """ + tenant_id = str(current_user.id) + # Tenant was provisioned at signup; no upsert needed here. + with httpx.Client(timeout=15) as client: + resp = client.post( + f"{_base()}/publish", + json={ + "tenant_id": tenant_id, + "topic": "user.created", + "eligible_for_retry": True, + "metadata": {"source": "test-publish"}, + "data": { + "user_id": tenant_id, + "email": current_user.email, + "test": True, + }, + }, + headers=_outpost_headers(), + ) + _raise_for_outpost(resp) + return resp.json() diff --git a/skills/outpost/examples/fastapi-saas/backend/app/api/routes/private.py b/skills/outpost/examples/fastapi-saas/backend/app/api/routes/private.py new file mode 100644 index 0000000..9f33ef1 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/backend/app/api/routes/private.py @@ -0,0 +1,38 @@ +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 diff --git a/skills/outpost/examples/fastapi-saas/backend/app/api/routes/users.py b/skills/outpost/examples/fastapi-saas/backend/app/api/routes/users.py new file mode 100644 index 0000000..32460db --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/backend/app/api/routes/users.py @@ -0,0 +1,281 @@ +import logging +import uuid +from typing import Any + +import httpx +from fastapi import APIRouter, BackgroundTasks, 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 + +logger = logging.getLogger(__name__) + + +def _publish_user_created(user: User) -> None: + """ + Publish a user.created event to Outpost. + Called in a background task — failures are logged but do not affect the response. + The user's UUID is used as the tenant_id so each customer maps to one Outpost tenant. + """ + if not settings.OUTPOST_API_KEY: + return + base = settings.OUTPOST_API_BASE_URL.rstrip("/") + headers = { + "Authorization": f"Bearer {settings.OUTPOST_API_KEY}", + "Content-Type": "application/json", + } + tenant_id = str(user.id) + try: + with httpx.Client(timeout=10) as client: + # Ensure the tenant exists before publishing + client.put(f"{base}/tenants/{tenant_id}", json={}, headers=headers) + # Publish the domain event + client.post( + f"{base}/publish", + json={ + "tenant_id": tenant_id, + "topic": "user.created", + "eligible_for_retry": True, + "data": { + "user_id": tenant_id, + "email": user.email, + "full_name": user.full_name, + }, + }, + headers=headers, + ) + except Exception as exc: # noqa: BLE001 + logger.warning("Outpost publish failed for user %s: %s", tenant_id, exc) + +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() + + users_public = [UserPublic.model_validate(user) for user in users] + return UsersPublic(data=users_public, count=count) + + +@router.post( + "/", dependencies=[Depends(get_current_active_superuser)], response_model=UserPublic +) +def create_user( + *, session: SessionDep, user_in: UserCreate, background_tasks: BackgroundTasks +) -> 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, + ) + # Publish user.created event to Outpost (best-effort, non-blocking) + background_tasks.add_task(_publish_user_created, user) + 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, background_tasks: BackgroundTasks +) -> 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) + # Publish user.created event to Outpost (best-effort, non-blocking) + background_tasks.add_task(_publish_user_created, user) + 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") diff --git a/skills/outpost/examples/fastapi-saas/backend/app/api/routes/utils.py b/skills/outpost/examples/fastapi-saas/backend/app/api/routes/utils.py new file mode 100644 index 0000000..fc09341 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/backend/app/api/routes/utils.py @@ -0,0 +1,31 @@ +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 diff --git a/skills/outpost/examples/fastapi-saas/backend/app/backend_pre_start.py b/skills/outpost/examples/fastapi-saas/backend/app/backend_pre_start.py new file mode 100644 index 0000000..c2f8e29 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/backend/app/backend_pre_start.py @@ -0,0 +1,39 @@ +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() diff --git a/skills/outpost/examples/fastapi-saas/backend/app/core/__init__.py b/skills/outpost/examples/fastapi-saas/backend/app/core/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/skills/outpost/examples/fastapi-saas/backend/app/core/config.py b/skills/outpost/examples/fastapi-saas/backend/app/core/config.py new file mode 100644 index 0000000..58e8207 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/backend/app/core/config.py @@ -0,0 +1,123 @@ +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 + + # Hookdeck Outpost + OUTPOST_API_KEY: str | None = None + OUTPOST_API_BASE_URL: str = "https://api.outpost.hookdeck.com/2025-07-01" + + 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 diff --git a/skills/outpost/examples/fastapi-saas/backend/app/core/db.py b/skills/outpost/examples/fastapi-saas/backend/app/core/db.py new file mode 100644 index 0000000..ba991fb --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/backend/app/core/db.py @@ -0,0 +1,33 @@ +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) diff --git a/skills/outpost/examples/fastapi-saas/backend/app/core/security.py b/skills/outpost/examples/fastapi-saas/backend/app/core/security.py new file mode 100644 index 0000000..1e49ebc --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/backend/app/core/security.py @@ -0,0 +1,36 @@ +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) diff --git a/skills/outpost/examples/fastapi-saas/backend/app/crud.py b/skills/outpost/examples/fastapi-saas/backend/app/crud.py new file mode 100644 index 0000000..a8ceba6 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/backend/app/crud.py @@ -0,0 +1,68 @@ +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 diff --git a/skills/outpost/examples/fastapi-saas/backend/app/email-templates/src/new_account.mjml b/skills/outpost/examples/fastapi-saas/backend/app/email-templates/src/new_account.mjml new file mode 100644 index 0000000..f41a3e3 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/backend/app/email-templates/src/new_account.mjml @@ -0,0 +1,15 @@ + + + + + {{ project_name }} - New Account + Welcome to your new account! + Here are your account details: + Username: {{ username }} + Password: {{ password }} + Go to Dashboard + + + + + diff --git a/skills/outpost/examples/fastapi-saas/backend/app/email-templates/src/reset_password.mjml b/skills/outpost/examples/fastapi-saas/backend/app/email-templates/src/reset_password.mjml new file mode 100644 index 0000000..743f5d7 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/backend/app/email-templates/src/reset_password.mjml @@ -0,0 +1,17 @@ + + + + + {{ project_name }} - Password Recovery + Hello {{ username }} + We've received a request to reset your password. You can do it by clicking the button below: + Reset password + Or copy and paste the following link into your browser: + {{ link }} + This password will expire in {{ valid_hours }} hours. + + If you didn't request a password recovery you can disregard this email. + + + + diff --git a/skills/outpost/examples/fastapi-saas/backend/app/email-templates/src/test_email.mjml b/skills/outpost/examples/fastapi-saas/backend/app/email-templates/src/test_email.mjml new file mode 100644 index 0000000..45d58d6 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/backend/app/email-templates/src/test_email.mjml @@ -0,0 +1,11 @@ + + + + + {{ project_name }} + Test email for: {{ email }} + + + + + diff --git a/skills/outpost/examples/fastapi-saas/backend/app/initial_data.py b/skills/outpost/examples/fastapi-saas/backend/app/initial_data.py new file mode 100644 index 0000000..d806c3d --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/backend/app/initial_data.py @@ -0,0 +1,23 @@ +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() diff --git a/skills/outpost/examples/fastapi-saas/backend/app/main.py b/skills/outpost/examples/fastapi-saas/backend/app/main.py new file mode 100644 index 0000000..9a95801 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/backend/app/main.py @@ -0,0 +1,33 @@ +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) diff --git a/skills/outpost/examples/fastapi-saas/backend/app/models.py b/skills/outpost/examples/fastapi-saas/backend/app/models.py new file mode 100644 index 0000000..0ae3cf6 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/backend/app/models.py @@ -0,0 +1,129 @@ +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[assignment] + 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[assignment] + + +# 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) diff --git a/skills/outpost/examples/fastapi-saas/backend/app/tests_pre_start.py b/skills/outpost/examples/fastapi-saas/backend/app/tests_pre_start.py new file mode 100644 index 0000000..0ce6045 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/backend/app/tests_pre_start.py @@ -0,0 +1,39 @@ +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() diff --git a/skills/outpost/examples/fastapi-saas/backend/app/utils.py b/skills/outpost/examples/fastapi-saas/backend/app/utils.py new file mode 100644 index 0000000..29fcfc1 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/backend/app/utils.py @@ -0,0 +1,123 @@ +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-untyped] +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 diff --git a/skills/outpost/examples/fastapi-saas/backend/pyproject.toml b/skills/outpost/examples/fastapi-saas/backend/pyproject.toml new file mode 100644 index 0000000..b96ac66 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/backend/pyproject.toml @@ -0,0 +1,82 @@ +[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", + "outpost_sdk>=0.1.0", +] + +[dependency-groups] +dev = [ + "pytest<8.0.0,>=7.4.3", + "mypy<2.0.0,>=1.8.0", + "ty>=0.0.25", + "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 + +[tool.ty.terminal] +error-on-warning = true diff --git a/skills/outpost/examples/fastapi-saas/backend/scripts/format.sh b/skills/outpost/examples/fastapi-saas/backend/scripts/format.sh new file mode 100755 index 0000000..7be2f81 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/backend/scripts/format.sh @@ -0,0 +1,5 @@ +#!/bin/sh -e +set -x + +ruff check app scripts --fix +ruff format app scripts diff --git a/skills/outpost/examples/fastapi-saas/backend/scripts/lint.sh b/skills/outpost/examples/fastapi-saas/backend/scripts/lint.sh new file mode 100644 index 0000000..ccc981e --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/backend/scripts/lint.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash + +set -e +set -x + +mypy app +ty check app +ruff check app +ruff format app --check diff --git a/skills/outpost/examples/fastapi-saas/backend/scripts/prestart.sh b/skills/outpost/examples/fastapi-saas/backend/scripts/prestart.sh new file mode 100644 index 0000000..1b395d5 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/backend/scripts/prestart.sh @@ -0,0 +1,13 @@ +#! /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 diff --git a/skills/outpost/examples/fastapi-saas/backend/scripts/test.sh b/skills/outpost/examples/fastapi-saas/backend/scripts/test.sh new file mode 100755 index 0000000..38c3e89 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/backend/scripts/test.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash + +set -e +set -x + +coverage run -m pytest tests/ +coverage report +coverage html --title "${@-coverage}" diff --git a/skills/outpost/examples/fastapi-saas/backend/scripts/tests-start.sh b/skills/outpost/examples/fastapi-saas/backend/scripts/tests-start.sh new file mode 100644 index 0000000..89dcb0d --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/backend/scripts/tests-start.sh @@ -0,0 +1,7 @@ +#! /usr/bin/env bash +set -e +set -x + +python app/tests_pre_start.py + +bash scripts/test.sh "$@" diff --git a/skills/outpost/examples/fastapi-saas/backend/test_outpost_wire.py b/skills/outpost/examples/fastapi-saas/backend/test_outpost_wire.py new file mode 100644 index 0000000..1adecc9 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/backend/test_outpost_wire.py @@ -0,0 +1,42 @@ +""" +Standalone tests for Outpost BFF error mapping. + +Kept at backend/ (not under tests/) so template tests/conftest.py does not run +(session DB fixture would require PostgreSQL). +Mirrors logic in app.api.routes.outpost._raise_for_outpost — keep in sync if that changes. +""" + +import httpx +import pytest +from fastapi import HTTPException + + +def raise_for_outpost_response(response: httpx.Response) -> None: + if response.is_success: + return + try: + detail = response.json() + except Exception: + detail = response.text or "Outpost API error" + raise HTTPException(status_code=response.status_code, detail=detail) + + +def test_raise_for_outpost_success() -> None: + resp = httpx.Response(200, json={"ok": True}) + raise_for_outpost_response(resp) + + +def test_raise_for_outpost_json_body() -> None: + resp = httpx.Response(422, json={"error": "invalid"}) + with pytest.raises(HTTPException) as exc: + raise_for_outpost_response(resp) + assert exc.value.status_code == 422 + assert exc.value.detail == {"error": "invalid"} + + +def test_raise_for_outpost_text_body() -> None: + resp = httpx.Response(502, text="bad gateway") + with pytest.raises(HTTPException) as exc: + raise_for_outpost_response(resp) + assert exc.value.status_code == 502 + assert exc.value.detail == "bad gateway" diff --git a/skills/outpost/examples/fastapi-saas/backend/tests/__init__.py b/skills/outpost/examples/fastapi-saas/backend/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/skills/outpost/examples/fastapi-saas/backend/tests/api/__init__.py b/skills/outpost/examples/fastapi-saas/backend/tests/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/skills/outpost/examples/fastapi-saas/backend/tests/api/routes/__init__.py b/skills/outpost/examples/fastapi-saas/backend/tests/api/routes/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/skills/outpost/examples/fastapi-saas/backend/tests/api/routes/test_items.py b/skills/outpost/examples/fastapi-saas/backend/tests/api/routes/test_items.py new file mode 100644 index 0000000..3e82cd0 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/backend/tests/api/routes/test_items.py @@ -0,0 +1,164 @@ +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" diff --git a/skills/outpost/examples/fastapi-saas/backend/tests/api/routes/test_login.py b/skills/outpost/examples/fastapi-saas/backend/tests/api/routes/test_login.py new file mode 100644 index 0000000..96677a2 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/backend/tests/api/routes/test_login.py @@ -0,0 +1,191 @@ +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") diff --git a/skills/outpost/examples/fastapi-saas/backend/tests/api/routes/test_private.py b/skills/outpost/examples/fastapi-saas/backend/tests/api/routes/test_private.py new file mode 100644 index 0000000..1e1f985 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/backend/tests/api/routes/test_private.py @@ -0,0 +1,26 @@ +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" diff --git a/skills/outpost/examples/fastapi-saas/backend/tests/api/routes/test_users.py b/skills/outpost/examples/fastapi-saas/backend/tests/api/routes/test_users.py new file mode 100644 index 0000000..9c4cdd5 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/backend/tests/api/routes/test_users.py @@ -0,0 +1,521 @@ +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" diff --git a/skills/outpost/examples/fastapi-saas/backend/tests/conftest.py b/skills/outpost/examples/fastapi-saas/backend/tests/conftest.py new file mode 100644 index 0000000..8ddab7b --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/backend/tests/conftest.py @@ -0,0 +1,42 @@ +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 + ) diff --git a/skills/outpost/examples/fastapi-saas/backend/tests/crud/__init__.py b/skills/outpost/examples/fastapi-saas/backend/tests/crud/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/skills/outpost/examples/fastapi-saas/backend/tests/crud/test_user.py b/skills/outpost/examples/fastapi-saas/backend/tests/crud/test_user.py new file mode 100644 index 0000000..3db77ef --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/backend/tests/crud/test_user.py @@ -0,0 +1,130 @@ +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 diff --git a/skills/outpost/examples/fastapi-saas/backend/tests/scripts/__init__.py b/skills/outpost/examples/fastapi-saas/backend/tests/scripts/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/skills/outpost/examples/fastapi-saas/backend/tests/scripts/test_backend_pre_start.py b/skills/outpost/examples/fastapi-saas/backend/tests/scripts/test_backend_pre_start.py new file mode 100644 index 0000000..e8f35c6 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/backend/tests/scripts/test_backend_pre_start.py @@ -0,0 +1,33 @@ +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) diff --git a/skills/outpost/examples/fastapi-saas/backend/tests/scripts/test_test_pre_start.py b/skills/outpost/examples/fastapi-saas/backend/tests/scripts/test_test_pre_start.py new file mode 100644 index 0000000..180bdd5 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/backend/tests/scripts/test_test_pre_start.py @@ -0,0 +1,33 @@ +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) diff --git a/skills/outpost/examples/fastapi-saas/backend/tests/utils/__init__.py b/skills/outpost/examples/fastapi-saas/backend/tests/utils/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/skills/outpost/examples/fastapi-saas/backend/tests/utils/item.py b/skills/outpost/examples/fastapi-saas/backend/tests/utils/item.py new file mode 100644 index 0000000..ee51b35 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/backend/tests/utils/item.py @@ -0,0 +1,16 @@ +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) diff --git a/skills/outpost/examples/fastapi-saas/backend/tests/utils/user.py b/skills/outpost/examples/fastapi-saas/backend/tests/utils/user.py new file mode 100644 index 0000000..5867431 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/backend/tests/utils/user.py @@ -0,0 +1,49 @@ +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) diff --git a/skills/outpost/examples/fastapi-saas/backend/tests/utils/utils.py b/skills/outpost/examples/fastapi-saas/backend/tests/utils/utils.py new file mode 100644 index 0000000..184bac4 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/backend/tests/utils/utils.py @@ -0,0 +1,26 @@ +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 diff --git a/skills/outpost/examples/fastapi-saas/compose.override.yml b/skills/outpost/examples/fastapi-saas/compose.override.yml new file mode 100644 index 0000000..5bf13af --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/compose.override.yml @@ -0,0 +1,136 @@ +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: + # Host 5432 often taken (e.g. other Docker stacks); use 54334 for local eval. + - "54334: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 diff --git a/skills/outpost/examples/fastapi-saas/compose.traefik.yml b/skills/outpost/examples/fastapi-saas/compose.traefik.yml new file mode 100644 index 0000000..bcd7d14 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/compose.traefik.yml @@ -0,0 +1,77 @@ +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 diff --git a/skills/outpost/examples/fastapi-saas/compose.yml b/skills/outpost/examples/fastapi-saas/compose.yml new file mode 100644 index 0000000..2488fc0 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/compose.yml @@ -0,0 +1,174 @@ +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 diff --git a/skills/outpost/examples/fastapi-saas/copier.yml b/skills/outpost/examples/fastapi-saas/copier.yml new file mode 100644 index 0000000..f98e3fc --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/copier.yml @@ -0,0 +1,100 @@ +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] diff --git a/skills/outpost/examples/fastapi-saas/deployment.md b/skills/outpost/examples/fastapi-saas/deployment.md new file mode 100644 index 0000000..4b8ebc1 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/deployment.md @@ -0,0 +1,344 @@ +# FastAPI Project - Deployment + +You can deploy the project using Docker Compose to a remote server. + +This project expects you to have a Traefik proxy handling communication to the outside world and HTTPS certificates. + +You can use CI/CD (continuous integration and continuous deployment) systems to deploy automatically, there are already configurations to do it with GitHub Actions. + +But you have to configure a couple things first. 🤓 + +## Preparation + +* Have a remote server ready and available. +* Configure the DNS records of your domain to point to the IP of the server you just created. +* Configure a wildcard subdomain for your domain, so that you can have multiple subdomains for different services, e.g. `*.fastapi-project.example.com`. This will be useful for accessing different components, like `dashboard.fastapi-project.example.com`, `api.fastapi-project.example.com`, `traefik.fastapi-project.example.com`, `adminer.fastapi-project.example.com`, etc. And also for `staging`, like `dashboard.staging.fastapi-project.example.com`, `adminer.staging.fastapi-project.example.com`, etc. +* Install and configure [Docker](https://docs.docker.com/engine/install/) on the remote server (Docker Engine, not Docker Desktop). + +## Public Traefik + +We need a Traefik proxy to handle incoming connections and HTTPS certificates. + +You need to do these next steps only once. + +### Traefik Docker Compose + +* Create a remote directory to store your Traefik Docker Compose file: + +```bash +mkdir -p /root/code/traefik-public/ +``` + +Copy the Traefik Docker Compose file to your server. You could do it by running the command `rsync` in your local terminal: + +```bash +rsync -a compose.traefik.yml root@your-server.example.com:/root/code/traefik-public/ +``` + +### Traefik Public Network + +This Traefik will expect a Docker "public network" named `traefik-public` to communicate with your stack(s). + +This way, there will be a single public Traefik proxy that handles the communication (HTTP and HTTPS) with the outside world, and then behind that, you could have one or more stacks with different domains, even if they are on the same single server. + +To create a Docker "public network" named `traefik-public` run the following command in your remote server: + +```bash +docker network create traefik-public +``` + +### Traefik Environment Variables + +The Traefik Docker Compose file expects some environment variables to be set in your terminal before starting it. You can do it by running the following commands in your remote server. + +* Create the username for HTTP Basic Auth, e.g.: + +```bash +export USERNAME=admin +``` + +* Create an environment variable with the password for HTTP Basic Auth, e.g.: + +```bash +export PASSWORD=changethis +``` + +* Use openssl to generate the "hashed" version of the password for HTTP Basic Auth and store it in an environment variable: + +```bash +export HASHED_PASSWORD=$(openssl passwd -apr1 $PASSWORD) +``` + +To verify that the hashed password is correct, you can print it: + +```bash +echo $HASHED_PASSWORD +``` + +* Create an environment variable with the domain name for your server, e.g.: + +```bash +export DOMAIN=fastapi-project.example.com +``` + +* Create an environment variable with the email for Let's Encrypt, e.g.: + +```bash +export EMAIL=admin@example.com +``` + +**Note**: you need to set a different email, an email `@example.com` won't work. + +### Start the Traefik Docker Compose + +Go to the directory where you copied the Traefik Docker Compose file in your remote server: + +```bash +cd /root/code/traefik-public/ +``` + +Now with the environment variables set and the `compose.traefik.yml` in place, you can start the Traefik Docker Compose running the following command: + +```bash +docker compose -f compose.traefik.yml up -d +``` + +## Deploy the FastAPI Project + +Now that you have Traefik in place you can deploy your FastAPI project with Docker Compose. + +**Note**: You might want to jump ahead to the section about Continuous Deployment with GitHub Actions. + +## Copy the Code + +```bash +rsync -av --filter=":- .gitignore" ./ root@your-server.example.com:/root/code/app/ +``` + +Note: `--filter=":- .gitignore"` tells `rsync` to use the same rules as git, ignore files ignored by git, like the Python virtual environment. + +## Environment Variables + +You need to set some environment variables first. + +### Generate secret keys + +Some environment variables in the `.env` file have a default value of `changethis`. + +You have to change them with a secret key, to generate secret keys you can run the following command: + +```bash +python -c "import secrets; print(secrets.token_urlsafe(32))" +``` + +Copy the content and use that as password / secret key. And run that again to generate another secure key. + +### Required Environment Variables + +Set the `ENVIRONMENT`, by default `local` (for development), but when deploying to a server you would put something like `staging` or `production`: + +```bash +export ENVIRONMENT=production +``` + +Set the `DOMAIN`, by default `localhost` (for development), but when deploying you would use your own domain, for example: + +```bash +export DOMAIN=fastapi-project.example.com +``` + +Set the `POSTGRES_PASSWORD` to something different than `changethis`: + +```bash +export POSTGRES_PASSWORD="changethis" +``` + +Set the `SECRET_KEY`, used to sign tokens: + +```bash +export SECRET_KEY="changethis" +``` + +Note: you can use the Python command above to generate a secure secret key. + +Set the `FIRST_SUPER_USER_PASSWORD` to something different than `changethis`: + +```bash +export FIRST_SUPERUSER_PASSWORD="changethis" +``` + +Set the `BACKEND_CORS_ORIGINS` to include your domain: + +```bash +export BACKEND_CORS_ORIGINS="https://dashboard.${DOMAIN?Variable not set},https://api.${DOMAIN?Variable not set}" +``` + +You can set several other environment variables: + +* `PROJECT_NAME`: The name of the project, used in the API for the docs and emails. +* `STACK_NAME`: The name of the stack used for Docker Compose labels and project name, this should be different for `staging`, `production`, etc. You could use the same domain replacing dots with dashes, e.g. `fastapi-project-example-com` and `staging-fastapi-project-example-com`. +* `BACKEND_CORS_ORIGINS`: A list of allowed CORS origins separated by commas. +* `FIRST_SUPERUSER`: The email of the first superuser, this superuser will be the one that can create new users. +* `SMTP_HOST`: The SMTP server host to send emails, this would come from your email provider (E.g. Mailgun, Sparkpost, Sendgrid, etc). +* `SMTP_USER`: The SMTP server user to send emails. +* `SMTP_PASSWORD`: The SMTP server password to send emails. +* `EMAILS_FROM_EMAIL`: The email account to send emails from. +* `POSTGRES_SERVER`: The hostname of the PostgreSQL server. You can leave the default of `db`, provided by the same Docker Compose. You normally wouldn't need to change this unless you are using a third-party provider. +* `POSTGRES_PORT`: The port of the PostgreSQL server. You can leave the default. You normally wouldn't need to change this unless you are using a third-party provider. +* `POSTGRES_USER`: The Postgres user, you can leave the default. +* `POSTGRES_DB`: The database name to use for this application. You can leave the default of `app`. +* `SENTRY_DSN`: The DSN for Sentry, if you are using it. + +## GitHub Actions Environment Variables + +There are some environment variables only used by GitHub Actions that you can configure: + +* `LATEST_CHANGES`: Used by the GitHub Action [latest-changes](https://github.com/tiangolo/latest-changes) to automatically add release notes based on the PRs merged. It's a personal access token, read the docs for details. +* `SMOKESHOW_AUTH_KEY`: Used to handle and publish the code coverage using [Smokeshow](https://github.com/samuelcolvin/smokeshow), follow their instructions to create a (free) Smokeshow key. + +### Deploy with Docker Compose + +With the environment variables in place, you can deploy with Docker Compose: + +```bash +cd /root/code/app/ +docker compose -f compose.yml build +docker compose -f compose.yml up -d +``` + +For production you wouldn't want to have the overrides in `compose.override.yml`, that's why we explicitly specify `compose.yml` as the file to use. + +## Continuous Deployment (CD) + +You can use GitHub Actions to deploy your project automatically. 😎 + +You can have multiple environment deployments. + +There are already two environments configured, `staging` and `production`. 🚀 + +### Install GitHub Actions Runner + +* On your remote server, create a user for your GitHub Actions: + +```bash +sudo adduser github +``` + +* Add Docker permissions to the `github` user: + +```bash +sudo usermod -aG docker github +``` + +* Temporarily switch to the `github` user: + +```bash +sudo su - github +``` + +* Go to the `github` user's home directory: + +```bash +cd +``` + +* [Install a GitHub Action self-hosted runner following the official guide](https://docs.github.com/en/actions/hosting-your-own-runners/managing-self-hosted-runners/adding-self-hosted-runners#adding-a-self-hosted-runner-to-a-repository). + +* When asked about labels, add a label for the environment, e.g. `production`. You can also add labels later. + +After installing, the guide would tell you to run a command to start the runner. Nevertheless, it would stop once you terminate that process or if your local connection to your server is lost. + +To make sure it runs on startup and continues running, you can install it as a service. To do that, exit the `github` user and go back to the `root` user: + +```bash +exit +``` + +After you do it, you will be on the previous user again. And you will be on the previous directory, belonging to that user. + +Before being able to go the `github` user directory, you need to become the `root` user (you might already be): + +```bash +sudo su +``` + +* As the `root` user, go to the `actions-runner` directory inside of the `github` user's home directory: + +```bash +cd /home/github/actions-runner +``` + +* Install the self-hosted runner as a service with the user `github`: + +```bash +./svc.sh install github +``` + +* Start the service: + +```bash +./svc.sh start +``` + +* Check the status of the service: + +```bash +./svc.sh status +``` + +You can read more about it in the official guide: [Configuring the self-hosted runner application as a service](https://docs.github.com/en/actions/hosting-your-own-runners/managing-self-hosted-runners/configuring-the-self-hosted-runner-application-as-a-service). + +### Set Secrets + +On your repository, configure secrets for the environment variables you need, the same ones described above, including `SECRET_KEY`, etc. Follow the [official GitHub guide for setting repository secrets](https://docs.github.com/en/actions/security-guides/using-secrets-in-github-actions#creating-secrets-for-a-repository). + +The current Github Actions workflows expect these secrets: + +* `DOMAIN_PRODUCTION` +* `DOMAIN_STAGING` +* `STACK_NAME_PRODUCTION` +* `STACK_NAME_STAGING` +* `EMAILS_FROM_EMAIL` +* `FIRST_SUPERUSER` +* `FIRST_SUPERUSER_PASSWORD` +* `POSTGRES_PASSWORD` +* `SECRET_KEY` +* `LATEST_CHANGES` +* `SMOKESHOW_AUTH_KEY` + +## GitHub Action Deployment Workflows + +There are GitHub Action workflows in the `.github/workflows` directory already configured for deploying to the environments (GitHub Actions runners with the labels): + +* `staging`: after pushing (or merging) to the branch `master`. +* `production`: after publishing a release. + +If you need to add extra environments you could use those as a starting point. + +## URLs + +Replace `fastapi-project.example.com` with your domain. + +### Main Traefik Dashboard + +Traefik UI: `https://traefik.fastapi-project.example.com` + +### Production + +Frontend: `https://dashboard.fastapi-project.example.com` + +Backend API docs: `https://api.fastapi-project.example.com/docs` + +Backend API base URL: `https://api.fastapi-project.example.com` + +Adminer: `https://adminer.fastapi-project.example.com` + +### Staging + +Frontend: `https://dashboard.staging.fastapi-project.example.com` + +Backend API docs: `https://api.staging.fastapi-project.example.com/docs` + +Backend API base URL: `https://api.staging.fastapi-project.example.com` + +Adminer: `https://adminer.staging.fastapi-project.example.com` diff --git a/skills/outpost/examples/fastapi-saas/development.md b/skills/outpost/examples/fastapi-saas/development.md new file mode 100644 index 0000000..7879ffc --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/development.md @@ -0,0 +1,221 @@ +# FastAPI Project - Development + +## Docker Compose + +* Start the local stack with Docker Compose: + +```bash +docker compose watch +``` + +* Now you can open your browser and interact with these URLs: + +Frontend, built with Docker, with routes handled based on the path: + +Backend, JSON based web API based on OpenAPI: + +Automatic interactive documentation with Swagger UI (from the OpenAPI backend): + +Adminer, database web administration: + +Traefik UI, to see how the routes are being handled by the proxy: + +**Note**: The first time you start your stack, it might take a minute for it to be ready. While the backend waits for the database to be ready and configures everything. You can check the logs to monitor it. + +To check the logs, run (in another terminal): + +```bash +docker compose logs +``` + +To check the logs of a specific service, add the name of the service, e.g.: + +```bash +docker compose logs backend +``` + +## Mailcatcher + +Mailcatcher is a simple SMTP server that catches all emails sent by the backend during local development. Instead of sending real emails, they are captured and displayed in a web interface. + +This is useful for: + +* Testing email functionality during development +* Verifying email content and formatting +* Debugging email-related functionality without sending real emails + +The backend is automatically configured to use Mailcatcher when running with Docker Compose locally (SMTP on port 1025). All captured emails can be viewed at . + +## Local Development + +The Docker Compose files are configured so that each of the services is available in a different port in `localhost`. + +For the backend and frontend, they use the same port that would be used by their local development server, so, the backend is at `http://localhost:8000` and the frontend at `http://localhost:5173`. + +This way, you could turn off a Docker Compose service and start its local development service, and everything would keep working, because it all uses the same ports. + +For example, you can stop that `frontend` service in the Docker Compose, in another terminal, run: + +```bash +docker compose stop frontend +``` + +And then start the local frontend development server: + +```bash +bun run dev +``` + +Or you could stop the `backend` Docker Compose service: + +```bash +docker compose stop backend +``` + +And then you can run the local development server for the backend: + +```bash +cd backend +fastapi dev app/main.py +``` + +## Docker Compose in `localhost.tiangolo.com` + +When you start the Docker Compose stack, it uses `localhost` by default, with different ports for each service (backend, frontend, adminer, etc). + +When you deploy it to production (or staging), it will deploy each service in a different subdomain, like `api.example.com` for the backend and `dashboard.example.com` for the frontend. + +In the guide about [deployment](deployment.md) you can read about Traefik, the configured proxy. That's the component in charge of transmitting traffic to each service based on the subdomain. + +If you want to test that it's all working locally, you can edit the local `.env` file, and change: + +```dotenv +DOMAIN=localhost.tiangolo.com +``` + +That will be used by the Docker Compose files to configure the base domain for the services. + +Traefik will use this to transmit traffic at `api.localhost.tiangolo.com` to the backend, and traffic at `dashboard.localhost.tiangolo.com` to the frontend. + +The domain `localhost.tiangolo.com` is a special domain that is configured (with all its subdomains) to point to `127.0.0.1`. This way you can use that for your local development. + +After you update it, run again: + +```bash +docker compose watch +``` + +When deploying, for example in production, the main Traefik is configured outside of the Docker Compose files. For local development, there's an included Traefik in `compose.override.yml`, just to let you test that the domains work as expected, for example with `api.localhost.tiangolo.com` and `dashboard.localhost.tiangolo.com`. + +## Docker Compose files and env vars + +There is a main `compose.yml` file with all the configurations that apply to the whole stack, it is used automatically by `docker compose`. + +And there's also a `compose.override.yml` with overrides for development, for example to mount the source code as a volume. It is used automatically by `docker compose` to apply overrides on top of `compose.yml`. + +These Docker Compose files use the `.env` file containing configurations to be injected as environment variables in the containers. + +They also use some additional configurations taken from environment variables set in the scripts before calling the `docker compose` command. + +After changing variables, make sure you restart the stack: + +```bash +docker compose watch +``` + +## The .env file + +The `.env` file is the one that contains all your configurations, generated keys and passwords, etc. + +Depending on your workflow, you could want to exclude it from Git, for example if your project is public. In that case, you would have to make sure to set up a way for your CI tools to obtain it while building or deploying your project. + +One way to do it could be to add each environment variable to your CI/CD system, and updating the `compose.yml` file to read that specific env var instead of reading the `.env` file. + +## Pre-commits and code linting + +we are using a tool called [prek](https://prek.j178.dev/) (modern alternative to [Pre-commit](https://pre-commit.com/)) for code linting and formatting. + +When you install it, it runs right before making a commit in git. This way it ensures that the code is consistent and formatted even before it is committed. + +You can find a file `.pre-commit-config.yaml` with configurations at the root of the project. + +#### Install prek to run automatically + +`prek` is already part of the dependencies of the project. + +After having the `prek` tool installed and available, you need to "install" it in the local repository, so that it runs automatically before each commit. + +Using `uv`, you could do it with (make sure you are inside `backend` folder): + +```bash +❯ uv run prek install -f +prek installed at `../.git/hooks/pre-commit` +``` + +The `-f` flag forces the installation, in case there was already a `pre-commit` hook previously installed. + +Now whenever you try to commit, e.g. with: + +```bash +git commit +``` + +...prek will run and check and format the code you are about to commit, and will ask you to add that code (stage it) with git again before committing. + +Then you can `git add` the modified/fixed files again and now you can commit. + +#### Running prek hooks manually + +you can also run `prek` manually on all the files, you can do it using `uv` with: + +```bash +❯ uv run prek run --all-files +check for added large files..............................................Passed +check toml...............................................................Passed +check yaml...............................................................Passed +fix end of files.........................................................Passed +trim trailing whitespace.................................................Passed +ruff.....................................................................Passed +ruff-format..............................................................Passed +biome check..............................................................Passed +``` + +## URLs + +The production or staging URLs would use these same paths, but with your own domain. + +### Development URLs + +Development URLs, for local development. + +Frontend: + +Backend: + +Automatic Interactive Docs (Swagger UI): + +Automatic Alternative Docs (ReDoc): + +Adminer: + +Traefik UI: + +MailCatcher: + +### Development URLs with `localhost.tiangolo.com` Configured + +Development URLs, for local development. + +Frontend: + +Backend: + +Automatic Interactive Docs (Swagger UI): + +Automatic Alternative Docs (ReDoc): + +Adminer: + +Traefik UI: + +MailCatcher: diff --git a/skills/outpost/examples/fastapi-saas/frontend/.dockerignore b/skills/outpost/examples/fastapi-saas/frontend/.dockerignore new file mode 100644 index 0000000..f06235c --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/frontend/.dockerignore @@ -0,0 +1,2 @@ +node_modules +dist diff --git a/skills/outpost/examples/fastapi-saas/frontend/.gitignore b/skills/outpost/examples/fastapi-saas/frontend/.gitignore new file mode 100644 index 0000000..093ec6d --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/frontend/.gitignore @@ -0,0 +1,30 @@ +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +pnpm-debug.log* +lerna-debug.log* + +node_modules +dist +dist-ssr +*.local +openapi.json + +# Editor directories and files +.vscode/* +!.vscode/extensions.json +.idea +.DS_Store +*.suo +*.ntvs* +*.njsproj +*.sln +*.sw? +/test-results/ +/playwright-report/ +/blob-report/ +/playwright/.cache/ +/playwright/.auth/ diff --git a/skills/outpost/examples/fastapi-saas/frontend/Dockerfile b/skills/outpost/examples/fastapi-saas/frontend/Dockerfile new file mode 100644 index 0000000..e9bae40 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/frontend/Dockerfile @@ -0,0 +1,26 @@ +# Stage 0, "build-stage", based on Bun, to build and compile the frontend +FROM oven/bun:1 AS build-stage + +WORKDIR /app + +COPY package.json bun.lock /app/ + +COPY frontend/package.json /app/frontend/ + +WORKDIR /app/frontend + +RUN bun install + +COPY ./frontend /app/frontend +ARG VITE_API_URL + +RUN bun run build + + +# Stage 1, based on Nginx, to have only the compiled app, ready for production with Nginx +FROM nginx:1 + +COPY --from=build-stage /app/frontend/dist/ /usr/share/nginx/html + +COPY ./frontend/nginx.conf /etc/nginx/conf.d/default.conf +COPY ./frontend/nginx-backend-not-found.conf /etc/nginx/extra-conf.d/backend-not-found.conf diff --git a/skills/outpost/examples/fastapi-saas/frontend/Dockerfile.playwright b/skills/outpost/examples/fastapi-saas/frontend/Dockerfile.playwright new file mode 100644 index 0000000..3438648 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/frontend/Dockerfile.playwright @@ -0,0 +1,21 @@ +FROM mcr.microsoft.com/playwright:v1.58.2-noble + +WORKDIR /app + +RUN apt-get update && apt-get install -y unzip \ + && rm -rf /var/lib/apt/lists/* + +RUN curl -fsSL https://bun.sh/install | bash +ENV PATH="/root/.bun/bin:$PATH" + +COPY package.json bun.lock /app/ + +COPY frontend/package.json /app/frontend/ + +WORKDIR /app/frontend + +RUN bun install + +COPY ./frontend /app/frontend + +ARG VITE_API_URL diff --git a/skills/outpost/examples/fastapi-saas/frontend/README.md b/skills/outpost/examples/fastapi-saas/frontend/README.md new file mode 100644 index 0000000..7b50d58 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/frontend/README.md @@ -0,0 +1,121 @@ +# FastAPI Project - Frontend + +The frontend is built with [Vite](https://vitejs.dev/), [React](https://reactjs.org/), [TypeScript](https://www.typescriptlang.org/), [TanStack Query](https://tanstack.com/query), [TanStack Router](https://tanstack.com/router) and [Tailwind CSS](https://tailwindcss.com/). + +## Requirements + +- [Bun](https://bun.sh/) (recommended) or [Node.js](https://nodejs.org/) + +## Quick Start + +```bash +bun install +bun run dev +``` + +* Then open your browser at http://localhost:5173/. + +Notice that this live server is not running inside Docker, it's for local development, and that is the recommended workflow. Once you are happy with your frontend, you can build the frontend Docker image and start it, to test it in a production-like environment. But building the image at every change will not be as productive as running the local development server with live reload. + +Check the file `package.json` to see other available options. + +### Removing the frontend + +If you are developing an API-only app and want to remove the frontend, you can do it easily: + +* Remove the `./frontend` directory. + +* In the `compose.yml` file, remove the whole service / section `frontend`. + +* In the `compose.override.yml` file, remove the whole service / section `frontend` and `playwright`. + +Done, you have a frontend-less (api-only) app. 🤓 + +--- + +If you want, you can also remove the `FRONTEND` environment variables from: + +* `.env` +* `./scripts/*.sh` + +But it would be only to clean them up, leaving them won't really have any effect either way. + +## Generate Client + +### Automatically + +* Activate the backend virtual environment. +* From the top level project directory, run the script: + +```bash +bash ./scripts/generate-client.sh +``` + +* Commit the changes. + +### Manually + +* Start the Docker Compose stack. + +* Download the OpenAPI JSON file from `http://localhost/api/v1/openapi.json` and copy it to a new file `openapi.json` at the root of the `frontend` directory. + +* To generate the frontend client, run: + +```bash +bun run generate-client +``` + +* Commit the changes. + +Notice that everytime the backend changes (changing the OpenAPI schema), you should follow these steps again to update the frontend client. + +## Using a Remote API + +If you want to use a remote API, you can set the environment variable `VITE_API_URL` to the URL of the remote API. For example, you can set it in the `frontend/.env` file: + +```env +VITE_API_URL=https://api.my-domain.example.com +``` + +Then, when you run the frontend, it will use that URL as the base URL for the API. + +## Code Structure + +The frontend code is structured as follows: + +* `frontend/src` - The main frontend code. +* `frontend/src/assets` - Static assets. +* `frontend/src/client` - The generated OpenAPI client. +* `frontend/src/components` - The different components of the frontend. +* `frontend/src/hooks` - Custom hooks. +* `frontend/src/routes` - The different routes of the frontend which include the pages. + +## End-to-End Testing with Playwright + +The frontend includes initial end-to-end tests using Playwright. To run the tests, you need to have the Docker Compose stack running. Start the stack with the following command: + +```bash +docker compose up -d --wait backend +``` + +Then, you can run the tests with the following command: + +```bash +bunx playwright test +``` + +You can also run your tests in UI mode to see the browser and interact with it running: + +```bash +bunx playwright test --ui +``` + +To stop and remove the Docker Compose stack and clean the data created in tests, use the following command: + +```bash +docker compose down -v +``` + +To update the tests, navigate to the tests directory and modify the existing test files or add new ones as needed. + +For more information on writing and running Playwright tests, refer to the official [Playwright documentation](https://playwright.dev/docs/intro). diff --git a/skills/outpost/examples/fastapi-saas/frontend/biome.json b/skills/outpost/examples/fastapi-saas/frontend/biome.json new file mode 100644 index 0000000..d24f85d --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/frontend/biome.json @@ -0,0 +1,46 @@ +{ + "$schema": "https://biomejs.dev/schemas/2.3.14/schema.json", + "assist": { "actions": { "source": { "organizeImports": "on" } } }, + "files": { + "includes": [ + "**", + "!**/dist/**/*", + "!**/node_modules/**/*", + "!**/src/routeTree.gen.ts", + "!**/src/client/**/*", + "!**/src/components/ui/**/*", + "!**/playwright-report", + "!**/playwright.config.ts" + ] + }, + "linter": { + "enabled": true, + "rules": { + "recommended": true, + "suspicious": { + "noExplicitAny": "off", + "noArrayIndexKey": "off" + }, + "style": { + "noNonNullAssertion": "off", + "noParameterAssign": "error", + "useSelfClosingElements": "error", + "noUselessElse": "error" + } + } + }, + "formatter": { + "indentStyle": "space" + }, + "javascript": { + "formatter": { + "quoteStyle": "double", + "semicolons": "asNeeded" + } + }, + "css": { + "parser": { + "tailwindDirectives": true + } + } +} diff --git a/skills/outpost/examples/fastapi-saas/frontend/components.json b/skills/outpost/examples/fastapi-saas/frontend/components.json new file mode 100644 index 0000000..2b0833f --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/frontend/components.json @@ -0,0 +1,22 @@ +{ + "$schema": "https://ui.shadcn.com/schema.json", + "style": "new-york", + "rsc": false, + "tsx": true, + "tailwind": { + "config": "", + "css": "src/index.css", + "baseColor": "neutral", + "cssVariables": true, + "prefix": "" + }, + "iconLibrary": "lucide", + "aliases": { + "components": "@/components", + "utils": "@/lib/utils", + "ui": "@/components/ui", + "lib": "@/lib", + "hooks": "@/hooks" + }, + "registries": {} +} diff --git a/skills/outpost/examples/fastapi-saas/frontend/index.html b/skills/outpost/examples/fastapi-saas/frontend/index.html new file mode 100644 index 0000000..57621a2 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/frontend/index.html @@ -0,0 +1,14 @@ + + + + + + + Full Stack FastAPI Project + + + +
+ + + diff --git a/skills/outpost/examples/fastapi-saas/frontend/nginx-backend-not-found.conf b/skills/outpost/examples/fastapi-saas/frontend/nginx-backend-not-found.conf new file mode 100644 index 0000000..f6fea66 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/frontend/nginx-backend-not-found.conf @@ -0,0 +1,9 @@ +location /api { + return 404; +} +location /docs { + return 404; +} +location /redoc { + return 404; +} diff --git a/skills/outpost/examples/fastapi-saas/frontend/nginx.conf b/skills/outpost/examples/fastapi-saas/frontend/nginx.conf new file mode 100644 index 0000000..ba4d9aa --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/frontend/nginx.conf @@ -0,0 +1,11 @@ +server { + listen 80; + + location / { + root /usr/share/nginx/html; + index index.html index.htm; + try_files $uri /index.html =404; + } + + include /etc/nginx/extra-conf.d/*.conf; +} diff --git a/skills/outpost/examples/fastapi-saas/frontend/openapi-ts.config.ts b/skills/outpost/examples/fastapi-saas/frontend/openapi-ts.config.ts new file mode 100644 index 0000000..b5a69e2 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/frontend/openapi-ts.config.ts @@ -0,0 +1,33 @@ +import { defineConfig } from "@hey-api/openapi-ts" + +export default defineConfig({ + input: "./openapi.json", + output: "./src/client", + + plugins: [ + "legacy/axios", + { + name: "@hey-api/sdk", + // NOTE: this doesn't allow tree-shaking + asClass: true, + operationId: true, + classNameBuilder: "{{name}}Service", + methodNameBuilder: (operation) => { + // @ts-expect-error + let name: string = operation.name + // @ts-expect-error + const service: string = operation.service + + if (service && name.toLowerCase().startsWith(service.toLowerCase())) { + name = name.slice(service.length) + } + + return name.charAt(0).toLowerCase() + name.slice(1) + }, + }, + { + name: "@hey-api/schemas", + type: "json", + }, + ], +}) diff --git a/skills/outpost/examples/fastapi-saas/frontend/package.json b/skills/outpost/examples/fastapi-saas/frontend/package.json new file mode 100644 index 0000000..f3b8d23 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/frontend/package.json @@ -0,0 +1,66 @@ +{ + "name": "frontend", + "private": true, + "version": "0.0.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "tsc -p tsconfig.build.json && vite build", + "lint": "biome check --write --unsafe --no-errors-on-unmatched --files-ignore-unknown=true ./", + "preview": "vite preview", + "generate-client": "openapi-ts", + "test": "bunx playwright test", + "test:ui": "bunx playwright test --ui" + }, + "dependencies": { + "@hookform/resolvers": "^5.2.2", + "@radix-ui/react-avatar": "^1.1.11", + "@radix-ui/react-checkbox": "^1.3.3", + "@radix-ui/react-dialog": "^1.1.15", + "@radix-ui/react-dropdown-menu": "^2.1.16", + "@radix-ui/react-label": "^2.1.8", + "@radix-ui/react-radio-group": "^1.3.8", + "@radix-ui/react-scroll-area": "^1.2.10", + "@radix-ui/react-select": "^2.2.6", + "@radix-ui/react-separator": "^1.1.8", + "@radix-ui/react-slot": "^1.2.4", + "@radix-ui/react-tabs": "^1.1.13", + "@radix-ui/react-tooltip": "^1.2.8", + "@tailwindcss/vite": "^4.1.18", + "@tanstack/react-query": "^5.90.21", + "@tanstack/react-query-devtools": "^5.91.1", + "@tanstack/react-router": "^1.163.3", + "@tanstack/react-router-devtools": "^1.163.3", + "@tanstack/react-table": "^8.21.3", + "axios": "1.13.5", + "class-variance-authority": "^0.7.1", + "clsx": "^2.1.1", + "form-data": "4.0.5", + "lucide-react": "^0.563.0", + "next-themes": "^0.4.6", + "react": "^19.1.1", + "react-dom": "^19.2.3", + "react-error-boundary": "^6.0.0", + "react-hook-form": "^7.68.0", + "react-icons": "^5.5.0", + "sonner": "^2.0.7", + "tailwind-merge": "^3.4.0", + "tailwindcss": "^4.2.1", + "zod": "^4.3.6" + }, + "devDependencies": { + "@biomejs/biome": "^2.3.14", + "@hey-api/openapi-ts": "0.73.0", + "@playwright/test": "1.58.2", + "@tanstack/router-devtools": "^1.166.7", + "@tanstack/router-plugin": "^1.140.0", + "@types/node": "^25.5.0", + "@types/react": "^19.2.7", + "@types/react-dom": "^19.2.3", + "@vitejs/plugin-react-swc": "^4.2.3", + "dotenv": "^17.3.1", + "tw-animate-css": "^1.4.0", + "typescript": "^5.9.3", + "vite": "^7.3.0" + } +} diff --git a/skills/outpost/examples/fastapi-saas/frontend/playwright.config.ts b/skills/outpost/examples/fastapi-saas/frontend/playwright.config.ts new file mode 100644 index 0000000..36f03d9 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/frontend/playwright.config.ts @@ -0,0 +1,91 @@ +import { defineConfig, devices } from '@playwright/test'; +import 'dotenv/config' + +/** + * Read environment variables from file. + * https://github.com/motdotla/dotenv + */ + +/** + * See https://playwright.dev/docs/test-configuration. + */ +export default defineConfig({ + testDir: './tests', + /* Run tests in files in parallel */ + fullyParallel: true, + /* Fail the build on CI if you accidentally left test.only in the source code. */ + forbidOnly: !!process.env.CI, + /* Retry on CI only */ + retries: process.env.CI ? 2 : 0, + /* Opt out of parallel tests on CI. */ + workers: process.env.CI ? 1 : undefined, + /* Reporter to use. See https://playwright.dev/docs/test-reporters */ + reporter: process.env.CI ? 'blob' : 'html', + /* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */ + use: { + /* Base URL to use in actions like `await page.goto('/')`. */ + baseURL: 'http://localhost:5173', + + /* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */ + trace: 'on-first-retry', + }, + + /* Configure projects for major browsers */ + projects: [ + { name: 'setup', testMatch: /.*\.setup\.ts/ }, + + { + name: 'chromium', + use: { + ...devices['Desktop Chrome'], + storageState: 'playwright/.auth/user.json', + }, + dependencies: ['setup'], + }, + + // { + // name: 'firefox', + // use: { + // ...devices['Desktop Firefox'], + // storageState: 'playwright/.auth/user.json', + // }, + // dependencies: ['setup'], + // }, + + // { + // name: 'webkit', + // use: { + // ...devices['Desktop Safari'], + // storageState: 'playwright/.auth/user.json', + // }, + // dependencies: ['setup'], + // }, + + /* Test against mobile viewports. */ + // { + // name: 'Mobile Chrome', + // use: { ...devices['Pixel 5'] }, + // }, + // { + // name: 'Mobile Safari', + // use: { ...devices['iPhone 12'] }, + // }, + + /* Test against branded browsers. */ + // { + // name: 'Microsoft Edge', + // use: { ...devices['Desktop Edge'], channel: 'msedge' }, + // }, + // { + // name: 'Google Chrome', + // use: { ...devices['Desktop Chrome'], channel: 'chrome' }, + // }, + ], + + /* Run your local dev server before starting the tests */ + webServer: { + command: 'bun run dev', + url: 'http://localhost:5173', + reuseExistingServer: !process.env.CI, + }, +}); diff --git a/skills/outpost/examples/fastapi-saas/frontend/public/assets/images/fastapi-icon-light.svg b/skills/outpost/examples/fastapi-saas/frontend/public/assets/images/fastapi-icon-light.svg new file mode 100644 index 0000000..d069c72 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/frontend/public/assets/images/fastapi-icon-light.svg @@ -0,0 +1,77 @@ + + + + + + + + image/svg+xml + + + + + + + + + + + + + diff --git a/skills/outpost/examples/fastapi-saas/frontend/public/assets/images/fastapi-icon.svg b/skills/outpost/examples/fastapi-saas/frontend/public/assets/images/fastapi-icon.svg new file mode 100644 index 0000000..df93a70 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/frontend/public/assets/images/fastapi-icon.svg @@ -0,0 +1,77 @@ + + + + + + + + image/svg+xml + + + + + + + + + + + + + diff --git a/skills/outpost/examples/fastapi-saas/frontend/public/assets/images/fastapi-logo-light.svg b/skills/outpost/examples/fastapi-saas/frontend/public/assets/images/fastapi-logo-light.svg new file mode 100644 index 0000000..1a84b98 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/frontend/public/assets/images/fastapi-logo-light.svg @@ -0,0 +1,83 @@ + + + + + + + + image/svg+xml + + + + + + + + + + + + + + diff --git a/skills/outpost/examples/fastapi-saas/frontend/public/assets/images/fastapi-logo.svg b/skills/outpost/examples/fastapi-saas/frontend/public/assets/images/fastapi-logo.svg new file mode 100644 index 0000000..c90d252 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/frontend/public/assets/images/fastapi-logo.svg @@ -0,0 +1,91 @@ + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + diff --git a/skills/outpost/examples/fastapi-saas/frontend/public/assets/images/favicon.png b/skills/outpost/examples/fastapi-saas/frontend/public/assets/images/favicon.png new file mode 100644 index 0000000000000000000000000000000000000000..e5b7c3ada7d093d237711560e03f6a841a4a41b2 GIT binary patch literal 5043 zcmV;k6HM%hP);M1&8FWQhbW?9;ba!ELWdL_~cP?peYja~^aAhuUa%Y?FJQ@H16F^Bs zK~#90?VWpg71g)tbaW^d;G zhwQnm_1l}@tXVT_t?v_6-Ko=kYBm*64Pb&ke z02A1cun%QFLJ5}c!7z%zETWp7dS`ZtD__hdB#{jye|V?|$-y*4F9scik_vK~vz78C z=ysG3z}SS8Z_+F`d9 z*+twNsP>k09l~hPOF@#{*3<%3AnUo6FD%H=@N zZA}pp1_}@sQ+?8Mz4OjWw*|G8xH6E;%R3j5@xU!WSGV=pOex6I1Z1J6PyNJgF|8#o z3?z>|{C&i{6X7P1fZKW;#sXf&G9T5fd)BxurX@UWAbB)z6ai*}{LpPJF7YN7Gc{}a z8*U3}3QrnH9-Ea$!1yi7D7UqEgaSnF(~N2FxGkh1o-&X;k>8UF>p_J701>zKcnejK zWdxY6>C-=TTTLCFFpw--l!Uo|3dnTeB)9c=oHCSI1Ut{s^z>@C#kg)DSvY$z7K?x( zt_q1iwxc>;C(L-)O%bjcNOE(N>CrA1)yXHola)iL3GzFND{?g_r^*clt{6z>=l2I) zjNj_m#dgFTqZ#*Xk9EaHtSglH`C~!f#y5|h3`7I#W&Z42VqI~}S|FJ_H$>9WStt`@ zQsIfqA1SVw9IIPeObk>rts<}lNOQb09}wPxieJWJ8j0ful6m>(Bi2hGy&SE`ry)fI zteu>A7}hf1Jf5Wr%eqmsvRB$wplt?{`LjlX@iNfPmI8eoLd#LPS|?0@ z(~i)0ImyjUj;4_4TA&`GIrzg9@r!aX-9ryYQ$)ml zpxROO$D^s-$0LZ0(~N0G*KwSveF{yRJZvSCW{s&5tb+L&67xU zz%c$CNq?yAeIV<={fG=}^LajAX9zt)_qFw;Hr>KxVg4{IYkeZlVNMPN7~5}P%x7pu zL$zh{+$TG%qhY%iXQ+u4xJ0w2ZfWfqtu~P4<_1X#Z3MY6VtpQFZ2y7AE8z@*e+ant%dv+F}^$n#HzZ8r~q zkV^Q#U9CR6H7$@Vm~#eNwVm%mz9ketIjfJX`1cz;A0no-qFgfyS6MF=eQY^g)e!=r z3p9Q5mn|LGx~opB@<>qg0Nj;2)bqElHJ=yhuq981V_+VDlL=Qm(3%5VY=LBc{zYIF zChA)CfnB=E<{NGeibua*ML5g@TQ-`H{QVuvitQRc3-l7roUysNgIaF3Mej#F`s>=j z1Eo4<%?fktz7jW<4;u*g16MbHP&3H9hb~X#5GyI|J8)y)0iNqTt16Fe z-(saLT^x4FJhejP3VCeyWz8MZdQ+pbH3agEVx*ZpSFT?^v zgsnH;7VOuli|f7Tx4+)2w-&50Kl$d6ms*_$s7W9&u(9Z|jT@vUlx{+r2jH4s=NN9A zCu~_fuz907YWXu^Z<_}|0+{9O^=TLk{rFaS{wMU!9Q^2)?89?RL2*tHdhpV9KXM=%2;4&{Y}T*!emiyH_UdQ z62G}8n&s?{9p$5&(t|-GwjTQ1XS?-|!d2nDWk+IKul;B>mY%Iy+576Y9Q#X}q3cOd z^8idr9d5+ZJmukPrfe)Qf3|W-0+nFsc7EBuRXdJ#+45(?31}Wr z87cE}Pp-|^Pxvm@W=xV0P7Yq|svHNIJZQM>txvUO^1$Ye=9Md+3x9s(NFw)lnm~l4U>elj!bH;& z@$GZJPMzhdv-;R-pdAPI>6kSu%=b%+6Yv*n18Q9itf(=NGT2=;&MQnrr?~v6jxStgzOv_&1pAeuKy?s6 zQ0C6+PSA)t)S1`F8aTx0kQDuEt(S^EwlWG=o23;;ZBUg!i1d`lW_1k`WPsaR>?RZl zkp8_3qiTK1!`0mT&U*8Iw{1Srp0HYv5jZahM#AN>xTW6(MvwL#BJTWbt{unPnTSIX zcA{3VAkf=w9d;tXU4tSEln}Noe!ulSE9c$yX0_!vJS`)Af}m$5(h$Z~XZMu>ow~O9 z3t6hn`^Wp%mXfdZ+TQ2Ibi&ZrmvK0LCfX|qlH#@wJGpz%@Q4B>7$Qtc9coNU z9cs6vW_j(i-Fo}FSHm%_)Gky~fIIfI&vrcHYabd8n#_N$X!XpZ)ls@!L^u77fMy5}tqv69+m!-?^=<{bG;a zwsxiYMOk9c7YYJZfcGxnR&s6c^Nc>Hbn?tSxY7*s+s&@TG;{%}41&b9f$kn`|BS;( z`RL$29kb?T^Y5iDhNX)wl|i7g#lt+x@RZXftw&GSTb~nmvYA!}K@Y|2aK_XjX|A_E z#pOpey>OMe@J>!-u`;8 zjxAVW{>$@W>0&}j5actrRkW4#?+rFOCdYOJ#-D7~2r7Gmi0meg-d7|U2ALNOiD~Pz z=kOsNw|1rZrW5Iv;u_r@1hXif0)b z#HiYV>3rNAyNGnYb6Y7bKT75stIg%HNv{;2RFv;DG(D#jp~b{vUf@S(_Ljk2Qyg!7 z3clE*!vC!GFN^2FK=Hxoy88lKLNy zy*&gfUj#f6DPm~%)8x|ABMX#JT2Zc}SHBRxwcr)sJhr0MR93!Jf6Fljs(myoh^eL~ zh;+5Z>z^0tuq981UykR*ZeB&?Z+dsmF*8_?f4L$oMsamm7Sz0&peDZ5cw;jF0R35YOZ zV9WEJm+jtZ4SoK}uy39ip}e4(Gyc`suI5H4=K$9>v)^`Z=-c1u)$!COAKkyHs$}wp zHRjVh|KX2g#S+y&G_|YAt6e8d-w4F?&Ge*ZW*ol#^Y&8+5U!RWN#owFBThnak%r~ejV}RpZ#$x z_gJNw+3TA-pykJ9k^69X<>7g!c9Nf-)%UxBT~+??qpeojvc=&oB`0`dH}|j*&1vbN z77e5s)80XyeJ^xZy~J=O6-RaSYcGZ~3s;+E)hAM{9j~EJX~vBATRN(B^F-Sj|4pS{ z3!L2Iv2CPFyY}3C-uDcs3HzU3xGKE2>_|(e`8bJimmeM zUT~pdh%jYifqBi!CBAvQfTa)U>k{ZZ6L`1H=lOUX-9mB2gKa&lO}DUbPg?Zw zIhfYFIPg^F;|gV1R+?sI?`-Rd5ltJ_^r@c!lOj3S$Abu&k(dXf2u-G$)1L+wM0&oD zXPB!Q)BhUj$Q$R$0pkoSHl-rGPXgwn5L{*SatSLe& zMrcM(aWsWQZ6E-dpWh$!4WM(>h50y-upiU9EYf~YeQb%jqnXoofOP}t2^#Z1t~iRt z^>&yCY>e+)J8xt(XxwK1IRU5weqB4;)D~=w`lXpOUI*hp@yPOMpJNDPaI!>y3v9k%^O8Pmf^pxcAKN9-l!91yw>ue zZO1VK0m!`BBQRKk(#5e#e41k)%4j?LJPmQwKu|YsX1)XxcS-Hy8r9v1@$;G|Wan@^ z?}VmL{RFAJ9MrL^z~?wNVCo2`%>yw?)1w(V#S~Zm7ZLg_0H^)SXAct zE$p}o7v$fJ>Z3r1m{y$l96>cpC(L*@mX*fbKmf8JuQ$k3C>O`P@zra8@+QH0U?$B5?RzjTa-Frs+`yNq8HAu!ZcA#sOp#V|5- z{IvJnRN;EAOU<0JmEwv^QSJf!MPV%=97c6I#g!MiZ65GI3sfKZ{X?e{3fv1i&W-43 z-bS@%iFqJfCrtgyZ8ddx%0P9<{JfzE_oH%!+giMVu12`8HEY#ljVBFMhb)+N32Mv) zM!K!VCDvkDGc_yQv(tt>ZJ;`2LEaE7CL!`GY+4oTVJzTPklC6!ZIjz#S|TnCRENyZ z>x;;Elv{8yj+lBU_>wwWHmw74QS>tFWNFm5lD$18P%smlr#Jz#)Bab}N zfez*1?g~1;{o;w?beOX80}5%HHQ}o$is)25JnMliP*l = { + readonly body?: any; + readonly cookies?: Record; + readonly errors?: Record; + readonly formData?: Record | any[] | Blob | File; + readonly headers?: Record; + readonly mediaType?: string; + readonly method: + | 'DELETE' + | 'GET' + | 'HEAD' + | 'OPTIONS' + | 'PATCH' + | 'POST' + | 'PUT'; + readonly path?: Record; + readonly query?: Record; + readonly responseHeader?: string; + readonly responseTransformer?: (data: unknown) => Promise; + readonly url: string; +}; \ No newline at end of file diff --git a/skills/outpost/examples/fastapi-saas/frontend/src/client/core/ApiResult.ts b/skills/outpost/examples/fastapi-saas/frontend/src/client/core/ApiResult.ts new file mode 100644 index 0000000..4c58e39 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/frontend/src/client/core/ApiResult.ts @@ -0,0 +1,7 @@ +export type ApiResult = { + readonly body: TData; + readonly ok: boolean; + readonly status: number; + readonly statusText: string; + readonly url: string; +}; \ No newline at end of file diff --git a/skills/outpost/examples/fastapi-saas/frontend/src/client/core/CancelablePromise.ts b/skills/outpost/examples/fastapi-saas/frontend/src/client/core/CancelablePromise.ts new file mode 100644 index 0000000..ccc082e --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/frontend/src/client/core/CancelablePromise.ts @@ -0,0 +1,126 @@ +export class CancelError extends Error { + constructor(message: string) { + super(message); + this.name = 'CancelError'; + } + + public get isCancelled(): boolean { + return true; + } +} + +export interface OnCancel { + readonly isResolved: boolean; + readonly isRejected: boolean; + readonly isCancelled: boolean; + + (cancelHandler: () => void): void; +} + +export class CancelablePromise implements Promise { + private _isResolved: boolean; + private _isRejected: boolean; + private _isCancelled: boolean; + readonly cancelHandlers: (() => void)[]; + readonly promise: Promise; + private _resolve?: (value: T | PromiseLike) => void; + private _reject?: (reason?: unknown) => void; + + constructor( + executor: ( + resolve: (value: T | PromiseLike) => void, + reject: (reason?: unknown) => void, + onCancel: OnCancel + ) => void + ) { + this._isResolved = false; + this._isRejected = false; + this._isCancelled = false; + this.cancelHandlers = []; + this.promise = new Promise((resolve, reject) => { + this._resolve = resolve; + this._reject = reject; + + const onResolve = (value: T | PromiseLike): void => { + if (this._isResolved || this._isRejected || this._isCancelled) { + return; + } + this._isResolved = true; + if (this._resolve) this._resolve(value); + }; + + const onReject = (reason?: unknown): void => { + if (this._isResolved || this._isRejected || this._isCancelled) { + return; + } + this._isRejected = true; + if (this._reject) this._reject(reason); + }; + + const onCancel = (cancelHandler: () => void): void => { + if (this._isResolved || this._isRejected || this._isCancelled) { + return; + } + this.cancelHandlers.push(cancelHandler); + }; + + Object.defineProperty(onCancel, 'isResolved', { + get: (): boolean => this._isResolved, + }); + + Object.defineProperty(onCancel, 'isRejected', { + get: (): boolean => this._isRejected, + }); + + Object.defineProperty(onCancel, 'isCancelled', { + get: (): boolean => this._isCancelled, + }); + + return executor(onResolve, onReject, onCancel as OnCancel); + }); + } + + get [Symbol.toStringTag]() { + return "Cancellable Promise"; + } + + public then( + onFulfilled?: ((value: T) => TResult1 | PromiseLike) | null, + onRejected?: ((reason: unknown) => TResult2 | PromiseLike) | null + ): Promise { + return this.promise.then(onFulfilled, onRejected); + } + + public catch( + onRejected?: ((reason: unknown) => TResult | PromiseLike) | null + ): Promise { + return this.promise.catch(onRejected); + } + + public finally(onFinally?: (() => void) | null): Promise { + return this.promise.finally(onFinally); + } + + public cancel(): void { + if (this._isResolved || this._isRejected || this._isCancelled) { + return; + } + this._isCancelled = true; + if (this.cancelHandlers.length) { + try { + for (const cancelHandler of this.cancelHandlers) { + cancelHandler(); + } + } catch (error) { + console.warn('Cancellation threw an error', error); + return; + } + } + this.cancelHandlers.length = 0; + if (this._reject) this._reject(new CancelError('Request aborted')); + } + + public get isCancelled(): boolean { + return this._isCancelled; + } +} \ No newline at end of file diff --git a/skills/outpost/examples/fastapi-saas/frontend/src/client/core/OpenAPI.ts b/skills/outpost/examples/fastapi-saas/frontend/src/client/core/OpenAPI.ts new file mode 100644 index 0000000..74f92b4 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/frontend/src/client/core/OpenAPI.ts @@ -0,0 +1,57 @@ +import type { AxiosRequestConfig, AxiosResponse } from 'axios'; +import type { ApiRequestOptions } from './ApiRequestOptions'; + +type Headers = Record; +type Middleware = (value: T) => T | Promise; +type Resolver = (options: ApiRequestOptions) => Promise; + +export class Interceptors { + _fns: Middleware[]; + + constructor() { + this._fns = []; + } + + eject(fn: Middleware): void { + const index = this._fns.indexOf(fn); + if (index !== -1) { + this._fns = [...this._fns.slice(0, index), ...this._fns.slice(index + 1)]; + } + } + + use(fn: Middleware): void { + this._fns = [...this._fns, fn]; + } +} + +export type OpenAPIConfig = { + BASE: string; + CREDENTIALS: 'include' | 'omit' | 'same-origin'; + ENCODE_PATH?: ((path: string) => string) | undefined; + HEADERS?: Headers | Resolver | undefined; + PASSWORD?: string | Resolver | undefined; + TOKEN?: string | Resolver | undefined; + USERNAME?: string | Resolver | undefined; + VERSION: string; + WITH_CREDENTIALS: boolean; + interceptors: { + request: Interceptors; + response: Interceptors; + }; +}; + +export const OpenAPI: OpenAPIConfig = { + BASE: '', + CREDENTIALS: 'include', + ENCODE_PATH: undefined, + HEADERS: undefined, + PASSWORD: undefined, + TOKEN: undefined, + USERNAME: undefined, + VERSION: '0.1.0', + WITH_CREDENTIALS: false, + interceptors: { + request: new Interceptors(), + response: new Interceptors(), + }, +}; \ No newline at end of file diff --git a/skills/outpost/examples/fastapi-saas/frontend/src/client/core/request.ts b/skills/outpost/examples/fastapi-saas/frontend/src/client/core/request.ts new file mode 100644 index 0000000..ecc2e39 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/frontend/src/client/core/request.ts @@ -0,0 +1,347 @@ +import axios from 'axios'; +import type { AxiosError, AxiosRequestConfig, AxiosResponse, AxiosInstance } from 'axios'; + +import { ApiError } from './ApiError'; +import type { ApiRequestOptions } from './ApiRequestOptions'; +import type { ApiResult } from './ApiResult'; +import { CancelablePromise } from './CancelablePromise'; +import type { OnCancel } from './CancelablePromise'; +import type { OpenAPIConfig } from './OpenAPI'; + +export const isString = (value: unknown): value is string => { + return typeof value === 'string'; +}; + +export const isStringWithValue = (value: unknown): value is string => { + return isString(value) && value !== ''; +}; + +export const isBlob = (value: any): value is Blob => { + return value instanceof Blob; +}; + +export const isFormData = (value: unknown): value is FormData => { + return value instanceof FormData; +}; + +export const isSuccess = (status: number): boolean => { + return status >= 200 && status < 300; +}; + +export const base64 = (str: string): string => { + try { + return btoa(str); + } catch (err) { + // @ts-ignore + return Buffer.from(str).toString('base64'); + } +}; + +export const getQueryString = (params: Record): string => { + const qs: string[] = []; + + const append = (key: string, value: unknown) => { + qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`); + }; + + const encodePair = (key: string, value: unknown) => { + if (value === undefined || value === null) { + return; + } + + if (value instanceof Date) { + append(key, value.toISOString()); + } else if (Array.isArray(value)) { + value.forEach(v => encodePair(key, v)); + } else if (typeof value === 'object') { + Object.entries(value).forEach(([k, v]) => encodePair(`${key}[${k}]`, v)); + } else { + append(key, value); + } + }; + + Object.entries(params).forEach(([key, value]) => encodePair(key, value)); + + return qs.length ? `?${qs.join('&')}` : ''; +}; + +const getUrl = (config: OpenAPIConfig, options: ApiRequestOptions): string => { + const encoder = config.ENCODE_PATH || encodeURI; + + const path = options.url + .replace('{api-version}', config.VERSION) + .replace(/{(.*?)}/g, (substring: string, group: string) => { + if (options.path?.hasOwnProperty(group)) { + return encoder(String(options.path[group])); + } + return substring; + }); + + const url = config.BASE + path; + return options.query ? url + getQueryString(options.query) : url; +}; + +export const getFormData = (options: ApiRequestOptions): FormData | undefined => { + if (options.formData) { + const formData = new FormData(); + + const process = (key: string, value: unknown) => { + if (isString(value) || isBlob(value)) { + formData.append(key, value); + } else { + formData.append(key, JSON.stringify(value)); + } + }; + + Object.entries(options.formData) + .filter(([, value]) => value !== undefined && value !== null) + .forEach(([key, value]) => { + if (Array.isArray(value)) { + value.forEach(v => process(key, v)); + } else { + process(key, value); + } + }); + + return formData; + } + return undefined; +}; + +type Resolver = (options: ApiRequestOptions) => Promise; + +export const resolve = async (options: ApiRequestOptions, resolver?: T | Resolver): Promise => { + if (typeof resolver === 'function') { + return (resolver as Resolver)(options); + } + return resolver; +}; + +export const getHeaders = async (config: OpenAPIConfig, options: ApiRequestOptions): Promise> => { + const [token, username, password, additionalHeaders] = await Promise.all([ + // @ts-ignore + resolve(options, config.TOKEN), + // @ts-ignore + resolve(options, config.USERNAME), + // @ts-ignore + resolve(options, config.PASSWORD), + // @ts-ignore + resolve(options, config.HEADERS), + ]); + + const headers = Object.entries({ + Accept: 'application/json', + ...additionalHeaders, + ...options.headers, + }) + .filter(([, value]) => value !== undefined && value !== null) + .reduce((headers, [key, value]) => ({ + ...headers, + [key]: String(value), + }), {} as Record); + + if (isStringWithValue(token)) { + headers['Authorization'] = `Bearer ${token}`; + } + + if (isStringWithValue(username) && isStringWithValue(password)) { + const credentials = base64(`${username}:${password}`); + headers['Authorization'] = `Basic ${credentials}`; + } + + if (options.body !== undefined) { + if (options.mediaType) { + headers['Content-Type'] = options.mediaType; + } else if (isBlob(options.body)) { + headers['Content-Type'] = options.body.type || 'application/octet-stream'; + } else if (isString(options.body)) { + headers['Content-Type'] = 'text/plain'; + } else if (!isFormData(options.body)) { + headers['Content-Type'] = 'application/json'; + } + } else if (options.formData !== undefined) { + if (options.mediaType) { + headers['Content-Type'] = options.mediaType; + } + } + + return headers; +}; + +export const getRequestBody = (options: ApiRequestOptions): unknown => { + if (options.body) { + return options.body; + } + return undefined; +}; + +export const sendRequest = async ( + config: OpenAPIConfig, + options: ApiRequestOptions, + url: string, + body: unknown, + formData: FormData | undefined, + headers: Record, + onCancel: OnCancel, + axiosClient: AxiosInstance +): Promise> => { + const controller = new AbortController(); + + let requestConfig: AxiosRequestConfig = { + data: body ?? formData, + headers, + method: options.method, + signal: controller.signal, + url, + withCredentials: config.WITH_CREDENTIALS, + }; + + onCancel(() => controller.abort()); + + for (const fn of config.interceptors.request._fns) { + requestConfig = await fn(requestConfig); + } + + try { + return await axiosClient.request(requestConfig); + } catch (error) { + const axiosError = error as AxiosError; + if (axiosError.response) { + return axiosError.response; + } + throw error; + } +}; + +export const getResponseHeader = (response: AxiosResponse, responseHeader?: string): string | undefined => { + if (responseHeader) { + const content = response.headers[responseHeader]; + if (isString(content)) { + return content; + } + } + return undefined; +}; + +export const getResponseBody = (response: AxiosResponse): unknown => { + if (response.status !== 204) { + return response.data; + } + return undefined; +}; + +export const catchErrorCodes = (options: ApiRequestOptions, result: ApiResult): void => { + const errors: Record = { + 400: 'Bad Request', + 401: 'Unauthorized', + 402: 'Payment Required', + 403: 'Forbidden', + 404: 'Not Found', + 405: 'Method Not Allowed', + 406: 'Not Acceptable', + 407: 'Proxy Authentication Required', + 408: 'Request Timeout', + 409: 'Conflict', + 410: 'Gone', + 411: 'Length Required', + 412: 'Precondition Failed', + 413: 'Payload Too Large', + 414: 'URI Too Long', + 415: 'Unsupported Media Type', + 416: 'Range Not Satisfiable', + 417: 'Expectation Failed', + 418: 'Im a teapot', + 421: 'Misdirected Request', + 422: 'Unprocessable Content', + 423: 'Locked', + 424: 'Failed Dependency', + 425: 'Too Early', + 426: 'Upgrade Required', + 428: 'Precondition Required', + 429: 'Too Many Requests', + 431: 'Request Header Fields Too Large', + 451: 'Unavailable For Legal Reasons', + 500: 'Internal Server Error', + 501: 'Not Implemented', + 502: 'Bad Gateway', + 503: 'Service Unavailable', + 504: 'Gateway Timeout', + 505: 'HTTP Version Not Supported', + 506: 'Variant Also Negotiates', + 507: 'Insufficient Storage', + 508: 'Loop Detected', + 510: 'Not Extended', + 511: 'Network Authentication Required', + ...options.errors, + } + + const error = errors[result.status]; + if (error) { + throw new ApiError(options, result, error); + } + + if (!result.ok) { + const errorStatus = result.status ?? 'unknown'; + const errorStatusText = result.statusText ?? 'unknown'; + const errorBody = (() => { + try { + return JSON.stringify(result.body, null, 2); + } catch (e) { + return undefined; + } + })(); + + throw new ApiError(options, result, + `Generic Error: status: ${errorStatus}; status text: ${errorStatusText}; body: ${errorBody}` + ); + } +}; + +/** + * Request method + * @param config The OpenAPI configuration object + * @param options The request options from the service + * @param axiosClient The axios client instance to use + * @returns CancelablePromise + * @throws ApiError + */ +export const request = (config: OpenAPIConfig, options: ApiRequestOptions, axiosClient: AxiosInstance = axios): CancelablePromise => { + return new CancelablePromise(async (resolve, reject, onCancel) => { + try { + const url = getUrl(config, options); + const formData = getFormData(options); + const body = getRequestBody(options); + const headers = await getHeaders(config, options); + + if (!onCancel.isCancelled) { + let response = await sendRequest(config, options, url, body, formData, headers, onCancel, axiosClient); + + for (const fn of config.interceptors.response._fns) { + response = await fn(response); + } + + const responseBody = getResponseBody(response); + const responseHeader = getResponseHeader(response, options.responseHeader); + + let transformedBody = responseBody; + if (options.responseTransformer && isSuccess(response.status)) { + transformedBody = await options.responseTransformer(responseBody) + } + + const result: ApiResult = { + url, + ok: isSuccess(response.status), + status: response.status, + statusText: response.statusText, + body: responseHeader ?? transformedBody, + }; + + catchErrorCodes(options, result); + + resolve(result.body); + } + } catch (error) { + reject(error); + } + }); +}; \ No newline at end of file diff --git a/skills/outpost/examples/fastapi-saas/frontend/src/client/index.ts b/skills/outpost/examples/fastapi-saas/frontend/src/client/index.ts new file mode 100644 index 0000000..50a1dd7 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/frontend/src/client/index.ts @@ -0,0 +1,6 @@ +// This file is auto-generated by @hey-api/openapi-ts +export { ApiError } from './core/ApiError'; +export { CancelablePromise, CancelError } from './core/CancelablePromise'; +export { OpenAPI, type OpenAPIConfig } from './core/OpenAPI'; +export * from './sdk.gen'; +export * from './types.gen'; \ No newline at end of file diff --git a/skills/outpost/examples/fastapi-saas/frontend/src/client/schemas.gen.ts b/skills/outpost/examples/fastapi-saas/frontend/src/client/schemas.gen.ts new file mode 100644 index 0000000..fb66c1f --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/frontend/src/client/schemas.gen.ts @@ -0,0 +1,559 @@ +// This file is auto-generated by @hey-api/openapi-ts + +export const Body_login_login_access_tokenSchema = { + properties: { + grant_type: { + anyOf: [ + { + type: 'string', + pattern: '^password$' + }, + { + type: 'null' + } + ], + title: 'Grant Type' + }, + username: { + type: 'string', + title: 'Username' + }, + password: { + type: 'string', + format: 'password', + title: 'Password' + }, + scope: { + type: 'string', + title: 'Scope', + default: '' + }, + client_id: { + anyOf: [ + { + type: 'string' + }, + { + type: 'null' + } + ], + title: 'Client Id' + }, + client_secret: { + anyOf: [ + { + type: 'string' + }, + { + type: 'null' + } + ], + format: 'password', + title: 'Client Secret' + } + }, + type: 'object', + required: ['username', 'password'], + title: 'Body_login-login_access_token' +} as const; + +export const HTTPValidationErrorSchema = { + properties: { + detail: { + items: { + '$ref': '#/components/schemas/ValidationError' + }, + type: 'array', + title: 'Detail' + } + }, + type: 'object', + title: 'HTTPValidationError' +} as const; + +export const ItemCreateSchema = { + properties: { + title: { + type: 'string', + maxLength: 255, + minLength: 1, + title: 'Title' + }, + description: { + anyOf: [ + { + type: 'string', + maxLength: 255 + }, + { + type: 'null' + } + ], + title: 'Description' + } + }, + type: 'object', + required: ['title'], + title: 'ItemCreate' +} as const; + +export const ItemPublicSchema = { + properties: { + title: { + type: 'string', + maxLength: 255, + minLength: 1, + title: 'Title' + }, + description: { + anyOf: [ + { + type: 'string', + maxLength: 255 + }, + { + type: 'null' + } + ], + title: 'Description' + }, + id: { + type: 'string', + format: 'uuid', + title: 'Id' + }, + owner_id: { + type: 'string', + format: 'uuid', + title: 'Owner Id' + }, + created_at: { + anyOf: [ + { + type: 'string', + format: 'date-time' + }, + { + type: 'null' + } + ], + title: 'Created At' + } + }, + type: 'object', + required: ['title', 'id', 'owner_id'], + title: 'ItemPublic' +} as const; + +export const ItemUpdateSchema = { + properties: { + title: { + anyOf: [ + { + type: 'string', + maxLength: 255, + minLength: 1 + }, + { + type: 'null' + } + ], + title: 'Title' + }, + description: { + anyOf: [ + { + type: 'string', + maxLength: 255 + }, + { + type: 'null' + } + ], + title: 'Description' + } + }, + type: 'object', + title: 'ItemUpdate' +} as const; + +export const ItemsPublicSchema = { + properties: { + data: { + items: { + '$ref': '#/components/schemas/ItemPublic' + }, + type: 'array', + title: 'Data' + }, + count: { + type: 'integer', + title: 'Count' + } + }, + type: 'object', + required: ['data', 'count'], + title: 'ItemsPublic' +} as const; + +export const MessageSchema = { + properties: { + message: { + type: 'string', + title: 'Message' + } + }, + type: 'object', + required: ['message'], + title: 'Message' +} as const; + +export const NewPasswordSchema = { + properties: { + token: { + type: 'string', + title: 'Token' + }, + new_password: { + type: 'string', + maxLength: 128, + minLength: 8, + title: 'New Password' + } + }, + type: 'object', + required: ['token', 'new_password'], + title: 'NewPassword' +} as const; + +export const PrivateUserCreateSchema = { + properties: { + email: { + type: 'string', + title: 'Email' + }, + password: { + type: 'string', + title: 'Password' + }, + full_name: { + type: 'string', + title: 'Full Name' + }, + is_verified: { + type: 'boolean', + title: 'Is Verified', + default: false + } + }, + type: 'object', + required: ['email', 'password', 'full_name'], + title: 'PrivateUserCreate' +} as const; + +export const TokenSchema = { + properties: { + access_token: { + type: 'string', + title: 'Access Token' + }, + token_type: { + type: 'string', + title: 'Token Type', + default: 'bearer' + } + }, + type: 'object', + required: ['access_token'], + title: 'Token' +} as const; + +export const UpdatePasswordSchema = { + properties: { + current_password: { + type: 'string', + maxLength: 128, + minLength: 8, + title: 'Current Password' + }, + new_password: { + type: 'string', + maxLength: 128, + minLength: 8, + title: 'New Password' + } + }, + type: 'object', + required: ['current_password', 'new_password'], + title: 'UpdatePassword' +} as const; + +export const UserCreateSchema = { + properties: { + email: { + type: 'string', + maxLength: 255, + format: 'email', + title: 'Email' + }, + is_active: { + type: 'boolean', + title: 'Is Active', + default: true + }, + is_superuser: { + type: 'boolean', + title: 'Is Superuser', + default: false + }, + full_name: { + anyOf: [ + { + type: 'string', + maxLength: 255 + }, + { + type: 'null' + } + ], + title: 'Full Name' + }, + password: { + type: 'string', + maxLength: 128, + minLength: 8, + title: 'Password' + } + }, + type: 'object', + required: ['email', 'password'], + title: 'UserCreate' +} as const; + +export const UserPublicSchema = { + properties: { + email: { + type: 'string', + maxLength: 255, + format: 'email', + title: 'Email' + }, + is_active: { + type: 'boolean', + title: 'Is Active', + default: true + }, + is_superuser: { + type: 'boolean', + title: 'Is Superuser', + default: false + }, + full_name: { + anyOf: [ + { + type: 'string', + maxLength: 255 + }, + { + type: 'null' + } + ], + title: 'Full Name' + }, + id: { + type: 'string', + format: 'uuid', + title: 'Id' + }, + created_at: { + anyOf: [ + { + type: 'string', + format: 'date-time' + }, + { + type: 'null' + } + ], + title: 'Created At' + } + }, + type: 'object', + required: ['email', 'id'], + title: 'UserPublic' +} as const; + +export const UserRegisterSchema = { + properties: { + email: { + type: 'string', + maxLength: 255, + format: 'email', + title: 'Email' + }, + password: { + type: 'string', + maxLength: 128, + minLength: 8, + title: 'Password' + }, + full_name: { + anyOf: [ + { + type: 'string', + maxLength: 255 + }, + { + type: 'null' + } + ], + title: 'Full Name' + } + }, + type: 'object', + required: ['email', 'password'], + title: 'UserRegister' +} as const; + +export const UserUpdateSchema = { + properties: { + email: { + anyOf: [ + { + type: 'string', + maxLength: 255, + format: 'email' + }, + { + type: 'null' + } + ], + title: 'Email' + }, + is_active: { + type: 'boolean', + title: 'Is Active', + default: true + }, + is_superuser: { + type: 'boolean', + title: 'Is Superuser', + default: false + }, + full_name: { + anyOf: [ + { + type: 'string', + maxLength: 255 + }, + { + type: 'null' + } + ], + title: 'Full Name' + }, + password: { + anyOf: [ + { + type: 'string', + maxLength: 128, + minLength: 8 + }, + { + type: 'null' + } + ], + title: 'Password' + } + }, + type: 'object', + title: 'UserUpdate' +} as const; + +export const UserUpdateMeSchema = { + properties: { + full_name: { + anyOf: [ + { + type: 'string', + maxLength: 255 + }, + { + type: 'null' + } + ], + title: 'Full Name' + }, + email: { + anyOf: [ + { + type: 'string', + maxLength: 255, + format: 'email' + }, + { + type: 'null' + } + ], + title: 'Email' + } + }, + type: 'object', + title: 'UserUpdateMe' +} as const; + +export const UsersPublicSchema = { + properties: { + data: { + items: { + '$ref': '#/components/schemas/UserPublic' + }, + type: 'array', + title: 'Data' + }, + count: { + type: 'integer', + title: 'Count' + } + }, + type: 'object', + required: ['data', 'count'], + title: 'UsersPublic' +} as const; + +export const ValidationErrorSchema = { + properties: { + loc: { + items: { + anyOf: [ + { + type: 'string' + }, + { + type: 'integer' + } + ] + }, + type: 'array', + title: 'Location' + }, + msg: { + type: 'string', + title: 'Message' + }, + type: { + type: 'string', + title: 'Error Type' + }, + input: { + title: 'Input' + }, + ctx: { + type: 'object', + title: 'Context' + } + }, + type: 'object', + required: ['loc', 'msg', 'type'], + title: 'ValidationError' +} as const; \ No newline at end of file diff --git a/skills/outpost/examples/fastapi-saas/frontend/src/client/sdk.gen.ts b/skills/outpost/examples/fastapi-saas/frontend/src/client/sdk.gen.ts new file mode 100644 index 0000000..ba79e3f --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/frontend/src/client/sdk.gen.ts @@ -0,0 +1,468 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { CancelablePromise } from './core/CancelablePromise'; +import { OpenAPI } from './core/OpenAPI'; +import { request as __request } from './core/request'; +import type { ItemsReadItemsData, ItemsReadItemsResponse, ItemsCreateItemData, ItemsCreateItemResponse, ItemsReadItemData, ItemsReadItemResponse, ItemsUpdateItemData, ItemsUpdateItemResponse, ItemsDeleteItemData, ItemsDeleteItemResponse, LoginLoginAccessTokenData, LoginLoginAccessTokenResponse, LoginTestTokenResponse, LoginRecoverPasswordData, LoginRecoverPasswordResponse, LoginResetPasswordData, LoginResetPasswordResponse, LoginRecoverPasswordHtmlContentData, LoginRecoverPasswordHtmlContentResponse, PrivateCreateUserData, PrivateCreateUserResponse, UsersReadUsersData, UsersReadUsersResponse, UsersCreateUserData, UsersCreateUserResponse, UsersReadUserMeResponse, UsersDeleteUserMeResponse, UsersUpdateUserMeData, UsersUpdateUserMeResponse, UsersUpdatePasswordMeData, UsersUpdatePasswordMeResponse, UsersRegisterUserData, UsersRegisterUserResponse, UsersReadUserByIdData, UsersReadUserByIdResponse, UsersUpdateUserData, UsersUpdateUserResponse, UsersDeleteUserData, UsersDeleteUserResponse, UtilsTestEmailData, UtilsTestEmailResponse, UtilsHealthCheckResponse } from './types.gen'; + +export class ItemsService { + /** + * Read Items + * Retrieve items. + * @param data The data for the request. + * @param data.skip + * @param data.limit + * @returns ItemsPublic Successful Response + * @throws ApiError + */ + public static readItems(data: ItemsReadItemsData = {}): CancelablePromise { + return __request(OpenAPI, { + method: 'GET', + url: '/api/v1/items/', + query: { + skip: data.skip, + limit: data.limit + }, + errors: { + 422: 'Validation Error' + } + }); + } + + /** + * Create Item + * Create new item. + * @param data The data for the request. + * @param data.requestBody + * @returns ItemPublic Successful Response + * @throws ApiError + */ + public static createItem(data: ItemsCreateItemData): CancelablePromise { + return __request(OpenAPI, { + method: 'POST', + url: '/api/v1/items/', + body: data.requestBody, + mediaType: 'application/json', + errors: { + 422: 'Validation Error' + } + }); + } + + /** + * Read Item + * Get item by ID. + * @param data The data for the request. + * @param data.id + * @returns ItemPublic Successful Response + * @throws ApiError + */ + public static readItem(data: ItemsReadItemData): CancelablePromise { + return __request(OpenAPI, { + method: 'GET', + url: '/api/v1/items/{id}', + path: { + id: data.id + }, + errors: { + 422: 'Validation Error' + } + }); + } + + /** + * Update Item + * Update an item. + * @param data The data for the request. + * @param data.id + * @param data.requestBody + * @returns ItemPublic Successful Response + * @throws ApiError + */ + public static updateItem(data: ItemsUpdateItemData): CancelablePromise { + return __request(OpenAPI, { + method: 'PUT', + url: '/api/v1/items/{id}', + path: { + id: data.id + }, + body: data.requestBody, + mediaType: 'application/json', + errors: { + 422: 'Validation Error' + } + }); + } + + /** + * Delete Item + * Delete an item. + * @param data The data for the request. + * @param data.id + * @returns Message Successful Response + * @throws ApiError + */ + public static deleteItem(data: ItemsDeleteItemData): CancelablePromise { + return __request(OpenAPI, { + method: 'DELETE', + url: '/api/v1/items/{id}', + path: { + id: data.id + }, + errors: { + 422: 'Validation Error' + } + }); + } +} + +export class LoginService { + /** + * Login Access Token + * OAuth2 compatible token login, get an access token for future requests + * @param data The data for the request. + * @param data.formData + * @returns Token Successful Response + * @throws ApiError + */ + public static loginAccessToken(data: LoginLoginAccessTokenData): CancelablePromise { + return __request(OpenAPI, { + method: 'POST', + url: '/api/v1/login/access-token', + formData: data.formData, + mediaType: 'application/x-www-form-urlencoded', + errors: { + 422: 'Validation Error' + } + }); + } + + /** + * Test Token + * Test access token + * @returns UserPublic Successful Response + * @throws ApiError + */ + public static testToken(): CancelablePromise { + return __request(OpenAPI, { + method: 'POST', + url: '/api/v1/login/test-token' + }); + } + + /** + * Recover Password + * Password Recovery + * @param data The data for the request. + * @param data.email + * @returns Message Successful Response + * @throws ApiError + */ + public static recoverPassword(data: LoginRecoverPasswordData): CancelablePromise { + return __request(OpenAPI, { + method: 'POST', + url: '/api/v1/password-recovery/{email}', + path: { + email: data.email + }, + errors: { + 422: 'Validation Error' + } + }); + } + + /** + * Reset Password + * Reset password + * @param data The data for the request. + * @param data.requestBody + * @returns Message Successful Response + * @throws ApiError + */ + public static resetPassword(data: LoginResetPasswordData): CancelablePromise { + return __request(OpenAPI, { + method: 'POST', + url: '/api/v1/reset-password/', + body: data.requestBody, + mediaType: 'application/json', + errors: { + 422: 'Validation Error' + } + }); + } + + /** + * Recover Password Html Content + * HTML Content for Password Recovery + * @param data The data for the request. + * @param data.email + * @returns string Successful Response + * @throws ApiError + */ + public static recoverPasswordHtmlContent(data: LoginRecoverPasswordHtmlContentData): CancelablePromise { + return __request(OpenAPI, { + method: 'POST', + url: '/api/v1/password-recovery-html-content/{email}', + path: { + email: data.email + }, + errors: { + 422: 'Validation Error' + } + }); + } +} + +export class PrivateService { + /** + * Create User + * Create a new user. + * @param data The data for the request. + * @param data.requestBody + * @returns UserPublic Successful Response + * @throws ApiError + */ + public static createUser(data: PrivateCreateUserData): CancelablePromise { + return __request(OpenAPI, { + method: 'POST', + url: '/api/v1/private/users/', + body: data.requestBody, + mediaType: 'application/json', + errors: { + 422: 'Validation Error' + } + }); + } +} + +export class UsersService { + /** + * Read Users + * Retrieve users. + * @param data The data for the request. + * @param data.skip + * @param data.limit + * @returns UsersPublic Successful Response + * @throws ApiError + */ + public static readUsers(data: UsersReadUsersData = {}): CancelablePromise { + return __request(OpenAPI, { + method: 'GET', + url: '/api/v1/users/', + query: { + skip: data.skip, + limit: data.limit + }, + errors: { + 422: 'Validation Error' + } + }); + } + + /** + * Create User + * Create new user. + * @param data The data for the request. + * @param data.requestBody + * @returns UserPublic Successful Response + * @throws ApiError + */ + public static createUser(data: UsersCreateUserData): CancelablePromise { + return __request(OpenAPI, { + method: 'POST', + url: '/api/v1/users/', + body: data.requestBody, + mediaType: 'application/json', + errors: { + 422: 'Validation Error' + } + }); + } + + /** + * Read User Me + * Get current user. + * @returns UserPublic Successful Response + * @throws ApiError + */ + public static readUserMe(): CancelablePromise { + return __request(OpenAPI, { + method: 'GET', + url: '/api/v1/users/me' + }); + } + + /** + * Delete User Me + * Delete own user. + * @returns Message Successful Response + * @throws ApiError + */ + public static deleteUserMe(): CancelablePromise { + return __request(OpenAPI, { + method: 'DELETE', + url: '/api/v1/users/me' + }); + } + + /** + * Update User Me + * Update own user. + * @param data The data for the request. + * @param data.requestBody + * @returns UserPublic Successful Response + * @throws ApiError + */ + public static updateUserMe(data: UsersUpdateUserMeData): CancelablePromise { + return __request(OpenAPI, { + method: 'PATCH', + url: '/api/v1/users/me', + body: data.requestBody, + mediaType: 'application/json', + errors: { + 422: 'Validation Error' + } + }); + } + + /** + * Update Password Me + * Update own password. + * @param data The data for the request. + * @param data.requestBody + * @returns Message Successful Response + * @throws ApiError + */ + public static updatePasswordMe(data: UsersUpdatePasswordMeData): CancelablePromise { + return __request(OpenAPI, { + method: 'PATCH', + url: '/api/v1/users/me/password', + body: data.requestBody, + mediaType: 'application/json', + errors: { + 422: 'Validation Error' + } + }); + } + + /** + * Register User + * Create new user without the need to be logged in. + * @param data The data for the request. + * @param data.requestBody + * @returns UserPublic Successful Response + * @throws ApiError + */ + public static registerUser(data: UsersRegisterUserData): CancelablePromise { + return __request(OpenAPI, { + method: 'POST', + url: '/api/v1/users/signup', + body: data.requestBody, + mediaType: 'application/json', + errors: { + 422: 'Validation Error' + } + }); + } + + /** + * Read User By Id + * Get a specific user by id. + * @param data The data for the request. + * @param data.userId + * @returns UserPublic Successful Response + * @throws ApiError + */ + public static readUserById(data: UsersReadUserByIdData): CancelablePromise { + return __request(OpenAPI, { + method: 'GET', + url: '/api/v1/users/{user_id}', + path: { + user_id: data.userId + }, + errors: { + 422: 'Validation Error' + } + }); + } + + /** + * Update User + * Update a user. + * @param data The data for the request. + * @param data.userId + * @param data.requestBody + * @returns UserPublic Successful Response + * @throws ApiError + */ + public static updateUser(data: UsersUpdateUserData): CancelablePromise { + return __request(OpenAPI, { + method: 'PATCH', + url: '/api/v1/users/{user_id}', + path: { + user_id: data.userId + }, + body: data.requestBody, + mediaType: 'application/json', + errors: { + 422: 'Validation Error' + } + }); + } + + /** + * Delete User + * Delete a user. + * @param data The data for the request. + * @param data.userId + * @returns Message Successful Response + * @throws ApiError + */ + public static deleteUser(data: UsersDeleteUserData): CancelablePromise { + return __request(OpenAPI, { + method: 'DELETE', + url: '/api/v1/users/{user_id}', + path: { + user_id: data.userId + }, + errors: { + 422: 'Validation Error' + } + }); + } +} + +export class UtilsService { + /** + * Test Email + * Test emails. + * @param data The data for the request. + * @param data.emailTo + * @returns Message Successful Response + * @throws ApiError + */ + public static testEmail(data: UtilsTestEmailData): CancelablePromise { + return __request(OpenAPI, { + method: 'POST', + url: '/api/v1/utils/test-email/', + query: { + email_to: data.emailTo + }, + errors: { + 422: 'Validation Error' + } + }); + } + + /** + * Health Check + * @returns boolean Successful Response + * @throws ApiError + */ + public static healthCheck(): CancelablePromise { + return __request(OpenAPI, { + method: 'GET', + url: '/api/v1/utils/health-check/' + }); + } +} \ No newline at end of file diff --git a/skills/outpost/examples/fastapi-saas/frontend/src/client/types.gen.ts b/skills/outpost/examples/fastapi-saas/frontend/src/client/types.gen.ts new file mode 100644 index 0000000..91b5ba3 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/frontend/src/client/types.gen.ts @@ -0,0 +1,240 @@ +// This file is auto-generated by @hey-api/openapi-ts + +export type Body_login_login_access_token = { + grant_type?: (string | null); + username: string; + password: string; + scope?: string; + client_id?: (string | null); + client_secret?: (string | null); +}; + +export type HTTPValidationError = { + detail?: Array; +}; + +export type ItemCreate = { + title: string; + description?: (string | null); +}; + +export type ItemPublic = { + title: string; + description?: (string | null); + id: string; + owner_id: string; + created_at?: (string | null); +}; + +export type ItemsPublic = { + data: Array; + count: number; +}; + +export type ItemUpdate = { + title?: (string | null); + description?: (string | null); +}; + +export type Message = { + message: string; +}; + +export type NewPassword = { + token: string; + new_password: string; +}; + +export type PrivateUserCreate = { + email: string; + password: string; + full_name: string; + is_verified?: boolean; +}; + +export type Token = { + access_token: string; + token_type?: string; +}; + +export type UpdatePassword = { + current_password: string; + new_password: string; +}; + +export type UserCreate = { + email: string; + is_active?: boolean; + is_superuser?: boolean; + full_name?: (string | null); + password: string; +}; + +export type UserPublic = { + email: string; + is_active?: boolean; + is_superuser?: boolean; + full_name?: (string | null); + id: string; + created_at?: (string | null); +}; + +export type UserRegister = { + email: string; + password: string; + full_name?: (string | null); +}; + +export type UsersPublic = { + data: Array; + count: number; +}; + +export type UserUpdate = { + email?: (string | null); + is_active?: boolean; + is_superuser?: boolean; + full_name?: (string | null); + password?: (string | null); +}; + +export type UserUpdateMe = { + full_name?: (string | null); + email?: (string | null); +}; + +export type ValidationError = { + loc: Array<(string | number)>; + msg: string; + type: string; + input?: unknown; + ctx?: { + [key: string]: unknown; + }; +}; + +export type ItemsReadItemsData = { + limit?: number; + skip?: number; +}; + +export type ItemsReadItemsResponse = (ItemsPublic); + +export type ItemsCreateItemData = { + requestBody: ItemCreate; +}; + +export type ItemsCreateItemResponse = (ItemPublic); + +export type ItemsReadItemData = { + id: string; +}; + +export type ItemsReadItemResponse = (ItemPublic); + +export type ItemsUpdateItemData = { + id: string; + requestBody: ItemUpdate; +}; + +export type ItemsUpdateItemResponse = (ItemPublic); + +export type ItemsDeleteItemData = { + id: string; +}; + +export type ItemsDeleteItemResponse = (Message); + +export type LoginLoginAccessTokenData = { + formData: Body_login_login_access_token; +}; + +export type LoginLoginAccessTokenResponse = (Token); + +export type LoginTestTokenResponse = (UserPublic); + +export type LoginRecoverPasswordData = { + email: string; +}; + +export type LoginRecoverPasswordResponse = (Message); + +export type LoginResetPasswordData = { + requestBody: NewPassword; +}; + +export type LoginResetPasswordResponse = (Message); + +export type LoginRecoverPasswordHtmlContentData = { + email: string; +}; + +export type LoginRecoverPasswordHtmlContentResponse = (string); + +export type PrivateCreateUserData = { + requestBody: PrivateUserCreate; +}; + +export type PrivateCreateUserResponse = (UserPublic); + +export type UsersReadUsersData = { + limit?: number; + skip?: number; +}; + +export type UsersReadUsersResponse = (UsersPublic); + +export type UsersCreateUserData = { + requestBody: UserCreate; +}; + +export type UsersCreateUserResponse = (UserPublic); + +export type UsersReadUserMeResponse = (UserPublic); + +export type UsersDeleteUserMeResponse = (Message); + +export type UsersUpdateUserMeData = { + requestBody: UserUpdateMe; +}; + +export type UsersUpdateUserMeResponse = (UserPublic); + +export type UsersUpdatePasswordMeData = { + requestBody: UpdatePassword; +}; + +export type UsersUpdatePasswordMeResponse = (Message); + +export type UsersRegisterUserData = { + requestBody: UserRegister; +}; + +export type UsersRegisterUserResponse = (UserPublic); + +export type UsersReadUserByIdData = { + userId: string; +}; + +export type UsersReadUserByIdResponse = (UserPublic); + +export type UsersUpdateUserData = { + requestBody: UserUpdate; + userId: string; +}; + +export type UsersUpdateUserResponse = (UserPublic); + +export type UsersDeleteUserData = { + userId: string; +}; + +export type UsersDeleteUserResponse = (Message); + +export type UtilsTestEmailData = { + emailTo: string; +}; + +export type UtilsTestEmailResponse = (Message); + +export type UtilsHealthCheckResponse = (boolean); \ No newline at end of file diff --git a/skills/outpost/examples/fastapi-saas/frontend/src/components/Admin/AddUser.tsx b/skills/outpost/examples/fastapi-saas/frontend/src/components/Admin/AddUser.tsx new file mode 100644 index 0000000..a0b534b --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/frontend/src/components/Admin/AddUser.tsx @@ -0,0 +1,238 @@ +import { zodResolver } from "@hookform/resolvers/zod" +import { useMutation, useQueryClient } from "@tanstack/react-query" +import { Plus } from "lucide-react" +import { useState } from "react" +import { useForm } from "react-hook-form" +import { z } from "zod" + +import { type UserCreate, UsersService } from "@/client" +import { Button } from "@/components/ui/button" +import { Checkbox } from "@/components/ui/checkbox" +import { + Dialog, + DialogClose, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, + DialogTrigger, +} from "@/components/ui/dialog" +import { + Form, + FormControl, + FormField, + FormItem, + FormLabel, + FormMessage, +} from "@/components/ui/form" +import { Input } from "@/components/ui/input" +import { LoadingButton } from "@/components/ui/loading-button" +import useCustomToast from "@/hooks/useCustomToast" +import { handleError } from "@/utils" + +const formSchema = z + .object({ + email: z.email({ message: "Invalid email address" }), + full_name: z.string().optional(), + password: z + .string() + .min(1, { message: "Password is required" }) + .min(8, { message: "Password must be at least 8 characters" }), + confirm_password: z + .string() + .min(1, { message: "Please confirm your password" }), + is_superuser: z.boolean(), + is_active: z.boolean(), + }) + .refine((data) => data.password === data.confirm_password, { + message: "The passwords don't match", + path: ["confirm_password"], + }) + +type FormData = z.infer + +const AddUser = () => { + const [isOpen, setIsOpen] = useState(false) + const queryClient = useQueryClient() + const { showSuccessToast, showErrorToast } = useCustomToast() + + const form = useForm({ + resolver: zodResolver(formSchema), + mode: "onBlur", + criteriaMode: "all", + defaultValues: { + email: "", + full_name: "", + password: "", + confirm_password: "", + is_superuser: false, + is_active: false, + }, + }) + + const mutation = useMutation({ + mutationFn: (data: UserCreate) => + UsersService.createUser({ requestBody: data }), + onSuccess: () => { + showSuccessToast("User created successfully") + form.reset() + setIsOpen(false) + }, + onError: handleError.bind(showErrorToast), + onSettled: () => { + queryClient.invalidateQueries({ queryKey: ["users"] }) + }, + }) + + const onSubmit = (data: FormData) => { + mutation.mutate(data) + } + + return ( + + + + + + + Add User + + Fill in the form below to add a new user to the system. + + +
+ +
+ ( + + + Email * + + + + + + + )} + /> + + ( + + Full Name + + + + + + )} + /> + + ( + + + Set Password * + + + + + + + )} + /> + + ( + + + Confirm Password{" "} + * + + + + + + + )} + /> + + ( + + + + + Is superuser? + + )} + /> + + ( + + + + + Is active? + + )} + /> +
+ + + + + + + Save + + +
+ +
+
+ ) +} + +export default AddUser diff --git a/skills/outpost/examples/fastapi-saas/frontend/src/components/Admin/DeleteUser.tsx b/skills/outpost/examples/fastapi-saas/frontend/src/components/Admin/DeleteUser.tsx new file mode 100644 index 0000000..4ffd023 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/frontend/src/components/Admin/DeleteUser.tsx @@ -0,0 +1,95 @@ +import { useMutation, useQueryClient } from "@tanstack/react-query" +import { Trash2 } from "lucide-react" +import { useState } from "react" +import { useForm } from "react-hook-form" + +import { UsersService } from "@/client" +import { Button } from "@/components/ui/button" +import { + Dialog, + DialogClose, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from "@/components/ui/dialog" +import { DropdownMenuItem } from "@/components/ui/dropdown-menu" +import { LoadingButton } from "@/components/ui/loading-button" +import useCustomToast from "@/hooks/useCustomToast" +import { handleError } from "@/utils" + +interface DeleteUserProps { + id: string + onSuccess: () => void +} + +const DeleteUser = ({ id, onSuccess }: DeleteUserProps) => { + const [isOpen, setIsOpen] = useState(false) + const queryClient = useQueryClient() + const { showSuccessToast, showErrorToast } = useCustomToast() + const { handleSubmit } = useForm() + + const deleteUser = async (id: string) => { + await UsersService.deleteUser({ userId: id }) + } + + const mutation = useMutation({ + mutationFn: deleteUser, + onSuccess: () => { + showSuccessToast("The user was deleted successfully") + setIsOpen(false) + onSuccess() + }, + onError: handleError.bind(showErrorToast), + onSettled: () => { + queryClient.invalidateQueries() + }, + }) + + const onSubmit = async () => { + mutation.mutate(id) + } + + return ( + + e.preventDefault()} + onClick={() => setIsOpen(true)} + > + + Delete User + + +
+ + Delete User + + All items associated with this user will also be{" "} + permanently deleted. Are you sure? You will not + be able to undo this action. + + + + + + + + + Delete + + +
+
+
+ ) +} + +export default DeleteUser diff --git a/skills/outpost/examples/fastapi-saas/frontend/src/components/Admin/EditUser.tsx b/skills/outpost/examples/fastapi-saas/frontend/src/components/Admin/EditUser.tsx new file mode 100644 index 0000000..172904f --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/frontend/src/components/Admin/EditUser.tsx @@ -0,0 +1,239 @@ +import { zodResolver } from "@hookform/resolvers/zod" +import { useMutation, useQueryClient } from "@tanstack/react-query" +import { Pencil } from "lucide-react" +import { useState } from "react" +import { useForm } from "react-hook-form" +import { z } from "zod" + +import { type UserPublic, UsersService } from "@/client" +import { Button } from "@/components/ui/button" +import { Checkbox } from "@/components/ui/checkbox" +import { + Dialog, + DialogClose, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from "@/components/ui/dialog" +import { DropdownMenuItem } from "@/components/ui/dropdown-menu" +import { + Form, + FormControl, + FormField, + FormItem, + FormLabel, + FormMessage, +} from "@/components/ui/form" +import { Input } from "@/components/ui/input" +import { LoadingButton } from "@/components/ui/loading-button" +import useCustomToast from "@/hooks/useCustomToast" +import { handleError } from "@/utils" + +const formSchema = z + .object({ + email: z.email({ message: "Invalid email address" }), + full_name: z.string().optional(), + password: z + .string() + .min(8, { message: "Password must be at least 8 characters" }) + .optional() + .or(z.literal("")), + confirm_password: z.string().optional(), + is_superuser: z.boolean().optional(), + is_active: z.boolean().optional(), + }) + .refine((data) => !data.password || data.password === data.confirm_password, { + message: "The passwords don't match", + path: ["confirm_password"], + }) + +type FormData = z.infer + +interface EditUserProps { + user: UserPublic + onSuccess: () => void +} + +const EditUser = ({ user, onSuccess }: EditUserProps) => { + const [isOpen, setIsOpen] = useState(false) + const queryClient = useQueryClient() + const { showSuccessToast, showErrorToast } = useCustomToast() + + const form = useForm({ + resolver: zodResolver(formSchema), + mode: "onBlur", + criteriaMode: "all", + defaultValues: { + email: user.email, + full_name: user.full_name ?? undefined, + is_superuser: user.is_superuser, + is_active: user.is_active, + }, + }) + + const mutation = useMutation({ + mutationFn: (data: FormData) => + UsersService.updateUser({ userId: user.id, requestBody: data }), + onSuccess: () => { + showSuccessToast("User updated successfully") + setIsOpen(false) + onSuccess() + }, + onError: handleError.bind(showErrorToast), + onSettled: () => { + queryClient.invalidateQueries({ queryKey: ["users"] }) + }, + }) + + const onSubmit = (data: FormData) => { + // exclude confirm_password from submission data and remove password if empty + const { confirm_password: _, ...submitData } = data + if (!submitData.password) { + delete submitData.password + } + mutation.mutate(submitData) + } + + return ( + + e.preventDefault()} + onClick={() => setIsOpen(true)} + > + + Edit User + + +
+ + + Edit User + + Update the user details below. + + +
+ ( + + + Email * + + + + + + + )} + /> + + ( + + Full Name + + + + + + )} + /> + + ( + + Set Password + + + + + + )} + /> + + ( + + Confirm Password + + + + + + )} + /> + + ( + + + + + Is superuser? + + )} + /> + + ( + + + + + Is active? + + )} + /> +
+ + + + + + + Save + + +
+ +
+
+ ) +} + +export default EditUser diff --git a/skills/outpost/examples/fastapi-saas/frontend/src/components/Admin/UserActionsMenu.tsx b/skills/outpost/examples/fastapi-saas/frontend/src/components/Admin/UserActionsMenu.tsx new file mode 100644 index 0000000..01f71cb --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/frontend/src/components/Admin/UserActionsMenu.tsx @@ -0,0 +1,40 @@ +import { EllipsisVertical } from "lucide-react" +import { useState } from "react" + +import type { UserPublic } from "@/client" +import { Button } from "@/components/ui/button" +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuTrigger, +} from "@/components/ui/dropdown-menu" +import useAuth from "@/hooks/useAuth" +import DeleteUser from "./DeleteUser" +import EditUser from "./EditUser" + +interface UserActionsMenuProps { + user: UserPublic +} + +export const UserActionsMenu = ({ user }: UserActionsMenuProps) => { + const [open, setOpen] = useState(false) + const { user: currentUser } = useAuth() + + if (user.id === currentUser?.id) { + return null + } + + return ( + + + + + + setOpen(false)} /> + setOpen(false)} /> + + + ) +} diff --git a/skills/outpost/examples/fastapi-saas/frontend/src/components/Admin/columns.tsx b/skills/outpost/examples/fastapi-saas/frontend/src/components/Admin/columns.tsx new file mode 100644 index 0000000..8b0fa13 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/frontend/src/components/Admin/columns.tsx @@ -0,0 +1,76 @@ +import type { ColumnDef } from "@tanstack/react-table" + +import type { UserPublic } from "@/client" +import { Badge } from "@/components/ui/badge" +import { cn } from "@/lib/utils" +import { UserActionsMenu } from "./UserActionsMenu" + +export type UserTableData = UserPublic & { + isCurrentUser: boolean +} + +export const columns: ColumnDef[] = [ + { + accessorKey: "full_name", + header: "Full Name", + cell: ({ row }) => { + const fullName = row.original.full_name + return ( +
+ + {fullName || "N/A"} + + {row.original.isCurrentUser && ( + + You + + )} +
+ ) + }, + }, + { + accessorKey: "email", + header: "Email", + cell: ({ row }) => ( + {row.original.email} + ), + }, + { + accessorKey: "is_superuser", + header: "Role", + cell: ({ row }) => ( + + {row.original.is_superuser ? "Superuser" : "User"} + + ), + }, + { + accessorKey: "is_active", + header: "Status", + cell: ({ row }) => ( +
+ + + {row.original.is_active ? "Active" : "Inactive"} + +
+ ), + }, + { + id: "actions", + header: () => Actions, + cell: ({ row }) => ( +
+ +
+ ), + }, +] diff --git a/skills/outpost/examples/fastapi-saas/frontend/src/components/Common/Appearance.tsx b/skills/outpost/examples/fastapi-saas/frontend/src/components/Common/Appearance.tsx new file mode 100644 index 0000000..1c56f6c --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/frontend/src/components/Common/Appearance.tsx @@ -0,0 +1,105 @@ +import { Monitor, Moon, Sun } from "lucide-react" + +import { type Theme, useTheme } from "@/components/theme-provider" +import { Button } from "@/components/ui/button" +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuTrigger, +} from "@/components/ui/dropdown-menu" +import { + SidebarMenuButton, + SidebarMenuItem, + useSidebar, +} from "@/components/ui/sidebar" + +type LucideIcon = React.FC> + +const ICON_MAP: Record = { + system: Monitor, + light: Sun, + dark: Moon, +} + +export const SidebarAppearance = () => { + const { isMobile } = useSidebar() + const { setTheme, theme } = useTheme() + const Icon = ICON_MAP[theme] + + return ( + + + + + + Appearance + Toggle theme + + + + setTheme("light")} + > + + Light + + setTheme("dark")} + > + + Dark + + setTheme("system")}> + + System + + + + + ) +} + +export const Appearance = () => { + const { setTheme } = useTheme() + + return ( +
+ + + + + + setTheme("light")} + > + + Light + + setTheme("dark")} + > + + Dark + + setTheme("system")}> + + System + + + +
+ ) +} diff --git a/skills/outpost/examples/fastapi-saas/frontend/src/components/Common/AuthLayout.tsx b/skills/outpost/examples/fastapi-saas/frontend/src/components/Common/AuthLayout.tsx new file mode 100644 index 0000000..4551610 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/frontend/src/components/Common/AuthLayout.tsx @@ -0,0 +1,26 @@ +import { Appearance } from "@/components/Common/Appearance" +import { Logo } from "@/components/Common/Logo" +import { Footer } from "./Footer" + +interface AuthLayoutProps { + children: React.ReactNode +} + +export function AuthLayout({ children }: AuthLayoutProps) { + return ( +
+
+ +
+
+
+ +
+
+
{children}
+
+
+
+
+ ) +} diff --git a/skills/outpost/examples/fastapi-saas/frontend/src/components/Common/DataTable.tsx b/skills/outpost/examples/fastapi-saas/frontend/src/components/Common/DataTable.tsx new file mode 100644 index 0000000..e5bf2ae --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/frontend/src/components/Common/DataTable.tsx @@ -0,0 +1,194 @@ +import { + type ColumnDef, + flexRender, + getCoreRowModel, + getPaginationRowModel, + useReactTable, +} from "@tanstack/react-table" +import { + ChevronLeft, + ChevronRight, + ChevronsLeft, + ChevronsRight, +} from "lucide-react" + +import { Button } from "@/components/ui/button" +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from "@/components/ui/select" +import { + Table, + TableBody, + TableCell, + TableHead, + TableHeader, + TableRow, +} from "@/components/ui/table" + +interface DataTableProps { + columns: ColumnDef[] + data: TData[] +} + +export function DataTable({ + columns, + data, +}: DataTableProps) { + const table = useReactTable({ + data, + columns, + getCoreRowModel: getCoreRowModel(), + getPaginationRowModel: getPaginationRowModel(), + }) + + return ( +
+ + + {table.getHeaderGroups().map((headerGroup) => ( + + {headerGroup.headers.map((header) => { + return ( + + {header.isPlaceholder + ? null + : flexRender( + header.column.columnDef.header, + header.getContext(), + )} + + ) + })} + + ))} + + + {table.getRowModel().rows.length ? ( + table.getRowModel().rows.map((row) => ( + + {row.getVisibleCells().map((cell) => ( + + {flexRender(cell.column.columnDef.cell, cell.getContext())} + + ))} + + )) + ) : ( + + + No results found. + + + )} + +
+ + {table.getPageCount() > 1 && ( +
+
+
+ Showing{" "} + {table.getState().pagination.pageIndex * + table.getState().pagination.pageSize + + 1}{" "} + to{" "} + {Math.min( + (table.getState().pagination.pageIndex + 1) * + table.getState().pagination.pageSize, + data.length, + )}{" "} + of{" "} + {data.length}{" "} + entries +
+
+

Rows per page

+ +
+
+ +
+
+ Page + + {table.getState().pagination.pageIndex + 1} + + of + + {table.getPageCount()} + +
+ +
+ + + + +
+
+
+ )} +
+ ) +} diff --git a/skills/outpost/examples/fastapi-saas/frontend/src/components/Common/ErrorComponent.tsx b/skills/outpost/examples/fastapi-saas/frontend/src/components/Common/ErrorComponent.tsx new file mode 100644 index 0000000..e4a97d2 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/frontend/src/components/Common/ErrorComponent.tsx @@ -0,0 +1,29 @@ +import { Link } from "@tanstack/react-router" +import { Button } from "@/components/ui/button" + +const ErrorComponent = () => { + return ( +
+
+
+ + Error + + Oops! +
+
+ +

+ Something went wrong. Please try again. +

+ + + +
+ ) +} + +export default ErrorComponent diff --git a/skills/outpost/examples/fastapi-saas/frontend/src/components/Common/Footer.tsx b/skills/outpost/examples/fastapi-saas/frontend/src/components/Common/Footer.tsx new file mode 100644 index 0000000..279e1e7 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/frontend/src/components/Common/Footer.tsx @@ -0,0 +1,44 @@ +import { FaGithub, FaLinkedinIn } from "react-icons/fa" +import { FaXTwitter } from "react-icons/fa6" + +const socialLinks = [ + { + icon: FaGithub, + href: "https://github.com/fastapi/fastapi", + label: "GitHub", + }, + { icon: FaXTwitter, href: "https://x.com/fastapi", label: "X" }, + { + icon: FaLinkedinIn, + href: "https://linkedin.com/company/fastapi", + label: "LinkedIn", + }, +] + +export function Footer() { + const currentYear = new Date().getFullYear() + + return ( +
+
+

+ Full Stack FastAPI Template - {currentYear} +

+
+ {socialLinks.map(({ icon: Icon, href, label }) => ( + + + + ))} +
+
+
+ ) +} diff --git a/skills/outpost/examples/fastapi-saas/frontend/src/components/Common/Logo.tsx b/skills/outpost/examples/fastapi-saas/frontend/src/components/Common/Logo.tsx new file mode 100644 index 0000000..05c299f --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/frontend/src/components/Common/Logo.tsx @@ -0,0 +1,60 @@ +import { Link } from "@tanstack/react-router" + +import { useTheme } from "@/components/theme-provider" +import { cn } from "@/lib/utils" +import icon from "/assets/images/fastapi-icon.svg" +import iconLight from "/assets/images/fastapi-icon-light.svg" +import logo from "/assets/images/fastapi-logo.svg" +import logoLight from "/assets/images/fastapi-logo-light.svg" + +interface LogoProps { + variant?: "full" | "icon" | "responsive" + className?: string + asLink?: boolean +} + +export function Logo({ + variant = "full", + className, + asLink = true, +}: LogoProps) { + const { resolvedTheme } = useTheme() + const isDark = resolvedTheme === "dark" + + const fullLogo = isDark ? logoLight : logo + const iconLogo = isDark ? iconLight : icon + + const content = + variant === "responsive" ? ( + <> + FastAPI + + + ) : ( + FastAPI + ) + + if (!asLink) { + return content + } + + return {content} +} diff --git a/skills/outpost/examples/fastapi-saas/frontend/src/components/Common/NotFound.tsx b/skills/outpost/examples/fastapi-saas/frontend/src/components/Common/NotFound.tsx new file mode 100644 index 0000000..04f42b8 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/frontend/src/components/Common/NotFound.tsx @@ -0,0 +1,31 @@ +import { Link } from "@tanstack/react-router" +import { Button } from "@/components/ui/button" + +const NotFound = () => { + return ( +
+
+
+ + 404 + + Oops! +
+
+ +

+ The page you are looking for was not found. +

+
+ + + +
+
+ ) +} + +export default NotFound diff --git a/skills/outpost/examples/fastapi-saas/frontend/src/components/Destinations/CreateDestination.tsx b/skills/outpost/examples/fastapi-saas/frontend/src/components/Destinations/CreateDestination.tsx new file mode 100644 index 0000000..ffe6045 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/frontend/src/components/Destinations/CreateDestination.tsx @@ -0,0 +1,451 @@ +/** + * 3-step Create Destination wizard. + * + * Step 1 — Choose destination type (from GET /destination-types) + * Step 2 — Select topics (from GET /topics) + * Step 3 — Fill type-specific config / credentials + */ + +import { useMutation, useQuery } from "@tanstack/react-query" +import { AlertCircle, CheckCircle2, ChevronLeft, Loader2, Webhook } from "lucide-react" +import { useState } from "react" +import { toast } from "sonner" + +import { + type DestinationSchemaField, + type DestinationType, + outpostApi, +} from "@/lib/outpost-api" +import { Button } from "@/components/ui/button" +import { Checkbox } from "@/components/ui/checkbox" +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from "@/components/ui/dialog" +import { Input } from "@/components/ui/input" +import { Label } from "@/components/ui/label" + +// --------------------------------------------------------------------------- +// Step 1: Pick destination type +// --------------------------------------------------------------------------- + +function TypeCard({ + schema, + selected, + onSelect, +}: { + schema: DestinationType + selected: boolean + onSelect: () => void +}) { + return ( + + ) +} + +function StepPickType({ + types, + selected, + onSelect, +}: { + types: DestinationType[] + selected: string | null + onSelect: (t: string) => void +}) { + return ( +
+ {types.map((t) => ( + onSelect(t.type)} + /> + ))} +
+ ) +} + +// --------------------------------------------------------------------------- +// Step 2: Select topics +// --------------------------------------------------------------------------- + +function StepPickTopics({ + topics, + selected, + onChange, +}: { + topics: string[] + selected: string[] + onChange: (topics: string[]) => void +}) { + const allSelected = selected.includes("*") + + const toggle = (topic: string) => { + if (topic === "*") { + onChange(allSelected ? [] : ["*"]) + return + } + if (allSelected) { + // switch from "all" to explicit list minus this one + onChange(topics.filter((t) => t !== topic)) + return + } + if (selected.includes(topic)) { + onChange(selected.filter((t) => t !== topic)) + } else { + onChange([...selected, topic]) + } + } + + return ( +
+

+ Choose which topics this destination should receive. Select "All topics" to + subscribe to everything. +

+ + {/* All topics shortcut */} + + + {/* Individual topics */} +
+ {topics.map((topic) => ( + + ))} +
+
+ ) +} + +// --------------------------------------------------------------------------- +// Step 3: Config / credentials form (dynamic) +// --------------------------------------------------------------------------- + +function ConfigField({ + field, + value, + onChange, +}: { + field: DestinationSchemaField + value: string + onChange: (v: string) => void +}) { + return ( +
+ + onChange(e.target.value)} + required={field.required} + /> + {field.description && ( +

{field.description}

+ )} +
+ ) +} + +function StepConfigure({ + schema, + configValues, + credValues, + onConfigChange, + onCredChange, +}: { + schema: DestinationType + configValues: Record + credValues: Record + onConfigChange: (k: string, v: string) => void + onCredChange: (k: string, v: string) => void +}) { + return ( +
+ {schema.instructions && ( +
+ {schema.instructions} +
+ )} + {schema.remote_setup_url && ( + + Complete external setup → + + )} + {schema.config_fields.map((f) => ( + onConfigChange(f.key, v)} + /> + ))} + {schema.credential_fields.map((f) => ( + onCredChange(f.key, v)} + /> + ))} +
+ ) +} + +// --------------------------------------------------------------------------- +// Wizard shell +// --------------------------------------------------------------------------- + +const STEP_LABELS = ["Choose type", "Select topics", "Configure"] + +interface CreateDestinationProps { + open: boolean + onClose: () => void + onCreated: () => void +} + +export default function CreateDestination({ + open, + onClose, + onCreated, +}: CreateDestinationProps) { + const [step, setStep] = useState(0) + const [selectedType, setSelectedType] = useState(null) + const [selectedTopics, setSelectedTopics] = useState([]) + const [configValues, setConfigValues] = useState>({}) + const [credValues, setCredValues] = useState>({}) + + const { data: types, isLoading: typesLoading } = useQuery({ + queryKey: ["outpost-destination-types"], + queryFn: outpostApi.listDestinationTypes, + enabled: open, + }) + + const { data: topics, isLoading: topicsLoading } = useQuery({ + queryKey: ["outpost-topics"], + queryFn: outpostApi.listTopics, + enabled: open, + }) + + const schema = types?.find((t) => t.type === selectedType) + + const createMutation = useMutation({ + mutationFn: () => { + if (!selectedType || selectedTopics.length === 0) throw new Error("Invalid state") + const config: Record = {} + for (const [k, v] of Object.entries(configValues)) { + if (v) config[k] = v + } + const credentials: Record = {} + for (const [k, v] of Object.entries(credValues)) { + if (v) credentials[k] = v + } + return outpostApi.createDestination({ + type: selectedType, + topics: selectedTopics.length === 1 && selectedTopics[0] === "*" ? "*" : selectedTopics, + config, + ...(Object.keys(credentials).length > 0 ? { credentials } : {}), + }) + }, + onSuccess: () => { + toast.success("Destination created successfully") + handleReset() + onCreated() + }, + onError: (err: Error) => toast.error(err.message), + }) + + const handleReset = () => { + setStep(0) + setSelectedType(null) + setSelectedTopics([]) + setConfigValues({}) + setCredValues({}) + } + + const handleClose = () => { + handleReset() + onClose() + } + + const canAdvance = () => { + if (step === 0) return selectedType !== null + if (step === 1) return selectedTopics.length > 0 + if (step === 2) { + if (!schema) return false + return schema.config_fields + .filter((f) => f.required) + .every((f) => configValues[f.key]?.trim()) + } + return false + } + + const handleNext = () => { + if (step < 2) setStep(step + 1) + else createMutation.mutate() + } + + return ( + + + + Add Event Destination + + Step {step + 1} of 3 — {STEP_LABELS[step]} + + + + {/* Step indicator */} +
+ {STEP_LABELS.map((label, i) => ( +
+
+ {label} +
+ ))} +
+ + {/* Step content */} +
+ {step === 0 && + (typesLoading ? ( +
+ +
+ ) : types && types.length > 0 ? ( + + ) : ( +
+ + No destination types available. Check your Outpost configuration. +
+ ))} + + {step === 1 && + (topicsLoading ? ( +
+ +
+ ) : topics ? ( + + ) : ( +
+ + Could not load topics. Check your Outpost configuration. +
+ ))} + + {step === 2 && + (schema ? ( + setConfigValues((p) => ({ ...p, [k]: v }))} + onCredChange={(k, v) => setCredValues((p) => ({ ...p, [k]: v }))} + /> + ) : ( +
+ +
+ ))} +
+ + + {step > 0 && ( + + )} + + + +
+ ) +} diff --git a/skills/outpost/examples/fastapi-saas/frontend/src/components/Items/AddItem.tsx b/skills/outpost/examples/fastapi-saas/frontend/src/components/Items/AddItem.tsx new file mode 100644 index 0000000..7c7c10c --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/frontend/src/components/Items/AddItem.tsx @@ -0,0 +1,144 @@ +import { zodResolver } from "@hookform/resolvers/zod" +import { useMutation, useQueryClient } from "@tanstack/react-query" +import { Plus } from "lucide-react" +import { useState } from "react" +import { useForm } from "react-hook-form" +import { z } from "zod" + +import { type ItemCreate, ItemsService } from "@/client" +import { Button } from "@/components/ui/button" +import { + Dialog, + DialogClose, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, + DialogTrigger, +} from "@/components/ui/dialog" +import { + Form, + FormControl, + FormField, + FormItem, + FormLabel, + FormMessage, +} from "@/components/ui/form" +import { Input } from "@/components/ui/input" +import { LoadingButton } from "@/components/ui/loading-button" +import useCustomToast from "@/hooks/useCustomToast" +import { handleError } from "@/utils" + +const formSchema = z.object({ + title: z.string().min(1, { message: "Title is required" }), + description: z.string().optional(), +}) + +type FormData = z.infer + +const AddItem = () => { + const [isOpen, setIsOpen] = useState(false) + const queryClient = useQueryClient() + const { showSuccessToast, showErrorToast } = useCustomToast() + + const form = useForm({ + resolver: zodResolver(formSchema), + mode: "onBlur", + criteriaMode: "all", + defaultValues: { + title: "", + description: "", + }, + }) + + const mutation = useMutation({ + mutationFn: (data: ItemCreate) => + ItemsService.createItem({ requestBody: data }), + onSuccess: () => { + showSuccessToast("Item created successfully") + form.reset() + setIsOpen(false) + }, + onError: handleError.bind(showErrorToast), + onSettled: () => { + queryClient.invalidateQueries({ queryKey: ["items"] }) + }, + }) + + const onSubmit = (data: FormData) => { + mutation.mutate(data) + } + + return ( + + + + + + + Add Item + + Fill in the details to add a new item. + + +
+ +
+ ( + + + Title * + + + + + + + )} + /> + + ( + + Description + + + + + + )} + /> +
+ + + + + + + Save + + +
+ +
+
+ ) +} + +export default AddItem diff --git a/skills/outpost/examples/fastapi-saas/frontend/src/components/Items/DeleteItem.tsx b/skills/outpost/examples/fastapi-saas/frontend/src/components/Items/DeleteItem.tsx new file mode 100644 index 0000000..9e61c34 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/frontend/src/components/Items/DeleteItem.tsx @@ -0,0 +1,94 @@ +import { useMutation, useQueryClient } from "@tanstack/react-query" +import { Trash2 } from "lucide-react" +import { useState } from "react" +import { useForm } from "react-hook-form" + +import { ItemsService } from "@/client" +import { Button } from "@/components/ui/button" +import { + Dialog, + DialogClose, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from "@/components/ui/dialog" +import { DropdownMenuItem } from "@/components/ui/dropdown-menu" +import { LoadingButton } from "@/components/ui/loading-button" +import useCustomToast from "@/hooks/useCustomToast" +import { handleError } from "@/utils" + +interface DeleteItemProps { + id: string + onSuccess: () => void +} + +const DeleteItem = ({ id, onSuccess }: DeleteItemProps) => { + const [isOpen, setIsOpen] = useState(false) + const queryClient = useQueryClient() + const { showSuccessToast, showErrorToast } = useCustomToast() + const { handleSubmit } = useForm() + + const deleteItem = async (id: string) => { + await ItemsService.deleteItem({ id: id }) + } + + const mutation = useMutation({ + mutationFn: deleteItem, + onSuccess: () => { + showSuccessToast("The item was deleted successfully") + setIsOpen(false) + onSuccess() + }, + onError: handleError.bind(showErrorToast), + onSettled: () => { + queryClient.invalidateQueries() + }, + }) + + const onSubmit = async () => { + mutation.mutate(id) + } + + return ( + + e.preventDefault()} + onClick={() => setIsOpen(true)} + > + + Delete Item + + +
+ + Delete Item + + This item will be permanently deleted. Are you sure? You will not + be able to undo this action. + + + + + + + + + Delete + + +
+
+
+ ) +} + +export default DeleteItem diff --git a/skills/outpost/examples/fastapi-saas/frontend/src/components/Items/EditItem.tsx b/skills/outpost/examples/fastapi-saas/frontend/src/components/Items/EditItem.tsx new file mode 100644 index 0000000..3d57f55 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/frontend/src/components/Items/EditItem.tsx @@ -0,0 +1,145 @@ +import { zodResolver } from "@hookform/resolvers/zod" +import { useMutation, useQueryClient } from "@tanstack/react-query" +import { Pencil } from "lucide-react" +import { useState } from "react" +import { useForm } from "react-hook-form" +import { z } from "zod" + +import { type ItemPublic, ItemsService } from "@/client" +import { Button } from "@/components/ui/button" +import { + Dialog, + DialogClose, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from "@/components/ui/dialog" +import { DropdownMenuItem } from "@/components/ui/dropdown-menu" +import { + Form, + FormControl, + FormField, + FormItem, + FormLabel, + FormMessage, +} from "@/components/ui/form" +import { Input } from "@/components/ui/input" +import { LoadingButton } from "@/components/ui/loading-button" +import useCustomToast from "@/hooks/useCustomToast" +import { handleError } from "@/utils" + +const formSchema = z.object({ + title: z.string().min(1, { message: "Title is required" }), + description: z.string().optional(), +}) + +type FormData = z.infer + +interface EditItemProps { + item: ItemPublic + onSuccess: () => void +} + +const EditItem = ({ item, onSuccess }: EditItemProps) => { + const [isOpen, setIsOpen] = useState(false) + const queryClient = useQueryClient() + const { showSuccessToast, showErrorToast } = useCustomToast() + + const form = useForm({ + resolver: zodResolver(formSchema), + mode: "onBlur", + criteriaMode: "all", + defaultValues: { + title: item.title, + description: item.description ?? undefined, + }, + }) + + const mutation = useMutation({ + mutationFn: (data: FormData) => + ItemsService.updateItem({ id: item.id, requestBody: data }), + onSuccess: () => { + showSuccessToast("Item updated successfully") + setIsOpen(false) + onSuccess() + }, + onError: handleError.bind(showErrorToast), + onSettled: () => { + queryClient.invalidateQueries({ queryKey: ["items"] }) + }, + }) + + const onSubmit = (data: FormData) => { + mutation.mutate(data) + } + + return ( + + e.preventDefault()} + onClick={() => setIsOpen(true)} + > + + Edit Item + + +
+ + + Edit Item + + Update the item details below. + + +
+ ( + + + Title * + + + + + + + )} + /> + + ( + + Description + + + + + + )} + /> +
+ + + + + + + Save + + +
+ +
+
+ ) +} + +export default EditItem diff --git a/skills/outpost/examples/fastapi-saas/frontend/src/components/Items/ItemActionsMenu.tsx b/skills/outpost/examples/fastapi-saas/frontend/src/components/Items/ItemActionsMenu.tsx new file mode 100644 index 0000000..1efe7bf --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/frontend/src/components/Items/ItemActionsMenu.tsx @@ -0,0 +1,34 @@ +import { EllipsisVertical } from "lucide-react" +import { useState } from "react" + +import type { ItemPublic } from "@/client" +import { Button } from "@/components/ui/button" +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuTrigger, +} from "@/components/ui/dropdown-menu" +import DeleteItem from "../Items/DeleteItem" +import EditItem from "../Items/EditItem" + +interface ItemActionsMenuProps { + item: ItemPublic +} + +export const ItemActionsMenu = ({ item }: ItemActionsMenuProps) => { + const [open, setOpen] = useState(false) + + return ( + + + + + + setOpen(false)} /> + setOpen(false)} /> + + + ) +} diff --git a/skills/outpost/examples/fastapi-saas/frontend/src/components/Items/columns.tsx b/skills/outpost/examples/fastapi-saas/frontend/src/components/Items/columns.tsx new file mode 100644 index 0000000..b41be2a --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/frontend/src/components/Items/columns.tsx @@ -0,0 +1,73 @@ +import type { ColumnDef } from "@tanstack/react-table" +import { Check, Copy } from "lucide-react" + +import type { ItemPublic } from "@/client" +import { Button } from "@/components/ui/button" +import { useCopyToClipboard } from "@/hooks/useCopyToClipboard" +import { cn } from "@/lib/utils" +import { ItemActionsMenu } from "./ItemActionsMenu" + +function CopyId({ id }: { id: string }) { + const [copiedText, copy] = useCopyToClipboard() + const isCopied = copiedText === id + + return ( +
+ {id} + +
+ ) +} + +export const columns: ColumnDef[] = [ + { + accessorKey: "id", + header: "ID", + cell: ({ row }) => , + }, + { + accessorKey: "title", + header: "Title", + cell: ({ row }) => ( + {row.original.title} + ), + }, + { + accessorKey: "description", + header: "Description", + cell: ({ row }) => { + const description = row.original.description + return ( + + {description || "No description"} + + ) + }, + }, + { + id: "actions", + header: () => Actions, + cell: ({ row }) => ( +
+ +
+ ), + }, +] diff --git a/skills/outpost/examples/fastapi-saas/frontend/src/components/Pending/PendingItems.tsx b/skills/outpost/examples/fastapi-saas/frontend/src/components/Pending/PendingItems.tsx new file mode 100644 index 0000000..9658335 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/frontend/src/components/Pending/PendingItems.tsx @@ -0,0 +1,46 @@ +import { Skeleton } from "@/components/ui/skeleton" +import { + Table, + TableBody, + TableCell, + TableHead, + TableHeader, + TableRow, +} from "@/components/ui/table" + +const PendingItems = () => ( + + + + ID + Title + Description + + Actions + + + + + {Array.from({ length: 5 }).map((_, index) => ( + + + + + + + + + + + +
+ +
+
+
+ ))} +
+
+) + +export default PendingItems diff --git a/skills/outpost/examples/fastapi-saas/frontend/src/components/Pending/PendingUsers.tsx b/skills/outpost/examples/fastapi-saas/frontend/src/components/Pending/PendingUsers.tsx new file mode 100644 index 0000000..85af2b1 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/frontend/src/components/Pending/PendingUsers.tsx @@ -0,0 +1,53 @@ +import { Skeleton } from "@/components/ui/skeleton" +import { + Table, + TableBody, + TableCell, + TableHead, + TableHeader, + TableRow, +} from "@/components/ui/table" + +const PendingUsers = () => ( + + + + Full Name + Email + Role + Status + + Actions + + + + + {Array.from({ length: 5 }).map((_, index) => ( + + + + + + + + + + + +
+ + +
+
+ +
+ +
+
+
+ ))} +
+
+) + +export default PendingUsers diff --git a/skills/outpost/examples/fastapi-saas/frontend/src/components/Sidebar/AppSidebar.tsx b/skills/outpost/examples/fastapi-saas/frontend/src/components/Sidebar/AppSidebar.tsx new file mode 100644 index 0000000..a77de3b --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/frontend/src/components/Sidebar/AppSidebar.tsx @@ -0,0 +1,44 @@ +import { Briefcase, Home, Users, Webhook } from "lucide-react" + +import { SidebarAppearance } from "@/components/Common/Appearance" +import { Logo } from "@/components/Common/Logo" +import { + Sidebar, + SidebarContent, + SidebarFooter, + SidebarHeader, +} from "@/components/ui/sidebar" +import useAuth from "@/hooks/useAuth" +import { type Item, Main } from "./Main" +import { User } from "./User" + +const baseItems: Item[] = [ + { icon: Home, title: "Dashboard", path: "/" }, + { icon: Briefcase, title: "Items", path: "/items" }, + { icon: Webhook, title: "Destinations", path: "/destinations" }, +] + +export function AppSidebar() { + const { user: currentUser } = useAuth() + + const items = currentUser?.is_superuser + ? [...baseItems, { icon: Users, title: "Admin", path: "/admin" }] + : baseItems + + return ( + + + + + +
+ + + + + + + ) +} + +export default AppSidebar diff --git a/skills/outpost/examples/fastapi-saas/frontend/src/components/Sidebar/Main.tsx b/skills/outpost/examples/fastapi-saas/frontend/src/components/Sidebar/Main.tsx new file mode 100644 index 0000000..0885cf4 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/frontend/src/components/Sidebar/Main.tsx @@ -0,0 +1,64 @@ +import { Link as RouterLink, useRouterState } from "@tanstack/react-router" +import type { LucideIcon } from "lucide-react" + +import { + SidebarGroup, + SidebarGroupContent, + SidebarMenu, + SidebarMenuButton, + SidebarMenuItem, + useSidebar, +} from "@/components/ui/sidebar" + +export type Item = { + icon: LucideIcon + title: string + path: string +} + +interface MainProps { + items: Item[] +} + +export function Main({ items }: MainProps) { + const { isMobile, setOpenMobile } = useSidebar() + const router = useRouterState() + const currentPath = router.location.pathname + + const handleMenuClick = () => { + if (isMobile) { + setOpenMobile(false) + } + } + + return ( + + + + {items.map((item) => { + const isActive = + item.path === "/destinations" + ? currentPath === "/destinations" || + currentPath.startsWith("/destinations/") + : currentPath === item.path + + return ( + + + + + {item.title} + + + + ) + })} + + + + ) +} diff --git a/skills/outpost/examples/fastapi-saas/frontend/src/components/Sidebar/User.tsx b/skills/outpost/examples/fastapi-saas/frontend/src/components/Sidebar/User.tsx new file mode 100644 index 0000000..12c6362 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/frontend/src/components/Sidebar/User.tsx @@ -0,0 +1,97 @@ +import { Link as RouterLink } from "@tanstack/react-router" +import { ChevronsUpDown, LogOut, Settings } from "lucide-react" + +import { Avatar, AvatarFallback } from "@/components/ui/avatar" +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuLabel, + DropdownMenuSeparator, + DropdownMenuTrigger, +} from "@/components/ui/dropdown-menu" +import { + SidebarMenu, + SidebarMenuButton, + SidebarMenuItem, + useSidebar, +} from "@/components/ui/sidebar" +import useAuth from "@/hooks/useAuth" +import { getInitials } from "@/utils" + +interface UserInfoProps { + fullName?: string + email?: string +} + +function UserInfo({ fullName, email }: UserInfoProps) { + return ( +
+ + + {getInitials(fullName || "User")} + + +
+

{fullName}

+

{email}

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

Change Password

+
+ + ( + + Current Password + + + + + + )} + /> + + ( + + New Password + + + + + + )} + /> + + ( + + Confirm Password + + + + + + )} + /> + + + Update Password + + + +
+ ) +} + +export default ChangePassword diff --git a/skills/outpost/examples/fastapi-saas/frontend/src/components/UserSettings/DeleteAccount.tsx b/skills/outpost/examples/fastapi-saas/frontend/src/components/UserSettings/DeleteAccount.tsx new file mode 100644 index 0000000..7b9e895 --- /dev/null +++ b/skills/outpost/examples/fastapi-saas/frontend/src/components/UserSettings/DeleteAccount.tsx @@ -0,0 +1,15 @@ +import DeleteConfirmation from "./DeleteConfirmation" + +const DeleteAccount = () => { + return ( +
+

Delete Account

+

+ Permanently delete your account and all associated data. +

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

User Information

+
+ + + editMode ? ( + + Full name + + + + + + ) : ( + + Full name +

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

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

{field.value}

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