Compare commits

..

389 Commits

Author SHA1 Message Date
Sebastián Ramírez 2eb8f5b624 🔖 Release version 0.8.0 2025-02-19 13:18:57 +01:00
github-actions 558b466d43 📝 Update release notes
[skip ci]
2025-02-19 12:00:29 +00:00
Alejandra 496c7090b3 ♻️ Redirect the user to login if we get 401/403 (#1501) 2025-02-19 12:00:08 +00:00
github-actions 50d2a3bfe1 📝 Update release notes
[skip ci]
2025-02-19 07:37:36 +00:00
Alejandra 1523c20cae 🐛 Refactor reset password test to create normal user instead of using super user (#1499) 2025-02-19 08:37:16 +01:00
github-actions f8e35a5249 📝 Update release notes
[skip ci]
2025-02-18 16:54:48 +00:00
Joel Pérez 9f6f8f088b ♻️ Replace email types from str to EmailStr in config.py (#1492) 2025-02-18 17:53:38 +01:00
github-actions ff5079079b 📝 Update release notes
[skip ci]
2025-02-18 15:03:12 +00:00
Alejandra 7b05fc1f6d 🔧 Remove unused context from router creation (#1498) 2025-02-18 15:02:50 +00:00
github-actions 86ef743226 📝 Update release notes
[skip ci]
2025-02-17 19:55:39 +00:00
Alejandra ed34e5e170 🔧 Configure path alias for cleaner imports (#1497) 2025-02-17 20:55:20 +01:00
github-actions 322975dd6e 📝 Update release notes
[skip ci]
2025-02-17 19:33:16 +00:00
Alejandra 55df823739 🛂 Migrate to Chakra UI v3 (#1496)
Co-authored-by: github-actions <github-actions@github.com>
2025-02-17 20:33:00 +01:00
github-actions 74e2604faf 📝 Update release notes
[skip ci]
2025-02-17 18:04:07 +00:00
Chris Handy 631980a876 📝 Removing deprecated manual client SDK step (#1494) 2025-02-17 18:03:49 +00:00
github-actions f178e58bfe 📝 Update release notes
[skip ci]
2025-02-10 19:26:55 +00:00
Christopher Markus aee08490e5 📝 Update Frontend README.md (#1462)
Fix incorrect script name which was generate-frontend-client.sh and now is generate-client.sh
2025-02-10 19:26:37 +00:00
github-actions 42fd54e06b 📝 Update release notes
[skip ci]
2025-02-10 19:26:00 +00:00
dependabot[bot] 16997dabf0 Bump vite from 5.0.13 to 5.4.14 in /frontend (#1469)
Bumps [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite) from 5.0.13 to 5.4.14.
- [Release notes](https://github.com/vitejs/vite/releases)
- [Changelog](https://github.com/vitejs/vite/blob/v5.4.14/packages/vite/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite/commits/v5.4.14/packages/vite)

---
updated-dependencies:
- dependency-name: vite
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-02-10 19:25:42 +00:00
github-actions 7cffa83649 📝 Update release notes
[skip ci]
2025-02-10 19:23:23 +00:00
Nauanbek 15f41f755b ♻️ Remove redundant item deletion code leveraging cascade delete (#1481) 2025-02-10 19:23:04 +00:00
github-actions f2eb1b5c5f 📝 Update release notes
[skip ci]
2025-02-10 15:14:40 +00:00
Robert (Jamie) Munro 6042eda4bc ✏️ Fix a couple of spelling mistakes (#1485) 2025-02-10 15:14:19 +00:00
github-actions ba1706b489 📝 Update release notes
[skip ci]
2025-01-06 11:33:15 +00:00
Boriss Jerjomkin c754a0058b 🧑‍🔧 Replace correct value for 'htmlFor' (#1456) 2025-01-06 11:32:57 +00:00
github-actions 2d553dda53 📝 Update release notes
[skip ci]
2025-01-05 14:58:03 +00:00
Alejandra 846dd9e81a ⬆️ Update Dockerfile to use uv version 0.5.11 (#1454) 2025-01-05 14:57:42 +00:00
github-actions d4df197c59 📝 Update release notes
[skip ci]
2024-12-21 11:01:03 +00:00
Ayoub Benaissa 87afb074a3 📝 Update frontend/README.md to also remove Playwright when removing Frontend (#1452) 2024-12-21 11:00:44 +00:00
github-actions 98a2d7ddcf 📝 Update release notes
[skip ci]
2024-12-21 10:59:48 +00:00
dependabot[bot] b95dea6d26 ⬆ Bump astral-sh/setup-uv from 4 to 5 (#1453)
Bumps [astral-sh/setup-uv](https://github.com/astral-sh/setup-uv) from 4 to 5.
- [Release notes](https://github.com/astral-sh/setup-uv/releases)
- [Commits](https://github.com/astral-sh/setup-uv/compare/v4...v5)

---
updated-dependencies:
- dependency-name: astral-sh/setup-uv
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-12-21 10:59:31 +00:00
github-actions 88c83cc06c 📝 Update release notes
[skip ci]
2024-12-10 09:59:57 +00:00
dependabot[bot] 3e6ed0157e ⬆ Bump astral-sh/setup-uv from 3 to 4 (#1433)
Bumps [astral-sh/setup-uv](https://github.com/astral-sh/setup-uv) from 3 to 4.
- [Release notes](https://github.com/astral-sh/setup-uv/releases)
- [Commits](https://github.com/astral-sh/setup-uv/compare/v3...v4)

---
updated-dependencies:
- dependency-name: astral-sh/setup-uv
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-12-10 09:59:36 +00:00
github-actions b0f6195827 📝 Update release notes
[skip ci]
2024-12-02 12:04:22 +00:00
Patrick Arminio 30832076f5 🎨 Move prefix and tags to routers (#1439) 2024-12-02 12:04:03 +00:00
github-actions aa71abedcc 📝 Update release notes
[skip ci]
2024-12-02 11:58:11 +00:00
Patrick Arminio 14129f7a50 ✨ Add private, local only, API for usage in E2E tests (#1429)
Co-authored-by: github-actions <github-actions@github.com>
2024-12-02 12:57:53 +01:00
github-actions 414864d848 📝 Update release notes
[skip ci]
2024-11-27 11:43:08 +00:00
Patrick Arminio 953e9e5416 ♻️ Remove modify id script in favor of openapi-ts config (#1434) 2024-11-27 12:42:44 +01:00
github-actions b7d2df2f81 📝 Update release notes
[skip ci]
2024-11-27 11:07:21 +00:00
Patrick Arminio a21c57ab2b ✨ Migrate to latest openapi-ts (#1430) 2024-11-27 12:06:59 +01:00
github-actions e34527325b 📝 Update release notes
[skip ci]
2024-11-08 22:02:26 +00:00
dependabot[bot] 19764d5307 ⬆ Bump tiangolo/latest-changes from 0.3.1 to 0.3.2 (#1418)
Bumps [tiangolo/latest-changes](https://github.com/tiangolo/latest-changes) from 0.3.1 to 0.3.2.
- [Release notes](https://github.com/tiangolo/latest-changes/releases)
- [Commits](https://github.com/tiangolo/latest-changes/compare/0.3.1...0.3.2)

---
updated-dependencies:
- dependency-name: tiangolo/latest-changes
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-11-08 22:02:06 +00:00
github-actions 3aad3fb877 📝 Update release notes 2024-11-01 15:29:47 +00:00
Sebastián Ramírez 61fa9431b7 📝 Update deployment.md, instructions to install GitHub Runner in non-root VMs (#1412) 2024-11-01 15:29:29 +00:00
github-actions 24c4f13629 📝 Update release notes 2024-10-25 21:56:53 +00:00
Sebastián Ramírez e684f3c8d6 👷 Improve Playwright CI speed: sharding (paralel runs), run in Docker to use cache, use env vars (#1405) 2024-10-25 21:56:34 +00:00
github-actions d3d370cad0 📝 Update release notes 2024-10-14 15:36:28 +00:00
Alejandra c23c91bd4e 👷 Update issue manager workflow (#1398) 2024-10-14 17:35:47 +02:00
github-actions 6768359244 📝 Update release notes 2024-10-12 13:55:29 +00:00
Sebastián Ramírez a2e3a8ae11 👷 Fix smokeshow, checkout files on CI (#1395) 2024-10-12 15:54:30 +02:00
github-actions f5612ed7cd 📝 Update release notes 2024-10-12 12:38:47 +00:00
Tobias 12a13b4108 📝 Add MailCatcher to development.md (#1387) 2024-10-12 14:38:29 +02:00
github-actions db7ea2cbbe 📝 Update release notes 2024-10-07 20:34:33 +00:00
Sebastián Ramírez 86d2fcc2e8 👷 Update labeler.yml (#1388) 2024-10-07 20:33:45 +00:00
github-actions 67e3f35491 📝 Update release notes 2024-10-03 18:35:51 +00:00
Justin Perdok 1c3e464acd 🔧 Add .auth playwright folder to .gitignore (#1383) 2024-10-03 20:35:15 +02:00
github-actions 372c9f8f91 📝 Update release notes 2024-10-03 18:33:05 +00:00
Saltie 8d52d018b4 ♻️ Add PaginationFooter component (#1381) 2024-10-03 20:32:46 +02:00
github-actions 88e1a607b0 📝 Update release notes 2024-09-30 13:39:42 +00:00
dependabot[bot] 6047623ad1 ⬆️ Bump rollup from 4.6.1 to 4.22.5 in /frontend (#1379)
Bumps [rollup](https://github.com/rollup/rollup) from 4.6.1 to 4.22.5.
- [Release notes](https://github.com/rollup/rollup/releases)
- [Changelog](https://github.com/rollup/rollup/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rollup/rollup/compare/v4.6.1...v4.22.5)

---
updated-dependencies:
- dependency-name: rollup
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-09-30 15:39:17 +02:00
github-actions 0a5f1025d6 📝 Update release notes 2024-09-27 16:42:55 +00:00
Muhammad Sameer Amin 172bfd9349 ♻️ Refactored code to use encryption algorithm name from settings for consistency (#1160)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2024-09-27 18:42:36 +02:00
github-actions 79883c879f 📝 Update release notes 2024-09-27 16:40:03 +00:00
github-actions 721a44ab2f 📝 Update release notes 2024-09-27 16:39:41 +00:00
Hmily ddb4235bfe 🔊 Enable logging for email utils by default (#1374)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2024-09-27 16:39:40 +00:00
dependabot[bot] 2939b7723b ⬆ Bump astral-sh/setup-uv from 2 to 3 (#1364)
Bumps [astral-sh/setup-uv](https://github.com/astral-sh/setup-uv) from 2 to 3.
- [Release notes](https://github.com/astral-sh/setup-uv/releases)
- [Commits](https://github.com/astral-sh/setup-uv/compare/v2...v3)

---
updated-dependencies:
- dependency-name: astral-sh/setup-uv
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-09-27 18:39:19 +02:00
github-actions 4d5b0a065c 📝 Update release notes 2024-09-27 16:30:27 +00:00
Chris 3793150fe4 👷 Update pre-commit end-of-file-fixer hook to exclude email-templates (#1296)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2024-09-27 16:30:09 +00:00
github-actions ab0d1bb12f 📝 Update release notes 2024-09-27 16:28:02 +00:00
dependabot[bot] 3136437bcb ⬆ Bump tiangolo/issue-manager from 0.5.0 to 0.5.1 (#1332)
Bumps [tiangolo/issue-manager](https://github.com/tiangolo/issue-manager) from 0.5.0 to 0.5.1.
- [Release notes](https://github.com/tiangolo/issue-manager/releases)
- [Commits](https://github.com/tiangolo/issue-manager/compare/0.5.0...0.5.1)

---
updated-dependencies:
- dependency-name: tiangolo/issue-manager
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-09-27 18:27:40 +02:00
github-actions b9ec1943eb 📝 Update release notes 2024-09-27 16:11:18 +00:00
Sebastián Ramírez fe7f4f7949 🔧 Add ENV PYTHONUNBUFFERED=1 to log output directly to Docker (#1378) 2024-09-27 16:10:59 +00:00
github-actions b67fb44e5b 📝 Update release notes 2024-09-27 16:00:15 +00:00
Waket Zheng 945fbc7699 🔧 Run task by the same Python environment used to run Copier (#1157)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2024-09-27 17:59:54 +02:00
github-actions 109a7454c7 📝 Update release notes 2024-09-27 15:53:52 +00:00
Sebastián Ramírez 38843cbe28 👷 Tweak generate client to error out if there are errors (#1377) 2024-09-27 15:53:31 +00:00
github-actions 1030118247 📝 Update release notes 2024-09-27 15:41:36 +00:00
Hani Sabsoob 08dd87d0f2 💡 Remove unnecessary comment (#1260)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2024-09-27 17:41:17 +02:00
github-actions 6a8fc240b3 📝 Update release notes 2024-09-27 14:23:43 +00:00
Sebastián Ramírez c297e9ee9e 👷 Generate and commit client only on same repo PRs, on forks, show the error (#1376) 2024-09-27 16:23:23 +02:00
Sebastián Ramírez 7e5ca88dc2 🔖 Release version 0.7.1 2024-09-27 15:30:04 +02:00
github-actions 451c656fb0 📝 Update release notes 2024-09-24 09:53:03 +00:00
Sebastián Ramírez 911223516c 👷 Use uv cache on GitHub Actions (#1366) 2024-09-24 11:52:42 +02:00
github-actions 1f666c4907 📝 Update release notes 2024-09-23 22:29:32 +00:00
Sebastián Ramírez 32227c4020 👷 Update GitHub Actions format (#1363) 2024-09-24 00:29:10 +02:00
github-actions cdc7b50fec 📝 Update release notes 2024-09-23 22:05:47 +00:00
Sebastián Ramírez 284527b7bc 👷 Use uv for Python env to generate client (#1362) 2024-09-24 00:05:29 +02:00
github-actions 6ed7aee371 📝 Update release notes 2024-09-23 21:27:39 +00:00
Sebastián Ramírez 39325ad421 👷 Run tests from Python environment (with uv), not from Docker container (#1361) 2024-09-23 23:27:21 +02:00
github-actions b3a77946cb 📝 Update release notes 2024-09-23 20:36:34 +00:00
Sebastián Ramírez 9b2e5813ae 🔨 Update generate-client.sh script, make it fail on errors, fix generation (#1360) 2024-09-23 22:36:14 +02:00
github-actions 55ad3b21ee 📝 Update release notes 2024-09-23 20:09:35 +00:00
Sebastián Ramírez d2020c1a37 ♻️ Update settings to use top level .env file (#1359) 2024-09-23 22:09:11 +02:00
github-actions 6fc03d1bf4 📝 Update release notes 2024-09-23 19:35:36 +00:00
Sebastián Ramírez 0435937f8e 👷 Add GitHub Actions workflow to lint backend apart from tests (#1358) 2024-09-23 21:35:18 +02:00
github-actions 8d9af8cb80 📝 Update release notes 2024-09-23 16:53:28 +00:00
Sebastián Ramírez 4fc9610175 💡 Add comments to Dockerfile with uv references (#1357) 2024-09-23 16:53:08 +00:00
github-actions 4b6fb7c465 📝 Update release notes 2024-09-23 14:11:09 +00:00
Sebastián Ramírez 81048277c7 ⬆️ Migrate from Poetry to uv (#1356) 2024-09-23 16:10:46 +02:00
github-actions fa97b372b4 📝 Update release notes 2024-09-23 11:40:12 +00:00
Sebastián Ramírez c8104d8ced 🔥 Remove logic for development dependencies and Jupyter, it was never documented, and I no longer use that trick (#1355) 2024-09-23 13:39:54 +02:00
github-actions 7ed8694643 📝 Update release notes 2024-09-22 22:29:44 +00:00
Sebastián Ramírez 4cd67f3483 ♻️ Use Docker Compose watch (#1354) 2024-09-23 00:29:23 +02:00
github-actions b262c2053c 📝 Update release notes 2024-09-22 16:25:47 +00:00
Sebastián Ramírez 651643982b 🔧 Use plain base official Python Docker image (#1351) 2024-09-22 18:25:29 +02:00
github-actions 224d0e31a8 📝 Update release notes 2024-09-22 16:20:17 +00:00
Sebastián Ramírez 87254dd79e 🚚 Move location of scripts to simplify file structure (#1352) 2024-09-22 18:19:57 +02:00
github-actions 68a7fe0899 📝 Update release notes 2024-09-20 15:13:01 +00:00
Sebastián Ramírez 8fe66c1cc1 ♻️ Refactor prestart (migrations), move that to its own container (#1350) 2024-09-20 17:12:40 +02:00
github-actions d87b6391b5 📝 Update release notes 2024-09-20 12:53:11 +00:00
Sebastián Ramírez 889a9bf5bf ⬆️ Upgrade FastAPI (#1349) 2024-09-20 14:52:45 +02:00
github-actions 44ff5730b7 📝 Update release notes 2024-09-20 12:43:51 +00:00
Sebastián Ramírez e64c9100ec ♻️ Include FRONTEND_HOST in CORS origins by default (#1348) 2024-09-20 14:43:32 +02:00
github-actions a292dbe10d 📝 Update release notes 2024-09-19 18:11:52 +00:00
Sebastián Ramírez 79d240f5b7 ♻️ Simplify domains with api.example.com for API and dashboard.example.com for frontend, improve local development with localhost (#1344) 2024-09-19 18:11:33 +00:00
github-actions 110a59c71d 📝 Update release notes 2024-09-16 22:26:45 +00:00
Sebastián Ramírez 2062b5b671 🔥 Simplify Traefik, remove www-redirects that add complexity (#1343) 2024-09-17 00:26:26 +02:00
github-actions 07b568b4f6 📝 Update release notes 2024-09-16 19:52:57 +00:00
Sebastián Ramírez 8a8a90459d 🩺 Add DB healthcheck (#1342) 2024-09-16 21:52:33 +02:00
github-actions eb88b52ff8 📝 Update release notes 2024-09-16 19:43:09 +00:00
Sebastián Ramírez 18a5cb21db 🔥 Enable support for Arm Docker images in Mac, remove old patch (#1341) 2024-09-16 21:42:50 +02:00
github-actions 46ac6a3c6f 📝 Update release notes 2024-09-12 13:21:44 +00:00
Patrick Arminio 97d04cd7ff 👷 Improve playwright CI job (#1335) 2024-09-12 15:21:24 +02:00
github-actions b3a49ae32e 📝 Update release notes 2024-09-07 15:20:44 +00:00
Sebastián Ramírez 4af652aa73 👷 Update issue-manager.yml (#1329) 2024-09-07 17:20:24 +02:00
github-actions ad3580703c 📝 Update release notes 2024-09-02 20:48:36 +00:00
Sofie Van Landeghem 2241d75131 set include-hidden-files to true for actions/upload-artifact@v4 (#1327) 2024-09-02 22:48:18 +02:00
github-actions 33b379bd46 📝 Update release notes 2024-08-29 18:11:08 +00:00
Alejandra bbad34aa8d 👷🏻 Auto-generate frontend client (#1320) 2024-08-29 20:10:49 +02:00
github-actions e8c73ff614 📝 Update release notes 2024-08-29 15:46:18 +00:00
Alejandra 644de7f186 🐛 Fix in .github/labeler.yml (#1322) 2024-08-29 17:46:02 +02:00
github-actions 90e3e337cb 📝 Update release notes 2024-08-29 15:38:45 +00:00
Alejandra 2fb7354923 👷 Update .github/labeler.yml (#1321) 2024-08-29 15:38:22 +00:00
github-actions 05bc1412b3 📝 Update release notes 2024-08-26 02:18:04 +00:00
Sebastián Ramírez 375170c386 👷 Update latest-changes GitHub Action (#1315) 2024-08-26 02:17:32 +00:00
github-actions 5005e5a5c1 📝 Update release notes 2024-08-17 18:59:41 +00:00
Alejandra 77040adf86 📝 Add Email Templates to backend/README.md (#1311) 2024-08-17 13:59:22 -05:00
github-actions 65c66f2050 📝 Update release notes 2024-08-15 20:43:14 +00:00
Sebastián Ramírez 8187a5283f 👷 Update configs for labeler (#1308) 2024-08-15 15:42:54 -05:00
github-actions 66c4ff169d 📝 Update release notes 2024-08-15 18:49:23 +00:00
Sebastián Ramírez d7d245a108 👷 Do not sync labels as it overrides manually added labels (#1307) 2024-08-15 13:48:43 -05:00
github-actions 6eff776fc1 📝 Update release notes 2024-08-14 19:12:46 +00:00
Sebastián Ramírez de57a7bac1 👷 Update GitHub Action labeler to add only one label (#1304) 2024-08-14 14:12:29 -05:00
github-actions 0f082d1265 📝 Update release notes 2024-08-14 14:57:14 +00:00
dependabot[bot] 5a138697ec ⬆️ Bump axios from 1.6.2 to 1.7.4 in /frontend (#1301)
Bumps [axios](https://github.com/axios/axios) from 1.6.2 to 1.7.4.
- [Release notes](https://github.com/axios/axios/releases)
- [Changelog](https://github.com/axios/axios/blob/v1.x/CHANGELOG.md)
- [Commits](https://github.com/axios/axios/compare/v1.6.2...v1.7.4)

---
updated-dependencies:
- dependency-name: axios
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Alejandra <90076947+alejsdev@users.noreply.github.com>
2024-08-14 09:56:53 -05:00
github-actions 79ed422871 📝 Update release notes 2024-08-14 03:58:27 +00:00
Sebastián Ramírez d275c6224b 👷 Update GitHub Action labeler dependencies (#1302) 2024-08-13 22:57:33 -05:00
github-actions 972714512b 📝 Update release notes 2024-08-13 22:34:48 +00:00
Sebastián Ramírez 4b9285643a 👷 Update GitHub Action labeler permissions (#1300) 2024-08-13 17:34:30 -05:00
github-actions cdf9a6548e 📝 Update release notes 2024-08-13 05:36:01 +00:00
Sebastián Ramírez 10c6cc72eb 👷 Add GitHub Action label-checker (#1299) 2024-08-13 05:35:21 +00:00
github-actions 7351d21fae 📝 Update release notes 2024-08-13 03:58:49 +00:00
jjaakko 974340c8ff ♻️ Remove duplicated information in the ItemCreate model (#1287) 2024-08-12 22:58:31 -05:00
github-actions 572f513458 📝 Update release notes 2024-08-13 02:45:00 +00:00
Sebastián Ramírez b4c34c63d6 👷 Add GitHub Action labeler (#1298) 2024-08-13 02:44:18 +00:00
github-actions ee82165ec7 📝 Update release notes 2024-08-13 02:11:43 +00:00
Sebastián Ramírez e46ba68301 👷 Add GitHub Action add-to-project (#1297) 2024-08-13 02:11:24 +00:00
github-actions 7a6107ff41 📝 Update release notes 2024-08-03 19:24:01 +00:00
Sebastián Ramírez df94e73a5a 👷 Update issue-manager (#1288) 2024-08-03 19:23:42 +00:00
Sebastián Ramírez af086764b3 🔖 Release version 0.7.0 2024-08-02 14:52:08 -05:00
github-actions a999734689 📝 Update release notes 2024-08-02 19:37:15 +00:00
Sebastián Ramírez 8ce3ce5903 📝 Update links from tiangolo repo to fastapi org repo (#1285) 2024-08-02 14:34:32 -05:00
github-actions 9ce8526605 📝 Update release notes 2024-08-02 19:05:10 +00:00
Alejandra 14c09b937d 🔧 Update deploy workflows to exclude the main repository (#1284) 2024-08-02 14:04:54 -05:00
github-actions bb5732dcbc 📝 Update release notes 2024-08-02 15:47:23 +00:00
Elijah Rippeth 2b2eefc121 🚨 Fix Docker build warning (#1283) 2024-08-02 10:47:06 -05:00
github-actions 1b5dd13044 📝 Update release notes 2024-08-01 18:48:17 +00:00
Abdul 36767344aa ♻️ Regenerate client to use UUID instead of id integers and update frontend (#1281) 2024-08-01 13:48:00 -05:00
github-actions 19049f2a74 📝 Update release notes 2024-08-01 18:01:21 +00:00
Alejandra b905768656 ♻️ Tweaks in frontend (#1273) 2024-08-01 18:01:03 +00:00
github-actions 93e83c1ad4 📝 Update release notes 2024-08-01 16:51:14 +00:00
Alejandra 9e0146c64c 📝 Add End-to-End Testing with Playwright to frontend README.md (#1279)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2024-08-01 16:50:55 +00:00
github-actions d9a21d3b49 📝 Update release notes 2024-08-01 16:45:25 +00:00
Alejandra ed61369c2b ♻️ Add random password util and refactor tests (#1277) 2024-08-01 11:45:05 -05:00
github-actions 17e4fb9141 📝 Update release notes 2024-08-01 16:44:17 +00:00
Alejandra 269040d670 ♻️ Refactor models to use cascade delete relationships (#1276) 2024-08-01 11:44:00 -05:00
github-actions d4ae12cd9a 📝 Update release notes 2024-08-01 02:00:15 +00:00
Sebastián Ramírez 5d21a267fc 👷 Update issue-manager.yml GitHub Action permissions (#1278) 2024-08-01 01:59:45 +00:00
github-actions 11e165fa71 📝 Update release notes 2024-07-31 22:14:21 +00:00
Alejandra 684256adbe ⬆️ Update SQLModel to version >=0.0.21 (#1275) 2024-07-31 22:14:04 +00:00
github-actions 6606bfcb53 📝 Update release notes 2024-07-31 22:08:46 +00:00
Alejandra 1f686689f1 🔥 Remove USERS_OPEN_REGISTRATION config, make registration enabled by default (#1274) 2024-07-31 17:08:26 -05:00
github-actions 7bba5a85f0 📝 Update release notes 2024-07-30 17:48:55 +00:00
Alejandra 8efef66c5c ✨ Add User Settings e2e tests (#1271) 2024-07-30 12:48:36 -05:00
github-actions c8b1b3a9b1 📝 Update release notes 2024-07-30 17:47:00 +00:00
Patrick Arminio b5b2929104 🔧 Reuse database url from config in alembic setup (#1229) 2024-07-30 12:46:41 -05:00
github-actions b15d482605 📝 Update release notes 2024-07-30 14:10:16 +00:00
Alejandra 1e9e561e5f ✨ Add Reset Password e2e tests (#1270) 2024-07-30 09:09:57 -05:00
github-actions 68b86b157f 📝 Update release notes 2024-07-29 17:54:02 +00:00
Alejandra 8f7004821a ✨ Add Sign Up e2e tests (#1268) 2024-07-29 12:53:43 -05:00
github-actions 41999a694f 📝 Update release notes 2024-07-23 19:59:57 +00:00
Alejandra 06a2ec8a2b 🔧 Update Playwright config and tests to use env variables (#1266) 2024-07-23 14:59:39 -05:00
github-actions aff2146d7e 📝 Update release notes 2024-07-23 00:41:16 +00:00
Alejandra c147a95563 ✨ Add Sign Up and make OPEN_USER_REGISTRATION=True by default (#1265) 2024-07-22 19:40:56 -05:00
github-actions 7a9920ac7b 📝 Update release notes 2024-07-22 23:04:45 +00:00
Alejandra a6fbe9df64 ✨ Add Login e2e tests (#1264)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2024-07-22 23:04:29 +00:00
github-actions 3c38ad1188 📝 Update release notes 2024-07-22 23:00:20 +00:00
Alejandra 000580d0ac ✨ Add initial setup for frontend / end-to-end tests with Playwright (#1261)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2024-07-22 23:00:02 +00:00
github-actions ddd4b1dbfd 📝 Update release notes 2024-07-22 22:49:22 +00:00
Esteban Maya e65b427ab1 ♻️ Edit refactor db models to use UUID's instead of integer ID's (#1259)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2024-07-22 22:49:02 +00:00
github-actions cc480df776 📝 Update release notes 2024-07-22 01:24:51 +00:00
Alejandra e15831c930 ♻️ Update form inputs width (#1263) 2024-07-22 01:24:32 +00:00
github-actions b79c7c8e99 📝 Update release notes 2024-07-22 00:57:06 +00:00
dependabot[bot] c6457cb8e1 ⬆️ Bump setuptools from 69.1.1 to 70.0.0 in /backend (#1255)
Bumps [setuptools](https://github.com/pypa/setuptools) from 69.1.1 to 70.0.0.
- [Release notes](https://github.com/pypa/setuptools/releases)
- [Changelog](https://github.com/pypa/setuptools/blob/main/NEWS.rst)
- [Commits](https://github.com/pypa/setuptools/compare/v69.1.1...v70.0.0)

---
updated-dependencies:
- dependency-name: setuptools
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-07-21 19:56:48 -05:00
github-actions ded08f6d97 📝 Update release notes 2024-07-22 00:56:37 +00:00
dependabot[bot] e31537c430 ⬆️ Bump certifi from 2024.2.2 to 2024.7.4 in /backend (#1250)
Bumps [certifi](https://github.com/certifi/python-certifi) from 2024.2.2 to 2024.7.4.
- [Commits](https://github.com/certifi/python-certifi/compare/2024.02.02...2024.07.04)

---
updated-dependencies:
- dependency-name: certifi
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-07-21 19:56:19 -05:00
github-actions 5d6a109cf2 📝 Update release notes 2024-07-22 00:56:04 +00:00
dependabot[bot] 53849188fe ⬆️ Bump urllib3 from 2.2.1 to 2.2.2 in /backend (#1235)
Bumps [urllib3](https://github.com/urllib3/urllib3) from 2.2.1 to 2.2.2.
- [Release notes](https://github.com/urllib3/urllib3/releases)
- [Changelog](https://github.com/urllib3/urllib3/blob/main/CHANGES.rst)
- [Commits](https://github.com/urllib3/urllib3/compare/2.2.1...2.2.2)

---
updated-dependencies:
- dependency-name: urllib3
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-07-21 19:55:45 -05:00
github-actions d8219050e1 📝 Update release notes 2024-07-22 00:36:26 +00:00
Javier Álvarez 6e1c888af3 ♻️ Replace deprecated utcnow() with now(timezone.utc) in utils module (#1247) 2024-07-21 19:36:05 -05:00
github-actions 68ef020782 📝 Update release notes 2024-07-22 00:34:10 +00:00
Alejandra 2ed7a0887c 🎨 Format frontend (#1262) 2024-07-22 00:33:50 +00:00
github-actions a38afb4676 📝 Update release notes 2024-07-18 20:27:56 +00:00
António Loureiro c38581ce26 ♻️ Abstraction of specific AddModal component out of the Navbar (#1246) 2024-07-18 15:27:39 -05:00
github-actions 8faf5c9fc9 📝 Update release notes 2024-07-18 20:25:18 +00:00
jmondaud 8ba2459b75 ♻️ Update login.tsx to prevent error if username or password are empty (#1257) 2024-07-18 15:24:51 -05:00
github-actions 763afde09b 📝 Update release notes 2024-06-30 01:05:43 +00:00
Patrick Arminio 8b8f0698e3 ✨ Add mailcatcher configuration (#1244) 2024-06-29 20:05:25 -05:00
github-actions 91c35331e4 📝 Update release notes 2024-06-28 14:22:56 +00:00
Alejandra 3865627301 ♻️ Refactor recover password (#1242) 2024-06-28 09:22:32 -05:00
github-actions 92a3480a60 📝 Update release notes 2024-06-27 21:39:05 +00:00
Alejandra a578dffcae 🎨 Format and lint (#1243) 2024-06-27 16:38:45 -05:00
github-actions 7a4f98c445 📝 Update release notes 2024-06-27 19:54:08 +00:00
Tomer Barletz 960a38aeb6 🎨 Run biome after OpenAPI client generation (#1226) 2024-06-27 14:53:51 -05:00
github-actions dabeff7801 📝 Update release notes 2024-06-27 19:50:16 +00:00
Patrick Arminio dda7934ed8 ✨ Introduce pagination in items (#1239) 2024-06-27 14:49:54 -05:00
github-actions db7d06b0f8 📝 Update release notes 2024-06-26 02:27:23 +00:00
Sebastián Ramírez dbf3899b7c ⬆️ Upgrade Traefik (#1241) 2024-06-26 02:27:06 +00:00
github-actions e20c35d76d 📝 Update release notes 2024-06-19 00:21:02 +00:00
Esteban Maya d421c90af2 🗃️ Add max_length validation for database models and input data (#1233) 2024-06-18 19:20:39 -05:00
github-actions df66c1d2ce 📝 Update release notes 2024-06-05 17:26:09 +00:00
Alejandra ef76179f9f ♻️ Update DeleteConfirmation component to use new service (#1224) 2024-06-05 17:25:47 +00:00
github-actions 0b16db4fe0 📝 Update release notes 2024-06-05 15:40:06 +00:00
Alejandra 2f0a682bfe ♻️ Update client services (#1223) 2024-06-05 10:39:46 -05:00
github-actions 90aa3dc274 📝 Update release notes 2024-06-01 22:44:23 +00:00
Alejandra 649a7dae4c 📝 Update release-notes.md (#1220) 2024-06-01 22:44:03 +00:00
github-actions e66aa0ea55 📝 Update release notes 2024-06-01 22:35:02 +00:00
Tomer Barletz 1bf057bd19 ✨ Add TanStack React Query devtools in dev build (#1217) 2024-06-01 22:34:41 +00:00
github-actions 9ad8f57cfd 📝 Update release notes 2024-06-01 22:31:20 +00:00
Tomer Barletz 0eb5e18d85 🐛 Fix welcome page to show logged-in user (#1218) 2024-06-01 17:31:03 -05:00
github-actions bd8b50308c 📝 Update release notes 2024-05-23 21:06:13 +00:00
dependabot[bot] df51c2ee6d ⬆️ Bump requests from 2.31.0 to 2.32.0 in /backend (#1211)
updated-dependencies:
- dependency-name: requests
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-05-23 14:05:55 -07:00
github-actions bf0459468f 📝 Update release notes 2024-05-20 18:30:38 +00:00
Alejandra 47548490bb ⚒️ Add minor frontend tweaks (#1210) 2024-05-20 11:30:18 -07:00
github-actions 7f7c08e22b 📝 Update release notes 2024-05-20 18:15:45 +00:00
Alejandra 44ed5b1783 🚚 Move assets to public folder (#1206) 2024-05-20 11:15:23 -07:00
github-actions eaa443736d 📝 Update release notes 2024-05-19 19:47:17 +00:00
Sebastián Ramírez 9c8c9c60e4 ♻️ Refactor redirect labels to simplify removing the frontend (#1208) 2024-05-19 12:46:58 -07:00
github-actions c80191445a 📝 Update release notes 2024-05-16 18:57:58 +00:00
Craz1k0ek a1dee4dd5d ✏️ Update README.md (#1205) 2024-05-16 18:57:38 +00:00
github-actions 6b3930fd6b 📝 Update release notes 2024-05-15 15:49:17 +00:00
Esteban Maya ef1f64b8f5 🔒️ Refactor migrate from python-jose to PyJWT (#1203) 2024-05-15 08:48:57 -07:00
github-actions 13f4e844d3 📝 Update release notes 2024-05-14 22:43:23 +00:00
dependabot[bot] a7202bf3ea ⬆️ Bump jinja2 from 3.1.3 to 3.1.4 in /backend (#1196)
Bumps [jinja2](https://github.com/pallets/jinja) from 3.1.3 to 3.1.4.
- [Release notes](https://github.com/pallets/jinja/releases)
- [Changelog](https://github.com/pallets/jinja/blob/main/CHANGES.rst)
- [Commits](https://github.com/pallets/jinja/compare/3.1.3...3.1.4)

---
updated-dependencies:
- dependency-name: jinja2
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-05-14 15:43:04 -07:00
github-actions 9057631fc0 📝 Update release notes 2024-05-10 18:22:14 +00:00
Sebastián Ramírez f9a1ac7b1c 👷 Update Smokeshow download artifact GitHub Action (#1198) 2024-05-10 18:21:52 +00:00
github-actions a7f4d7dd61 📝 Update release notes 2024-05-04 03:53:14 +00:00
Philipp Wurzer d0654b0896 ✏️ Fix Adminer URL in deployment.md (#1194) 2024-05-03 22:52:56 -05:00
github-actions 1197f2bac0 📝 Update release notes 2024-05-03 22:30:12 +00:00
Alejandra 8f6e8c9ee4 🔧 Update Node.js version in .nvmrc (#1192) 2024-05-03 15:29:52 -07:00
github-actions f0e85714be 📝 Update release notes 2024-05-03 22:29:24 +00:00
Alejandra 88a5c6448a 📝 Add Enabling Open User Registration to backend docs (#1191) 2024-05-03 15:29:03 -07:00
github-actions d86e68f211 📝 Update release notes 2024-04-28 00:23:33 +00:00
dependabot[bot] 91062a1f8d Bump gunicorn from 21.2.0 to 22.0.0 in /backend (#1176)
Bumps [gunicorn](https://github.com/benoitc/gunicorn) from 21.2.0 to 22.0.0.
- [Release notes](https://github.com/benoitc/gunicorn/releases)
- [Commits](https://github.com/benoitc/gunicorn/compare/21.2.0...22.0.0)

---
updated-dependencies:
- dependency-name: gunicorn
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-04-27 19:23:14 -05:00
github-actions a2626b2391 📝 Update release notes 2024-04-28 00:22:21 +00:00
dependabot[bot] d31245d53a Bump idna from 3.6 to 3.7 in /backend (#1168)
Bumps [idna](https://github.com/kjd/idna) from 3.6 to 3.7.
- [Release notes](https://github.com/kjd/idna/releases)
- [Changelog](https://github.com/kjd/idna/blob/master/HISTORY.rst)
- [Commits](https://github.com/kjd/idna/compare/v3.6...v3.7)

---
updated-dependencies:
- dependency-name: idna
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-04-27 19:22:03 -05:00
github-actions 72cd3c97f3 📝 Update release notes 2024-04-26 22:56:21 +00:00
Alejandra f11bec6aa6 🔥 Remove duplicated code (#1185) 2024-04-26 15:55:59 -07:00
github-actions cd462c0a84 📝 Update release notes 2024-04-26 20:47:19 +00:00
Joel Gotsch 84ef657406 🐛 Fix local Traefik proxy network config to fix Gateway Timeouts (#1184) 2024-04-26 13:47:00 -07:00
github-actions 8882dc53e8 📝 Update release notes 2024-04-26 19:35:30 +00:00
Alejandra b81cec8ea5 ♻️ Add delete_user_me endpoint and corresponding test cases (#1179)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2024-04-26 12:35:12 -07:00
github-actions d1cc75903e 📝 Update release notes 2024-04-23 02:19:03 +00:00
Esteban Maya 933419e79c ✅ Update test to add verification database records (#1178) 2024-04-22 22:18:41 -04:00
github-actions 897ee1481b 📝 Update release notes 2024-04-16 14:57:19 +00:00
Patrick Arminio 472e0f254b 🚸 Use useSuspenseQuery to fetch members and show skeleton (#1174) 2024-04-16 09:56:59 -05:00
github-actions fb361b1bf6 📝 Update release notes 2024-04-16 14:56:30 +00:00
Patrick Arminio 79a7182816 🔧 Ignore src/routeTree.gen.ts in biome (#1175) 2024-04-16 09:56:11 -05:00
github-actions 6509aaa8ff 📝 Update release notes 2024-04-15 21:35:10 +00:00
Alejandra 314da98a45 🎨 Format Utils (#1173) 2024-04-15 21:34:50 +00:00
github-actions 6e0674236b 📝 Update release notes 2024-04-15 21:28:46 +00:00
Bill Zhong 3bd0d98f51 ♻️ Fix tests when first superuser password is changed in .env (#1165)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2024-04-15 21:28:29 +00:00
github-actions 7ca1a3f045 📝 Update release notes 2024-04-15 21:20:01 +00:00
Alejandra 78a8a3b4c4 🐛 Fix bug when resetting password (#1171) 2024-04-15 21:19:40 +00:00
github-actions e53dc1702b 📝 Update release notes 2024-04-15 20:03:58 +00:00
Patrick Arminio c31a12c0fb ✨ Use suspense for items page (#1167) 2024-04-15 15:03:39 -05:00
github-actions cc10bf6e31 📝 Update release notes 2024-04-12 15:50:36 +00:00
Patrick Arminio 615170dc34 🚸 Mark login field as required (#1166) 2024-04-12 10:50:14 -05:00
github-actions c947cb09e1 📝 Update release notes 2024-04-09 15:19:34 +00:00
Alejandra 88505aa683 📝 Update release-notes.md (#1164) 2024-04-09 15:19:12 +00:00
github-actions 71efd68518 📝 Update release notes 2024-04-09 14:12:38 +00:00
Patrick Arminio 9523db2f53 🚸 Improve login (#1163) 2024-04-09 09:12:19 -05:00
github-actions 1e9cb5ec28 📝 Update release notes 2024-04-09 14:11:28 +00:00
Patrick Arminio d0fbd0e925 🥅 Handle AxiosErrors in Login page (#1162) 2024-04-09 09:11:09 -05:00
github-actions b8aef74702 📝 Update release notes 2024-04-08 20:49:54 +00:00
Alejandra ccd85b098b 🎨 Format frontend (#1161) 2024-04-08 15:49:22 -05:00
github-actions 98bd7e6350 📝 Update release notes 2024-04-06 23:26:34 +00:00
Alejandra b92de6eb4f ♻️ Regenerate frontend client (#1156) 2024-04-06 18:26:12 -05:00
github-actions e5670212ea 📝 Update release notes 2024-04-06 21:54:05 +00:00
Esteban Maya ad72c4d3fd ♻️ Refactor rename ModelsOut to ModelsPublic (#1154)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2024-04-06 21:53:49 +00:00
github-actions 1105ea4c5c 📝 Update release notes 2024-04-05 20:15:55 +00:00
Sebastián Ramírez 8a008f0bc8 🔧 Update mypy config to ignore .venv directories (#1155) 2024-04-05 20:15:34 +00:00
github-actions 2c6d4a0e57 📝 Update release notes 2024-04-05 20:05:45 +00:00
Patrick Arminio dcebccadba 🚨 Enable ARG001 to prevent unused arguments (#1152) 2024-04-05 15:05:28 -05:00
github-actions e3a023da1e 📝 Update release notes 2024-04-05 20:00:03 +00:00
Patrick Arminio e9b2f9f480 🔥 Remove isort configuration, since we use Ruff now (#1144)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2024-04-05 14:59:40 -05:00
github-actions 1538530349 📝 Update release notes 2024-04-04 14:31:02 +00:00
Patrick Arminio 2314dbd2df 🆙 Update React Query to TanStack Query (#1153) 2024-04-04 09:30:42 -05:00
github-actions 3628e039f8 📝 Update release notes 2024-04-03 21:40:51 +00:00
Alejandra 529a475c8d ♻️ Migrate frontend client generation from openapi-typescript-codegen to @hey-api/openapi-ts (#1151) 2024-04-03 16:40:33 -05:00
github-actions 7d7b31823f 📝 Update release notes 2024-04-03 21:08:51 +00:00
Alejandra 78b68e1ab9 🔧 Update pre-commit config to exclude generated client folder (#1150) 2024-04-03 21:08:33 +00:00
github-actions e97f7bfd95 📝 Update release notes 2024-04-03 20:08:08 +00:00
dependabot[bot] 6e6b230dfc Bump vite from 5.0.12 to 5.0.13 in /frontend (#1149)
Bumps [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite) from 5.0.12 to 5.0.13.
- [Release notes](https://github.com/vitejs/vite/releases)
- [Changelog](https://github.com/vitejs/vite/blob/v5.0.13/packages/vite/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite/commits/v5.0.13/packages/vite)

---
updated-dependencies:
- dependency-name: vite
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-04-03 15:07:51 -05:00
github-actions 601f46f6d6 📝 Update release notes 2024-04-03 14:41:50 +00:00
Patrick Arminio 822dbc52b5 🔧 Change .nvmrc format (#1148) 2024-04-03 09:41:28 -05:00
github-actions 28fa02eeb5 📝 Update release notes 2024-04-03 03:58:10 +00:00
Alejandra 73666b0556 🔥 Remove unused exports and update dependencies (#1146) 2024-04-02 22:57:53 -05:00
github-actions b117d30675 📝 Update release notes 2024-04-03 03:29:50 +00:00
Esteban Maya fa9541fb0d 🔧 Update sentry dns initialization following the environment settings (#1145) 2024-04-02 22:29:32 -05:00
github-actions ba3826e6ce 📝 Update release notes 2024-04-02 03:53:49 +00:00
Alejandra 4239d93ea6 ♻️ Refactor and tweaks, rename UserCreateOpen to UserRegister and others (#1143) 2024-04-01 22:53:33 -05:00
github-actions aed4db7521 📝 Update release notes 2024-03-29 02:15:31 +00:00
Alejandra 33fe25e332 🎨 Format imports (#1140) 2024-03-29 02:15:11 +00:00
github-actions cbd464cce5 📝 Update release notes 2024-03-29 01:22:47 +00:00
Alejandra 6874db48b0 ♻️ Refactor and remove React.FC (#1139) 2024-03-29 01:22:28 +00:00
github-actions 802eeeadc9 📝 Update release notes 2024-03-29 00:49:21 +00:00
Alejandra 84bc7e2ca8 ♻️ Add email pattern and refactor in frontend (#1138) 2024-03-28 19:49:02 -05:00
github-actions c8e57bb760 📝 Update release notes 2024-03-28 23:04:39 +00:00
Esteban Maya c8b3ccce39 🥅 Set up Sentry for FastAPI applications (#1136)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2024-03-28 23:04:20 +00:00
github-actions 31f604264f 📝 Update release notes 2024-03-27 02:35:30 +00:00
Esteban Maya 2b0701e870 🎨 Ignore alembic from ruff lint and format (#1131) 2024-03-27 02:35:14 +00:00
github-actions 6cd3156672 📝 Update release notes 2024-03-25 21:57:05 +00:00
Sebastián Ramírez 1e20627934 🔥 Remove deprecated Docker Compose version key (#1129) 2024-03-25 21:56:49 +00:00
github-actions 73f6db9488 📝 Update release notes 2024-03-25 21:55:41 +00:00
Sebastián Ramírez f03db728e7 ✨ Add support for deploying multiple environments (staging, production) to the same server (#1128) 2024-03-25 21:55:24 +00:00
github-actions 4c8837c2a6 📝 Update release notes 2024-03-25 21:05:59 +00:00
Sebastián Ramírez c05bfc8ddc 📝 Update instructions to clone for a private repo, including updates (#1127) 2024-03-25 21:05:40 +00:00
github-actions 27a6c58fec 📝 Update release notes 2024-03-25 20:41:23 +00:00
Sebastián Ramírez e7975da967 📝 Add docs about CI keys, LATEST_CHANGES and SMOKESHOW_AUTH_KEY (#1126) 2024-03-25 20:41:06 +00:00
github-actions 90252c9804 📝 Update release notes 2024-03-25 20:34:21 +00:00
Sebastián Ramírez 78777ff011 👷 Update CI GitHub Actions to allow running in private repos (#1125) 2024-03-25 20:34:05 +00:00
github-actions 2e30c948cb 📝 Update release notes 2024-03-22 14:21:53 +00:00
Leon Lowitzki ac25e154ad ✏️ Fix file path in backend/README.md when not wanting to use migrations #1116 2024-03-22 09:21:32 -05:00
github-actions f442b8df52 📝 Update release notes 2024-03-21 20:52:14 +00:00
Esteban Maya 4f52d86d97 📝 Add documentation for pre-commit and code linting (#718)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2024-03-21 20:51:54 +00:00
github-actions b6f37e4fb7 📝 Update release notes 2024-03-18 17:39:05 +00:00
Alejandra 6b79f8c919 🔧 Add GitHub templates for discussions and issues, and security policy (#1105) 2024-03-18 17:38:44 +00:00
github-actions 0f2805a82d 📝 Update release notes 2024-03-18 14:36:38 +00:00
dependabot[bot] 2c572d3af0 ⬆ Bump dawidd6/action-download-artifact from 3.1.2 to 3.1.4 (#1103)
Bumps [dawidd6/action-download-artifact](https://github.com/dawidd6/action-download-artifact) from 3.1.2 to 3.1.4.
- [Release notes](https://github.com/dawidd6/action-download-artifact/releases)
- [Commits](https://github.com/dawidd6/action-download-artifact/compare/v3.1.2...v3.1.4)

---
updated-dependencies:
- dependency-name: dawidd6/action-download-artifact
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-03-18 15:36:15 +01:00
github-actions 6761293df6 📝 Update release notes 2024-03-17 18:50:25 +00:00
Alejandra 80083299eb 🔧 Add Biome to pre-commit config (#1098) 2024-03-17 18:50:06 +00:00
github-actions 7eafadd552 📝 Update release notes 2024-03-17 18:49:20 +00:00
efonte 7770b3d1b3 📝 Fix localhost URLs in development.md (#1099) 2024-03-17 19:49:00 +01:00
github-actions 569f64cbeb 📝 Update release notes 2024-03-17 16:40:28 +00:00
dependabot[bot] fa6e97e0a2 Bump follow-redirects from 1.15.5 to 1.15.6 in /frontend (#734)
Bumps [follow-redirects](https://github.com/follow-redirects/follow-redirects) from 1.15.5 to 1.15.6.
- [Release notes](https://github.com/follow-redirects/follow-redirects/releases)
- [Commits](https://github.com/follow-redirects/follow-redirects/compare/v1.15.5...v1.15.6)

---
updated-dependencies:
- dependency-name: follow-redirects
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-03-17 17:40:12 +01:00
github-actions c2220b8e68 📝 Update release notes 2024-03-17 16:29:03 +00:00
Alejandra 94a2037f8a 🎨 Format with Biome (#1097) 2024-03-17 16:28:45 +00:00
github-actions d4ee4db2f0 📝 Update release notes 2024-03-17 16:23:56 +00:00
Alejandra 4fbbdf4e94 🔥 Remove ESLint and Prettier from pre-commit config (#1096) 2024-03-17 16:23:36 +00:00
github-actions 6e7b8fd1df 📝 Update release notes 2024-03-17 16:13:41 +00:00
Alejandra 7856fd811b 🎨 Update quote style in biome formatter (#1095) 2024-03-17 16:13:25 +00:00
github-actions 477c5abf14 📝 Update release notes 2024-03-17 16:06:09 +00:00
Santiago Gandolfo 43435d50dd ♻️ Replace ESLint and Prettier with Biome to format and lint frontend (#719)
Co-authored-by: User <alejsdev@gmail.com>
Co-authored-by: Alejandra <90076947+alejsdev@users.noreply.github.com>
2024-03-17 16:05:47 +00:00
github-actions 75fc26192c 📝 Update release notes 2024-03-17 13:43:50 +00:00
Sebastián Ramírez 6aa2296dea 🐛 Fix 403 when the frontend has a directory without an index.html (#1094) 2024-03-17 13:43:31 +00:00
github-actions fa7d42eddd 📝 Update release notes 2024-03-16 13:02:54 +00:00
Δ̷̨̧̡̭̺̙̞͖̖͕̰̥̙̯͙̞̯̗̔͌͐̿͊̌́̄̑̿̓̉̈̀͘͠λ̶͔͓̘̘̳͇̻̍̏͌̅̓̓͂̍̾̔͜λ̶̛̯̖̯̲̱͎̙͎̎̐͆͂̽̓̇́͌́̀̏̎̅͋̏̊͘λ̶̨̨̰̟̯̫̲̲̫̯̭̤̳̼̫͉̹̞́̐̒Δ̷̡̛̥̖͇͚͍͍̄̏̂͛̅̌͗̂̽̅̀͆̿̔̚͜ a32cb74edd 🔥 Delete leftover celery file (#727) 2024-03-16 14:02:34 +01:00
github-actions 18ea605849 📝 Update release notes 2024-03-15 00:05:45 +00:00
Alejandra a2a1900105 🎨 Replace buttons styling for variants for consistency (#722) 2024-03-15 01:05:28 +01:00
github-actions 3fbdf21a05 📝 Update release notes 2024-03-14 11:27:23 +00:00
Alejandra f5764acd56 🛠️ Improve modify-openapi-operationids.js (#720) 2024-03-14 12:27:03 +01:00
github-actions 557b44f0e8 📝 Update release notes 2024-03-13 23:57:40 +00:00
Esteban Maya 85b7d6bc63 ♻️ Replace pytest-mock with unittest.mock and remove pytest-cov (#717) 2024-03-14 00:57:19 +01:00
github-actions a7deb9b39c 📝 Update release notes 2024-03-13 22:09:39 +00:00
Alejandra 85c1b06400 📝 Update README.md (#716) 2024-03-13 23:09:21 +01:00
github-actions 4fda65bec3 📝 Update release notes 2024-03-13 21:59:47 +00:00
Alejandra 21232c0f9f 🛠️ Minor changes in frontend (#715) 2024-03-13 21:59:28 +00:00
github-actions 10ef99cb68 📝 Update release notes 2024-03-13 20:44:12 +00:00
Alejandra b08aec7d98 ⚙️ Update pre-commit config with Prettier and ESLint (#714) 2024-03-13 21:43:54 +01:00
github-actions 2e96f05138 📝 Update release notes 2024-03-13 18:07:58 +00:00
Dudi Levy bbddf944e2 ♻ Update Docker image to prevent errors in M1 Macs (#710) 2024-03-13 19:07:40 +01:00
github-actions 80e6c81977 📝 Update release notes 2024-03-13 18:06:48 +00:00
Salomon Popp e13d120fd1 ✏ Fix typo in variable names in backend/app/api/routes/items.py and backend/app/api/routes/users.py (#711)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2024-03-13 18:06:22 +00:00
github-actions afc55bdf91 📝 Update release notes 2024-03-13 17:55:54 +00:00
emmanuel 24662000e7 ✏ Update header titles for consistency (#708) 2024-03-13 18:55:33 +01:00
github-actions 63e54cb9a5 📝 Update release notes 2024-03-13 11:55:17 +00:00
Alejandra ba042eca1f 📝 Update README.md, dark mode screenshot position (#706) 2024-03-13 12:54:57 +01:00
205 changed files with 13272 additions and 11985 deletions
+8 -1
View File
@@ -1,6 +1,14 @@
# Domain # Domain
# This would be set to the production domain with an env var on deployment # This would be set to the production domain with an env var on deployment
# used by Traefik to transmit traffic and aqcuire TLS certificates
DOMAIN=localhost DOMAIN=localhost
# To test the local Traefik config
# DOMAIN=localhost.tiangolo.com
# Used by the backend to generate links in emails to the frontend
FRONTEND_HOST=http://localhost:5173
# In staging and production, set this env var to the frontend host, e.g.
# FRONTEND_HOST=https://dashboard.example.com
# Environment: local, staging, production # Environment: local, staging, production
ENVIRONMENT=local ENVIRONMENT=local
@@ -13,7 +21,6 @@ BACKEND_CORS_ORIGINS="http://localhost,http://localhost:5173,https://localhost,h
SECRET_KEY=changethis SECRET_KEY=changethis
FIRST_SUPERUSER=admin@example.com FIRST_SUPERUSER=admin@example.com
FIRST_SUPERUSER_PASSWORD=changethis FIRST_SUPERUSER_PASSWORD=changethis
USERS_OPEN_REGISTRATION=False
# Emails # Emails
SMTP_HOST= SMTP_HOST=
+118
View File
@@ -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.
+10
View File
@@ -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
+22
View File
@@ -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.
+6 -6
View File
@@ -1,16 +1,16 @@
version: 2 version: 2
updates: updates:
# GitHub Actions # GitHub Actions
- package-ecosystem: "github-actions" - package-ecosystem: github-actions
directory: "/" directory: /
schedule: schedule:
interval: "daily" interval: daily
commit-message: commit-message:
prefix: ⬆ prefix: ⬆
# Python # Python
- package-ecosystem: "pip" - package-ecosystem: pip
directory: "/" directory: /
schedule: schedule:
interval: "daily" interval: daily
commit-message: commit-message:
prefix: ⬆ prefix: ⬆
+25
View File
@@ -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/**'
+18
View File
@@ -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 }}
+5 -2
View File
@@ -7,12 +7,15 @@ on:
jobs: jobs:
deploy: deploy:
# Do not deploy in the main repository, only in user projects
if: github.repository_owner != 'fastapi'
runs-on: runs-on:
- self-hosted - self-hosted
- production - production
env: env:
ENVIRONMENT: production ENVIRONMENT: production
DOMAIN: ${{ secrets.DOMAIN_PRODUCTION }} DOMAIN: ${{ secrets.DOMAIN_PRODUCTION }}
STACK_NAME: ${{ secrets.STACK_NAME_PRODUCTION }}
SECRET_KEY: ${{ secrets.SECRET_KEY }} SECRET_KEY: ${{ secrets.SECRET_KEY }}
FIRST_SUPERUSER: ${{ secrets.FIRST_SUPERUSER }} FIRST_SUPERUSER: ${{ secrets.FIRST_SUPERUSER }}
FIRST_SUPERUSER_PASSWORD: ${{ secrets.FIRST_SUPERUSER_PASSWORD }} FIRST_SUPERUSER_PASSWORD: ${{ secrets.FIRST_SUPERUSER_PASSWORD }}
@@ -25,5 +28,5 @@ jobs:
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v4
- run: docker compose -f docker-compose.yml build - run: docker compose -f docker-compose.yml --project-name ${{ secrets.STACK_NAME_PRODUCTION }} build
- run: docker compose -f docker-compose.yml up -d - run: docker compose -f docker-compose.yml --project-name ${{ secrets.STACK_NAME_PRODUCTION }} up -d
+5 -2
View File
@@ -7,12 +7,15 @@ on:
jobs: jobs:
deploy: deploy:
# Do not deploy in the main repository, only in user projects
if: github.repository_owner != 'fastapi'
runs-on: runs-on:
- self-hosted - self-hosted
- staging - staging
env: env:
ENVIRONMENT: staging ENVIRONMENT: staging
DOMAIN: ${{ secrets.DOMAIN_STAGING }} DOMAIN: ${{ secrets.DOMAIN_STAGING }}
STACK_NAME: ${{ secrets.STACK_NAME_STAGING }}
SECRET_KEY: ${{ secrets.SECRET_KEY }} SECRET_KEY: ${{ secrets.SECRET_KEY }}
FIRST_SUPERUSER: ${{ secrets.FIRST_SUPERUSER }} FIRST_SUPERUSER: ${{ secrets.FIRST_SUPERUSER }}
FIRST_SUPERUSER_PASSWORD: ${{ secrets.FIRST_SUPERUSER_PASSWORD }} FIRST_SUPERUSER_PASSWORD: ${{ secrets.FIRST_SUPERUSER_PASSWORD }}
@@ -25,5 +28,5 @@ jobs:
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v4
- run: docker compose -f docker-compose.yml build - run: docker compose -f docker-compose.yml --project-name ${{ secrets.STACK_NAME_STAGING }} build
- run: docker compose -f docker-compose.yml up -d - run: docker compose -f docker-compose.yml --project-name ${{ secrets.STACK_NAME_STAGING }} up -d
+61
View File
@@ -0,0 +1,61 @@
name: Generate Client
on:
pull_request:
types:
- opened
- synchronize
jobs:
generate-client:
permissions:
contents: write
runs-on: ubuntu-latest
steps:
# For PRs from forks
- uses: actions/checkout@v4
# For PRs from the same repo
- uses: actions/checkout@v4
if: ( github.event_name != 'pull_request' || github.secret_source == 'Actions' )
with:
ref: ${{ github.head_ref }}
token: ${{ secrets.FULL_STACK_FASTAPI_TEMPLATE_REPO_TOKEN }}
- uses: actions/setup-node@v4
with:
node-version: lts/*
- uses: actions/setup-python@v5
with:
python-version: "3.10"
- name: Install uv
uses: astral-sh/setup-uv@v5
with:
version: "0.4.15"
enable-cache: true
- name: Install dependencies
run: npm ci
working-directory: frontend
- run: uv sync
working-directory: backend
- run: uv run bash scripts/generate-client.sh
env:
VIRTUAL_ENV: backend/.venv
ENVIRONMENT: production
SECRET_KEY: just-for-generating-client
POSTGRES_PASSWORD: just-for-generating-client
FIRST_SUPERUSER_PASSWORD: just-for-generating-client
- name: Add changes to git
run: |
git config --local user.email "github-actions@github.com"
git config --local user.name "github-actions"
git add frontend/src/client
# Same repo PRs
- name: Push changes
if: ( github.event_name != 'pull_request' || github.secret_source == 'Actions' )
run: |
git diff --staged --quiet || git commit -m "✨ Autogenerate frontend client"
git push
# Fork PRs
- name: Check changes
if: ( github.event_name == 'pull_request' && github.secret_source != 'Actions' )
run: |
git diff --staged --quiet || (echo "Changes detected in generated client, run scripts/generate-client.sh and commit the changes" && exit 1)
+24 -5
View File
@@ -2,27 +2,46 @@ name: Issue Manager
on: on:
schedule: schedule:
- cron: "0 0 * * *" - cron: "21 17 * * *"
issue_comment: issue_comment:
types: types:
- created - created
- edited
issues: issues:
types: types:
- labeled - labeled
pull_request_target:
types:
- labeled
workflow_dispatch:
permissions:
issues: write
pull-requests: write
jobs: jobs:
issue-manager: issue-manager:
if: github.repository_owner == 'fastapi'
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: tiangolo/issue-manager@0.5.0 - name: Dump GitHub context
env:
GITHUB_CONTEXT: ${{ toJson(github) }}
run: echo "$GITHUB_CONTEXT"
- uses: tiangolo/issue-manager@0.5.1
with: with:
token: ${{ secrets.GITHUB_TOKEN }} token: ${{ secrets.GITHUB_TOKEN }}
config: > config: >
{ {
"answered": { "answered": {
"users": ["tiangolo"],
"delay": 864000, "delay": 864000,
"message": "Assuming the original issue was solved, it will be automatically closed now. But feel free to add more comments or create new issues." "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."
},
"invalid": {
"delay": 0,
"message": "This was marked as invalid and will be closed now. If this is an error, please provide additional details."
} }
} }
+33
View File
@@ -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@v5
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 }}
+9 -8
View File
@@ -12,13 +12,15 @@ on:
description: PR number description: PR number
required: true required: true
debug_enabled: debug_enabled:
description: 'Run the build with tmate debugging enabled (https://github.com/marketplace/actions/debugging-with-tmate)' description: "Run the build with tmate debugging enabled (https://github.com/marketplace/actions/debugging-with-tmate)"
required: false required: false
default: 'false' default: "false"
jobs: jobs:
latest-changes: latest-changes:
runs-on: ubuntu-latest runs-on: ubuntu-latest
permissions:
pull-requests: read
steps: steps:
- name: Dump GitHub context - name: Dump GitHub context
env: env:
@@ -27,13 +29,12 @@ jobs:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
with: with:
# To allow latest-changes to commit to the main branch # To allow latest-changes to commit to the main branch
token: ${{ secrets.FULL_STACK_FASTAPI_POSTGRESQL_LATEST_CHANGES }} token: ${{ secrets.LATEST_CHANGES }}
- uses: docker://tiangolo/latest-changes:0.3.0 - uses: tiangolo/latest-changes@0.3.2
# - uses: tiangolo/latest-changes@main
with: with:
token: ${{ secrets.GITHUB_TOKEN }} token: ${{ secrets.GITHUB_TOKEN }}
latest_changes_file: ./release-notes.md latest_changes_file: ./release-notes.md
latest_changes_header: '## Latest Changes' latest_changes_header: "## Latest Changes"
end_regex: '^## ' end_regex: "^## "
debug_logs: true debug_logs: true
label_header_prefix: '### ' label_header_prefix: "### "
+28
View File
@@ -0,0 +1,28 @@
name: Lint Backend
on:
push:
branches:
- master
pull_request:
types:
- opened
- synchronize
jobs:
lint-backend:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.10"
- name: Install uv
uses: astral-sh/setup-uv@v5
with:
version: "0.4.15"
enable-cache: true
- run: uv run bash scripts/lint.sh
working-directory: backend
+131
View File
@@ -0,0 +1,131 @@
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@v4
# For pull requests it's not necessary to checkout the code but for the main branch it is
- uses: dorny/paths-filter@v3
id: filter
with:
filters: |
changed:
- backend/**
- frontend/**
- .env
- docker-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@v4
- uses: actions/setup-node@v4
with:
node-version: lts/*
- uses: actions/setup-python@v5
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@v5
with:
version: "0.4.15"
enable-cache: true
- run: uv sync
working-directory: backend
- run: npm ci
working-directory: frontend
- run: uv run bash scripts/generate-client.sh
env:
VIRTUAL_ENV: backend/.venv
- run: docker compose build
- run: docker compose down -v --remove-orphans
- name: Run Playwright tests
run: docker compose run --rm playwright npx 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@v4
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@v4
- uses: actions/setup-node@v4
with:
node-version: 20
- name: Install dependencies
run: npm ci
working-directory: frontend
- name: Download blob reports from GitHub Actions Artifacts
uses: actions/download-artifact@v4
with:
path: frontend/all-blob-reports
pattern: blob-report-*
merge-multiple: true
- name: Merge into HTML Report
run: npx playwright merge-reports --reporter html ./all-blob-reports
working-directory: frontend
- name: Upload HTML report
uses: actions/upload-artifact@v4
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
+12 -12
View File
@@ -2,30 +2,30 @@ name: Smokeshow
on: on:
workflow_run: workflow_run:
workflows: [Test] workflows: [Test Backend]
types: [completed] types: [completed]
permissions:
statuses: write
jobs: jobs:
smokeshow: smokeshow:
if: ${{ github.event.workflow_run.conclusion == 'success' }} if: ${{ github.event.workflow_run.conclusion == 'success' }}
runs-on: ubuntu-latest runs-on: ubuntu-latest
permissions:
actions: read
statuses: write
steps: steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5 - uses: actions/setup-python@v5
with: with:
python-version: '3.9' python-version: "3.10"
- run: pip install smokeshow - run: pip install smokeshow
- uses: actions/download-artifact@v4
- uses: dawidd6/action-download-artifact@v3.1.2
with: with:
workflow: test.yml name: coverage-html
commit: ${{ github.event.workflow_run.head_sha }} path: backend/htmlcov
github-token: ${{ secrets.GITHUB_TOKEN }}
- run: smokeshow upload coverage-html run-id: ${{ github.event.workflow_run.id }}
- run: smokeshow upload backend/htmlcov
env: env:
SMOKESHOW_GITHUB_STATUS_DESCRIPTION: Coverage {coverage-percentage} SMOKESHOW_GITHUB_STATUS_DESCRIPTION: Coverage {coverage-percentage}
SMOKESHOW_GITHUB_COVERAGE_THRESHOLD: 90 SMOKESHOW_GITHUB_COVERAGE_THRESHOLD: 90
+41
View File
@@ -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@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.10"
- name: Install uv
uses: astral-sh/setup-uv@v5
with:
version: "0.4.15"
enable-cache: true
- 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@v4
with:
name: coverage-html
path: backend/htmlcov
include-hidden-files: true
+26
View File
@@ -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@v4
- 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
-49
View File
@@ -1,49 +0,0 @@
name: Test
on:
push:
branches:
- master
pull_request:
types:
- opened
- synchronize
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.10'
- run: docker compose build
- run: docker compose down -v --remove-orphans
- run: docker compose up -d
- name: Lint
run: docker compose exec -T backend bash /app/scripts/lint.sh
- name: Run tests
run: docker compose exec -T backend bash /app/tests-start.sh "Coverage for ${{ github.sha }}"
- run: docker compose down -v --remove-orphans
- name: Store coverage files
uses: actions/upload-artifact@v4
with:
name: coverage-html
path: backend/htmlcov
# https://github.com/marketplace/actions/alls-green#why
alls-green: # This job does nothing and is only used for the branch protection
if: always()
needs:
- test
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) }}
+5
View File
@@ -1 +1,6 @@
.vscode .vscode
node_modules/
/test-results/
/playwright-report/
/blob-report/
/playwright/.cache/
+20 -13
View File
@@ -1,23 +1,30 @@
# See https://pre-commit.com for more information # See https://pre-commit.com for more information
# See https://pre-commit.com/hooks.html for more hooks # See https://pre-commit.com/hooks.html for more hooks
repos: repos:
- repo: https://github.com/pre-commit/pre-commit-hooks - repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0 rev: v4.4.0
hooks: hooks:
- id: check-added-large-files - id: check-added-large-files
- id: check-toml - id: check-toml
- id: check-yaml - id: check-yaml
args: args:
- --unsafe - --unsafe
- id: end-of-file-fixer - id: end-of-file-fixer
- id: trailing-whitespace exclude: |
- repo: https://github.com/charliermarsh/ruff-pre-commit (?x)^(
frontend/src/client/.*|
backend/app/email-templates/build/.*
)$
- id: trailing-whitespace
exclude: ^frontend/src/client/.*
- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: v0.2.2 rev: v0.2.2
hooks: hooks:
- id: ruff - id: ruff
args: args:
- --fix - --fix
- id: ruff-format - id: ruff-format
ci: ci:
autofix_commit_msg: 🎨 [pre-commit.ci] Auto format from pre-commit.com hooks autofix_commit_msg: 🎨 [pre-commit.ci] Auto format from pre-commit.com hooks
autoupdate_commit_msg: ⬆ [pre-commit.ci] pre-commit autoupdate autoupdate_commit_msg: ⬆ [pre-commit.ci] pre-commit autoupdate
+94 -23
View File
@@ -1,11 +1,7 @@
# Full Stack FastAPI Template # Full Stack FastAPI Template
<a href="https://github.com/tiangolo/full-stack-fastapi-template/actions?query=workflow%3ATest" target="_blank"><img src="https://github.com/tiangolo/full-stack-fastapi-template/workflows/Test/badge.svg" alt="Test"></a> <a href="https://github.com/fastapi/full-stack-fastapi-template/actions?query=workflow%3ATest" target="_blank"><img src="https://github.com/fastapi/full-stack-fastapi-template/workflows/Test/badge.svg" alt="Test"></a>
<a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/tiangolo/full-stack-fastapi-template" target="_blank"><img src="https://coverage-badge.samuelcolvin.workers.dev/tiangolo/full-stack-fastapi-template.svg" alt="Coverage"></a> <a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/fastapi/full-stack-fastapi-template" target="_blank"><img src="https://coverage-badge.samuelcolvin.workers.dev/fastapi/full-stack-fastapi-template.svg" alt="Coverage"></a>
### Dashboard - Dark Mode
[![API docs](img/dashboard-dark.png)](https://github.com/tiangolo/full-stack-fastapi-postgresql)
## Technology Stack and Features ## Technology Stack and Features
@@ -17,10 +13,11 @@
- 💃 Using TypeScript, hooks, Vite, and other parts of a modern frontend stack. - 💃 Using TypeScript, hooks, Vite, and other parts of a modern frontend stack.
- 🎨 [Chakra UI](https://chakra-ui.com) for the frontend components. - 🎨 [Chakra UI](https://chakra-ui.com) for the frontend components.
- 🤖 An automatically generated frontend client. - 🤖 An automatically generated frontend client.
- 🧪 [Playwright](https://playwright.dev) for End-to-End testing.
- 🦇 Dark mode support. - 🦇 Dark mode support.
- 🐋 [Docker Compose](https://www.docker.com) for development and production. - 🐋 [Docker Compose](https://www.docker.com) for development and production.
- 🔒 Secure password hashing by default. - 🔒 Secure password hashing by default.
- 🔑 JWT token authentication. - 🔑 JWT (JSON Web Token) authentication.
- 📫 Email based password recovery. - 📫 Email based password recovery.
- ✅ Tests with [Pytest](https://pytest.org). - ✅ Tests with [Pytest](https://pytest.org).
- 📞 [Traefik](https://traefik.io) as a reverse proxy / load balancer. - 📞 [Traefik](https://traefik.io) as a reverse proxy / load balancer.
@@ -29,36 +26,106 @@
### Dashboard Login ### Dashboard Login
[![API docs](img/login.png)](https://github.com/tiangolo/full-stack-fastapi-template) [![API docs](img/login.png)](https://github.com/fastapi/full-stack-fastapi-template)
### Dashboard - Admin ### Dashboard - Admin
[![API docs](img/dashboard.png)](https://github.com/tiangolo/full-stack-fastapi-template) [![API docs](img/dashboard.png)](https://github.com/fastapi/full-stack-fastapi-template)
### Dashboard - Create User ### Dashboard - Create User
[![API docs](img/dashboard-create.png)](https://github.com/tiangolo/full-stack-fastapi-template) [![API docs](img/dashboard-create.png)](https://github.com/fastapi/full-stack-fastapi-template)
### Dashboard - Items ### Dashboard - Items
[![API docs](img/dashboard-items.png)](https://github.com/tiangolo/full-stack-fastapi-template) [![API docs](img/dashboard-items.png)](https://github.com/fastapi/full-stack-fastapi-template)
### Dashboard - User Settings ### Dashboard - User Settings
[![API docs](img/dashboard-user-settings.png)](https://github.com/tiangolo/full-stack-fastapi-template) [![API docs](img/dashboard-user-settings.png)](https://github.com/fastapi/full-stack-fastapi-template)
### Interactive API documentation ### Dashboard - Dark Mode
[![API docs](img/docs.png)](https://github.com/tiangolo/full-stack-fastapi-template) [![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 ## How To Use It
You can **just fork or clone** this repository and use it as is. You can **just fork or clone** this repository and use it as is.
✨ It just works. ✨ ✨ 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 ### Configure
You can then update configs in the `.env` files to customize your configurations. You can then update configs in the `.env` files to customize your configurations.
@@ -69,7 +136,11 @@ Before deploying it, make sure you change at least the values for:
- `FIRST_SUPERUSER_PASSWORD` - `FIRST_SUPERUSER_PASSWORD`
- `POSTGRES_PASSWORD` - `POSTGRES_PASSWORD`
### Generate secret keys 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`. Some environment variables in the `.env` file have a default value of `changethis`.
@@ -81,7 +152,7 @@ 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. 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 ## How To Use It - Alternative With Copier
This repository also supports generating a new project using [Copier](https://copier.readthedocs.io). This repository also supports generating a new project using [Copier](https://copier.readthedocs.io).
@@ -103,25 +174,25 @@ pipx install copier
**Note**: If you have `pipx`, installing copier is optional, you could run it directly. **Note**: If you have `pipx`, installing copier is optional, you could run it directly.
### Generate a Project with Copier ### Generate a Project With Copier
Decide a name for your new project's directory, you will use it below. For example, `my-awesome-project`. 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: Go to the directory that will be the parent of your project, and run the command with your project's name:
```bash ```bash
copier copy https://github.com/tiangolo/full-stack-fastapi-template my-awesome-project --trust 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: If you have `pipx` and you didn't install `copier`, you can run it directly:
```bash ```bash
pipx run copier copy https://github.com/tiangolo/full-stack-fastapi-template my-awesome-project --trust 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/tiangolo/full-stack-fastapi-template/blob/master/.copier/update_dotenv.py) that updates your `.env` files. **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 ### Input Variables
Copier will ask you for some data, you might want to have at hand before generating the project. Copier will ask you for some data, you might want to have at hand before generating the project.
@@ -130,7 +201,7 @@ 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: 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). - `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 (no spaces) (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. - `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`: (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). - `first_superuser_password`: (default: `"changethis"`) The password of the first superuser (in .env).
+29
View File
@@ -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. 🙇
+32 -17
View File
@@ -1,28 +1,43 @@
FROM tiangolo/uvicorn-gunicorn-fastapi:python3.10 FROM python:3.10
ENV PYTHONUNBUFFERED=1
WORKDIR /app/ WORKDIR /app/
# Install Poetry # Install uv
RUN curl -sSL https://install.python-poetry.org | POETRY_HOME=/opt/poetry python && \ # Ref: https://docs.astral.sh/uv/guides/integration/docker/#installing-uv
cd /usr/local/bin && \ COPY --from=ghcr.io/astral-sh/uv:0.5.11 /uv /uvx /bin/
ln -s /opt/poetry/bin/poetry && \
poetry config virtualenvs.create false
# Copy poetry.lock* in case it doesn't exist in the repo # Place executables in the environment at the front of the path
COPY ./pyproject.toml ./poetry.lock* /app/ # Ref: https://docs.astral.sh/uv/guides/integration/docker/#using-the-environment
ENV PATH="/app/.venv/bin:$PATH"
# Allow installing dev dependencies to run tests # Compile bytecode
ARG INSTALL_DEV=false # Ref: https://docs.astral.sh/uv/guides/integration/docker/#compiling-bytecode
RUN bash -c "if [ $INSTALL_DEV == 'true' ] ; then poetry install --no-root ; else poetry install --no-root --only main ; fi" ENV UV_COMPILE_BYTECODE=1
# uv Cache
# Ref: https://docs.astral.sh/uv/guides/integration/docker/#caching
ENV UV_LINK_MODE=copy
# 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-project
ENV PYTHONPATH=/app ENV PYTHONPATH=/app
COPY ./scripts/ /app/ COPY ./scripts /app/scripts
COPY ./alembic.ini /app/ COPY ./pyproject.toml ./uv.lock ./alembic.ini /app/
COPY ./prestart.sh /app/
COPY ./tests-start.sh /app/
COPY ./app /app/app COPY ./app /app/app
# Sync the project
# Ref: https://docs.astral.sh/uv/guides/integration/docker/#intermediate-layers
RUN --mount=type=cache,target=/root/.cache/uv \
uv sync
CMD ["fastapi", "run", "--workers", "4", "app/main.py"]
+36 -62
View File
@@ -3,84 +3,50 @@
## Requirements ## Requirements
* [Docker](https://www.docker.com/). * [Docker](https://www.docker.com/).
* [Poetry](https://python-poetry.org/) for Python package and environment management. * [uv](https://docs.astral.sh/uv/) for Python package and environment management.
## Local Development ## Docker Compose
* Start the stack with Docker Compose: Start the local development environment with Docker Compose following the guide in [../development.md](../development.md).
```bash ## General Workflow
docker compose up -d
```
* Now you can open your browser and interact with these URLs: By default, the dependencies are managed with [uv](https://docs.astral.sh/uv/), go there and install it.
Frontend, built with Docker, with routes handled based on the path: http://localhost
Backend, JSON based web API based on OpenAPI: http://localhost/api/
Automatic interactive documentation with Swagger UI (from the OpenAPI backend): http://localhost/docs
Adminer, database web administration: http://localhost:8080
Traefik UI, to see how the routes are being handled by the proxy: http://localhost:8090
**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:
```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
```
If your Docker is not running in `localhost` (the URLs above wouldn't work) you would need to use the IP or domain where your Docker is running.
## Backend local development, additional details
### General workflow
By default, the dependencies are managed with [Poetry](https://python-poetry.org/), go there and install it.
From `./backend/` you can install all the dependencies with: From `./backend/` you can install all the dependencies with:
```console ```console
$ poetry install $ uv sync
``` ```
Then you can start a shell session with the new environment with: Then you can activate the virtual environment with:
```console ```console
$ poetry shell $ source .venv/bin/activate
``` ```
Make sure your editor is using the correct Python virtual environment. 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`. 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 ## 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. 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. The setup is also already configured so you can run the tests through the VS Code Python tests tab.
### Docker Compose Override ## Docker Compose Override
During development, you can change Docker Compose settings that will only affect the local development environment in the file `docker-compose.override.yml`. During development, you can change Docker Compose settings that will only affect the local development environment in the file `docker-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. 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 mounted as a Docker "host volume", mapping 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. 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 `/start-reload.sh` (included in the base image) instead of the default `/start.sh` (also included in the base image). 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: 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 ```console
$ docker compose up -d $ 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. 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.
@@ -88,10 +54,10 @@ There is also a commented out `command` override, you can uncomment it and comme
To get inside the container with a `bash` session you can start the stack with: To get inside the container with a `bash` session you can start the stack with:
```console ```console
$ docker compose up -d $ docker compose watch
``` ```
and then `exec` inside the running container: and then in another terminal, `exec` inside the running container:
```console ```console
$ docker compose exec backend bash $ docker compose exec backend bash
@@ -105,16 +71,16 @@ 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`. 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 script `/start-reload.sh` to run the debug live reloading server. You can run that script from inside the container with: There you can use the `fastapi run --reload` command to run the debug live reloading server.
```console ```console
$ bash /start-reload.sh $ fastapi run --reload app/main.py
``` ```
...it will look like: ...it will look like:
```console ```console
root@7f2607af31c3:/app# bash /start-reload.sh 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. and then hit enter. That runs the live reloading server that auto reloads when it detects code changes.
@@ -123,7 +89,7 @@ Nevertheless, if it doesn't detect a change but a syntax error, it will just sto
...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. ...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 ## Backend tests
To test the backend run: To test the backend run:
@@ -135,27 +101,27 @@ The tests run with Pytest, modify and add tests to `./backend/app/tests/`.
If you use GitHub Actions the tests will run automatically. If you use GitHub Actions the tests will run automatically.
#### Test running stack ### Test running stack
If your stack is already up and you just want to run the tests, you can use: If your stack is already up and you just want to run the tests, you can use:
```bash ```bash
docker compose exec backend bash /app/tests-start.sh docker compose exec backend bash scripts/tests-start.sh
``` ```
That `/app/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. 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: For example, to stop on first error:
```bash ```bash
docker compose exec backend bash /app/tests-start.sh -x docker compose exec backend bash scripts/tests-start.sh -x
``` ```
#### Test Coverage ### 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. 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 ## 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. 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.
@@ -183,16 +149,24 @@ $ alembic revision --autogenerate -m "Add column last_name to User model"
$ alembic upgrade head $ alembic upgrade head
``` ```
If you don't want to use migrations at all, uncomment the lines in the file at `./backend/app/db/init_db.py` that end in: 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 ```python
SQLModel.metadata.create_all(engine) SQLModel.metadata.create_all(engine)
``` ```
and comment the line in the file `prestart.sh` that contains: and comment the line in the file `scripts/prestart.sh` that contains:
```console ```console
$ alembic upgrade head $ 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. 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://marketplace.visualstudio.com/items?itemName=attilabuti.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.
+2 -6
View File
@@ -19,6 +19,7 @@ fileConfig(config.config_file_name)
# target_metadata = None # target_metadata = None
from app.models import SQLModel # noqa from app.models import SQLModel # noqa
from app.core.config import settings # noqa
target_metadata = SQLModel.metadata target_metadata = SQLModel.metadata
@@ -29,12 +30,7 @@ target_metadata = SQLModel.metadata
def get_url(): def get_url():
user = os.getenv("POSTGRES_USER", "postgres") return str(settings.SQLALCHEMY_DATABASE_URI)
password = os.getenv("POSTGRES_PASSWORD", "")
server = os.getenv("POSTGRES_SERVER", "db")
port = os.getenv("POSTGRES_PORT", "5432")
db = os.getenv("POSTGRES_DB", "app")
return f"postgresql+psycopg://{user}:{password}@{server}:{port}/{db}"
def run_migrations_offline(): def run_migrations_offline():
@@ -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(None, 'item', type_='foreignkey')
op.create_foreign_key('item_owner_id_fkey', 'item', 'user', ['owner_id'], ['id'])
op.alter_column('item', 'owner_id',
existing_type=sa.UUID(),
nullable=True)
# ### end Alembic commands ###
@@ -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)
@@ -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'])
+4 -3
View File
@@ -1,9 +1,10 @@
from collections.abc import Generator from collections.abc import Generator
from typing import Annotated from typing import Annotated
import jwt
from fastapi import Depends, HTTPException, status from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer from fastapi.security import OAuth2PasswordBearer
from jose import JWTError, jwt from jwt.exceptions import InvalidTokenError
from pydantic import ValidationError from pydantic import ValidationError
from sqlmodel import Session from sqlmodel import Session
@@ -32,7 +33,7 @@ def get_current_user(session: SessionDep, token: TokenDep) -> User:
token, settings.SECRET_KEY, algorithms=[security.ALGORITHM] token, settings.SECRET_KEY, algorithms=[security.ALGORITHM]
) )
token_data = TokenPayload(**payload) token_data = TokenPayload(**payload)
except (JWTError, ValidationError): except (InvalidTokenError, ValidationError):
raise HTTPException( raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN, status_code=status.HTTP_403_FORBIDDEN,
detail="Could not validate credentials", detail="Could not validate credentials",
@@ -51,6 +52,6 @@ CurrentUser = Annotated[User, Depends(get_current_user)]
def get_current_active_superuser(current_user: CurrentUser) -> User: def get_current_active_superuser(current_user: CurrentUser) -> User:
if not current_user.is_superuser: if not current_user.is_superuser:
raise HTTPException( raise HTTPException(
status_code=400, detail="The user doesn't have enough privileges" status_code=403, detail="The user doesn't have enough privileges"
) )
return current_user return current_user
+10 -5
View File
@@ -1,9 +1,14 @@
from fastapi import APIRouter from fastapi import APIRouter
from app.api.routes import items, login, users, utils from app.api.routes import items, login, private, users, utils
from app.core.config import settings
api_router = APIRouter() api_router = APIRouter()
api_router.include_router(login.router, tags=["login"]) api_router.include_router(login.router)
api_router.include_router(users.router, prefix="/users", tags=["users"]) api_router.include_router(users.router)
api_router.include_router(utils.router, prefix="/utils", tags=["utils"]) api_router.include_router(utils.router)
api_router.include_router(items.router, prefix="/items", tags=["items"]) api_router.include_router(items.router)
if settings.ENVIRONMENT == "local":
api_router.include_router(private.router)
+21 -14
View File
@@ -1,15 +1,16 @@
import uuid
from typing import Any from typing import Any
from fastapi import APIRouter, HTTPException from fastapi import APIRouter, HTTPException
from sqlmodel import func, select from sqlmodel import func, select
from app.api.deps import CurrentUser, SessionDep from app.api.deps import CurrentUser, SessionDep
from app.models import Item, ItemCreate, ItemOut, ItemsOut, ItemUpdate, Message from app.models import Item, ItemCreate, ItemPublic, ItemsPublic, ItemUpdate, Message
router = APIRouter() router = APIRouter(prefix="/items", tags=["items"])
@router.get("/", response_model=ItemsOut) @router.get("/", response_model=ItemsPublic)
def read_items( def read_items(
session: SessionDep, current_user: CurrentUser, skip: int = 0, limit: int = 100 session: SessionDep, current_user: CurrentUser, skip: int = 0, limit: int = 100
) -> Any: ) -> Any:
@@ -18,17 +19,17 @@ def read_items(
""" """
if current_user.is_superuser: if current_user.is_superuser:
statment = select(func.count()).select_from(Item) count_statement = select(func.count()).select_from(Item)
count = session.exec(statment).one() count = session.exec(count_statement).one()
statement = select(Item).offset(skip).limit(limit) statement = select(Item).offset(skip).limit(limit)
items = session.exec(statement).all() items = session.exec(statement).all()
else: else:
statment = ( count_statement = (
select(func.count()) select(func.count())
.select_from(Item) .select_from(Item)
.where(Item.owner_id == current_user.id) .where(Item.owner_id == current_user.id)
) )
count = session.exec(statment).one() count = session.exec(count_statement).one()
statement = ( statement = (
select(Item) select(Item)
.where(Item.owner_id == current_user.id) .where(Item.owner_id == current_user.id)
@@ -37,11 +38,11 @@ def read_items(
) )
items = session.exec(statement).all() items = session.exec(statement).all()
return ItemsOut(data=items, count=count) return ItemsPublic(data=items, count=count)
@router.get("/{id}", response_model=ItemOut) @router.get("/{id}", response_model=ItemPublic)
def read_item(session: SessionDep, current_user: CurrentUser, id: int) -> Any: def read_item(session: SessionDep, current_user: CurrentUser, id: uuid.UUID) -> Any:
""" """
Get item by ID. Get item by ID.
""" """
@@ -53,7 +54,7 @@ def read_item(session: SessionDep, current_user: CurrentUser, id: int) -> Any:
return item return item
@router.post("/", response_model=ItemOut) @router.post("/", response_model=ItemPublic)
def create_item( def create_item(
*, session: SessionDep, current_user: CurrentUser, item_in: ItemCreate *, session: SessionDep, current_user: CurrentUser, item_in: ItemCreate
) -> Any: ) -> Any:
@@ -67,9 +68,13 @@ def create_item(
return item return item
@router.put("/{id}", response_model=ItemOut) @router.put("/{id}", response_model=ItemPublic)
def update_item( def update_item(
*, session: SessionDep, current_user: CurrentUser, id: int, item_in: ItemUpdate *,
session: SessionDep,
current_user: CurrentUser,
id: uuid.UUID,
item_in: ItemUpdate,
) -> Any: ) -> Any:
""" """
Update an item. Update an item.
@@ -88,7 +93,9 @@ def update_item(
@router.delete("/{id}") @router.delete("/{id}")
def delete_item(session: SessionDep, current_user: CurrentUser, id: int) -> Message: def delete_item(
session: SessionDep, current_user: CurrentUser, id: uuid.UUID
) -> Message:
""" """
Delete an item. Delete an item.
""" """
+3 -3
View File
@@ -10,7 +10,7 @@ from app.api.deps import CurrentUser, SessionDep, get_current_active_superuser
from app.core import security from app.core import security
from app.core.config import settings from app.core.config import settings
from app.core.security import get_password_hash from app.core.security import get_password_hash
from app.models import Message, NewPassword, Token, UserOut from app.models import Message, NewPassword, Token, UserPublic
from app.utils import ( from app.utils import (
generate_password_reset_token, generate_password_reset_token,
generate_reset_password_email, generate_reset_password_email,
@@ -18,7 +18,7 @@ from app.utils import (
verify_password_reset_token, verify_password_reset_token,
) )
router = APIRouter() router = APIRouter(tags=["login"])
@router.post("/login/access-token") @router.post("/login/access-token")
@@ -43,7 +43,7 @@ def login_access_token(
) )
@router.post("/login/test-token", response_model=UserOut) @router.post("/login/test-token", response_model=UserPublic)
def test_token(current_user: CurrentUser) -> Any: def test_token(current_user: CurrentUser) -> Any:
""" """
Test access token Test access token
+38
View File
@@ -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
+39 -32
View File
@@ -1,3 +1,4 @@
import uuid
from typing import Any from typing import Any
from fastapi import APIRouter, Depends, HTTPException from fastapi import APIRouter, Depends, HTTPException
@@ -17,36 +18,38 @@ from app.models import (
UpdatePassword, UpdatePassword,
User, User,
UserCreate, UserCreate,
UserCreateOpen, UserPublic,
UserOut, UserRegister,
UsersOut, UsersPublic,
UserUpdate, UserUpdate,
UserUpdateMe, UserUpdateMe,
) )
from app.utils import generate_new_account_email, send_email from app.utils import generate_new_account_email, send_email
router = APIRouter() router = APIRouter(prefix="/users", tags=["users"])
@router.get( @router.get(
"/", dependencies=[Depends(get_current_active_superuser)], response_model=UsersOut "/",
dependencies=[Depends(get_current_active_superuser)],
response_model=UsersPublic,
) )
def read_users(session: SessionDep, skip: int = 0, limit: int = 100) -> Any: def read_users(session: SessionDep, skip: int = 0, limit: int = 100) -> Any:
""" """
Retrieve users. Retrieve users.
""" """
statment = select(func.count()).select_from(User) count_statement = select(func.count()).select_from(User)
count = session.exec(statment).one() count = session.exec(count_statement).one()
statement = select(User).offset(skip).limit(limit) statement = select(User).offset(skip).limit(limit)
users = session.exec(statement).all() users = session.exec(statement).all()
return UsersOut(data=users, count=count) return UsersPublic(data=users, count=count)
@router.post( @router.post(
"/", dependencies=[Depends(get_current_active_superuser)], response_model=UserOut "/", dependencies=[Depends(get_current_active_superuser)], response_model=UserPublic
) )
def create_user(*, session: SessionDep, user_in: UserCreate) -> Any: def create_user(*, session: SessionDep, user_in: UserCreate) -> Any:
""" """
@@ -72,7 +75,7 @@ def create_user(*, session: SessionDep, user_in: UserCreate) -> Any:
return user return user
@router.patch("/me", response_model=UserOut) @router.patch("/me", response_model=UserPublic)
def update_user_me( def update_user_me(
*, session: SessionDep, user_in: UserUpdateMe, current_user: CurrentUser *, session: SessionDep, user_in: UserUpdateMe, current_user: CurrentUser
) -> Any: ) -> Any:
@@ -114,38 +117,47 @@ def update_password_me(
return Message(message="Password updated successfully") return Message(message="Password updated successfully")
@router.get("/me", response_model=UserOut) @router.get("/me", response_model=UserPublic)
def read_user_me(session: SessionDep, current_user: CurrentUser) -> Any: def read_user_me(current_user: CurrentUser) -> Any:
""" """
Get current user. Get current user.
""" """
return current_user return current_user
@router.post("/open", response_model=UserOut) @router.delete("/me", response_model=Message)
def create_user_open(session: SessionDep, user_in: UserCreateOpen) -> Any: def delete_user_me(session: SessionDep, current_user: CurrentUser) -> Any:
"""
Delete own user.
"""
if current_user.is_superuser:
raise HTTPException(
status_code=403, detail="Super users are not allowed to delete themselves"
)
session.delete(current_user)
session.commit()
return Message(message="User deleted successfully")
@router.post("/signup", response_model=UserPublic)
def register_user(session: SessionDep, user_in: UserRegister) -> Any:
""" """
Create new user without the need to be logged in. Create new user without the need to be logged in.
""" """
if not settings.USERS_OPEN_REGISTRATION:
raise HTTPException(
status_code=403,
detail="Open user registration is forbidden on this server",
)
user = crud.get_user_by_email(session=session, email=user_in.email) user = crud.get_user_by_email(session=session, email=user_in.email)
if user: if user:
raise HTTPException( raise HTTPException(
status_code=400, status_code=400,
detail="The user with this email already exists in the system", detail="The user with this email already exists in the system",
) )
user_create = UserCreate.from_orm(user_in) user_create = UserCreate.model_validate(user_in)
user = crud.create_user(session=session, user_create=user_create) user = crud.create_user(session=session, user_create=user_create)
return user return user
@router.get("/{user_id}", response_model=UserOut) @router.get("/{user_id}", response_model=UserPublic)
def read_user_by_id( def read_user_by_id(
user_id: int, session: SessionDep, current_user: CurrentUser user_id: uuid.UUID, session: SessionDep, current_user: CurrentUser
) -> Any: ) -> Any:
""" """
Get a specific user by id. Get a specific user by id.
@@ -164,12 +176,12 @@ def read_user_by_id(
@router.patch( @router.patch(
"/{user_id}", "/{user_id}",
dependencies=[Depends(get_current_active_superuser)], dependencies=[Depends(get_current_active_superuser)],
response_model=UserOut, response_model=UserPublic,
) )
def update_user( def update_user(
*, *,
session: SessionDep, session: SessionDep,
user_id: int, user_id: uuid.UUID,
user_in: UserUpdate, user_in: UserUpdate,
) -> Any: ) -> Any:
""" """
@@ -193,9 +205,9 @@ def update_user(
return db_user return db_user
@router.delete("/{user_id}") @router.delete("/{user_id}", dependencies=[Depends(get_current_active_superuser)])
def delete_user( def delete_user(
session: SessionDep, current_user: CurrentUser, user_id: int session: SessionDep, current_user: CurrentUser, user_id: uuid.UUID
) -> Message: ) -> Message:
""" """
Delete a user. Delete a user.
@@ -203,15 +215,10 @@ def delete_user(
user = session.get(User, user_id) user = session.get(User, user_id)
if not user: if not user:
raise HTTPException(status_code=404, detail="User not found") raise HTTPException(status_code=404, detail="User not found")
elif user != current_user and not current_user.is_superuser: if user == current_user:
raise HTTPException(
status_code=403, detail="The user doesn't have enough privileges"
)
elif user == current_user and current_user.is_superuser:
raise HTTPException( raise HTTPException(
status_code=403, detail="Super users are not allowed to delete themselves" status_code=403, detail="Super users are not allowed to delete themselves"
) )
statement = delete(Item).where(col(Item.owner_id) == user_id) statement = delete(Item).where(col(Item.owner_id) == user_id)
session.exec(statement) # type: ignore session.exec(statement) # type: ignore
session.delete(user) session.delete(user)
+6 -1
View File
@@ -5,7 +5,7 @@ from app.api.deps import get_current_active_superuser
from app.models import Message from app.models import Message
from app.utils import generate_test_email, send_email from app.utils import generate_test_email, send_email
router = APIRouter() router = APIRouter(prefix="/utils", tags=["utils"])
@router.post( @router.post(
@@ -24,3 +24,8 @@ def test_email(email_to: EmailStr) -> Message:
html_content=email_data.html_content, html_content=email_data.html_content,
) )
return Message(message="Test email sent") return Message(message="Test email sent")
@router.get("/health-check/")
async def health_check() -> bool:
return True
-39
View File
@@ -1,39 +0,0 @@
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()
+20 -21
View File
@@ -5,6 +5,7 @@ from typing import Annotated, Any, Literal
from pydantic import ( from pydantic import (
AnyUrl, AnyUrl,
BeforeValidator, BeforeValidator,
EmailStr,
HttpUrl, HttpUrl,
PostgresDsn, PostgresDsn,
computed_field, computed_field,
@@ -25,36 +26,38 @@ def parse_cors(v: Any) -> list[str] | str:
class Settings(BaseSettings): class Settings(BaseSettings):
model_config = SettingsConfigDict( model_config = SettingsConfigDict(
env_file=".env", env_ignore_empty=True, extra="ignore" # Use top level .env file (one level above ./backend/)
env_file="../.env",
env_ignore_empty=True,
extra="ignore",
) )
API_V1_STR: str = "/api/v1" API_V1_STR: str = "/api/v1"
SECRET_KEY: str = secrets.token_urlsafe(32) SECRET_KEY: str = secrets.token_urlsafe(32)
# 60 minutes * 24 hours * 8 days = 8 days # 60 minutes * 24 hours * 8 days = 8 days
ACCESS_TOKEN_EXPIRE_MINUTES: int = 60 * 24 * 8 ACCESS_TOKEN_EXPIRE_MINUTES: int = 60 * 24 * 8
DOMAIN: str = "localhost" FRONTEND_HOST: str = "http://localhost:5173"
ENVIRONMENT: Literal["local", "staging", "production"] = "local" ENVIRONMENT: Literal["local", "staging", "production"] = "local"
@computed_field # type: ignore[misc]
@property
def server_host(self) -> str:
# Use HTTPS for anything other than local development
if self.ENVIRONMENT == "local":
return f"http://{self.DOMAIN}"
return f"https://{self.DOMAIN}"
BACKEND_CORS_ORIGINS: Annotated[ BACKEND_CORS_ORIGINS: Annotated[
list[AnyUrl] | str, BeforeValidator(parse_cors) 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 PROJECT_NAME: str
SENTRY_DSN: HttpUrl | None = None SENTRY_DSN: HttpUrl | None = None
POSTGRES_SERVER: str POSTGRES_SERVER: str
POSTGRES_PORT: int = 5432 POSTGRES_PORT: int = 5432
POSTGRES_USER: str POSTGRES_USER: str
POSTGRES_PASSWORD: str POSTGRES_PASSWORD: str = ""
POSTGRES_DB: str = "" POSTGRES_DB: str = ""
@computed_field # type: ignore[misc] @computed_field # type: ignore[prop-decorator]
@property @property
def SQLALCHEMY_DATABASE_URI(self) -> PostgresDsn: def SQLALCHEMY_DATABASE_URI(self) -> PostgresDsn:
return MultiHostUrl.build( return MultiHostUrl.build(
@@ -72,9 +75,8 @@ class Settings(BaseSettings):
SMTP_HOST: str | None = None SMTP_HOST: str | None = None
SMTP_USER: str | None = None SMTP_USER: str | None = None
SMTP_PASSWORD: str | None = None SMTP_PASSWORD: str | None = None
# TODO: update type to EmailStr when sqlmodel supports it EMAILS_FROM_EMAIL: EmailStr | None = None
EMAILS_FROM_EMAIL: str | None = None EMAILS_FROM_NAME: EmailStr | None = None
EMAILS_FROM_NAME: str | None = None
@model_validator(mode="after") @model_validator(mode="after")
def _set_default_emails_from(self) -> Self: def _set_default_emails_from(self) -> Self:
@@ -84,17 +86,14 @@ class Settings(BaseSettings):
EMAIL_RESET_TOKEN_EXPIRE_HOURS: int = 48 EMAIL_RESET_TOKEN_EXPIRE_HOURS: int = 48
@computed_field # type: ignore[misc] @computed_field # type: ignore[prop-decorator]
@property @property
def emails_enabled(self) -> bool: def emails_enabled(self) -> bool:
return bool(self.SMTP_HOST and self.EMAILS_FROM_EMAIL) return bool(self.SMTP_HOST and self.EMAILS_FROM_EMAIL)
# TODO: update type to EmailStr when sqlmodel supports it EMAIL_TEST_USER: EmailStr = "test@example.com"
EMAIL_TEST_USER: str = "test@example.com" FIRST_SUPERUSER: EmailStr
# TODO: update type to EmailStr when sqlmodel supports it
FIRST_SUPERUSER: str
FIRST_SUPERUSER_PASSWORD: str FIRST_SUPERUSER_PASSWORD: str
USERS_OPEN_REGISTRATION: bool = False
def _check_default_secret(self, var_name: str, value: str | None) -> None: def _check_default_secret(self, var_name: str, value: str | None) -> None:
if value == "changethis": if value == "changethis":
+1 -2
View File
@@ -9,7 +9,7 @@ engine = create_engine(str(settings.SQLALCHEMY_DATABASE_URI))
# make sure all SQLModel models are imported (app.models) before initializing DB # make sure all SQLModel models are imported (app.models) before initializing DB
# otherwise, SQLModel might fail to initialize relationships properly # otherwise, SQLModel might fail to initialize relationships properly
# for more details: https://github.com/tiangolo/full-stack-fastapi-template/issues/28 # for more details: https://github.com/fastapi/full-stack-fastapi-template/issues/28
def init_db(session: Session) -> None: def init_db(session: Session) -> None:
@@ -18,7 +18,6 @@ def init_db(session: Session) -> None:
# the tables un-commenting the next lines # the tables un-commenting the next lines
# from sqlmodel import SQLModel # from sqlmodel import SQLModel
# from app.core.engine import engine
# This works because the models are already imported and registered from app.models # This works because the models are already imported and registered from app.models
# SQLModel.metadata.create_all(engine) # SQLModel.metadata.create_all(engine)
+3 -3
View File
@@ -1,7 +1,7 @@
from datetime import datetime, timedelta from datetime import datetime, timedelta, timezone
from typing import Any from typing import Any
from jose import jwt import jwt
from passlib.context import CryptContext from passlib.context import CryptContext
from app.core.config import settings from app.core.config import settings
@@ -13,7 +13,7 @@ ALGORITHM = "HS256"
def create_access_token(subject: str | Any, expires_delta: timedelta) -> str: def create_access_token(subject: str | Any, expires_delta: timedelta) -> str:
expire = datetime.utcnow() + expires_delta expire = datetime.now(timezone.utc) + expires_delta
to_encode = {"exp": expire, "sub": str(subject)} to_encode = {"exp": expire, "sub": str(subject)}
encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=ALGORITHM) encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt return encoded_jwt
+2 -1
View File
@@ -1,3 +1,4 @@
import uuid
from typing import Any from typing import Any
from sqlmodel import Session, select from sqlmodel import Session, select
@@ -45,7 +46,7 @@ def authenticate(*, session: Session, email: str, password: str) -> User | None:
return db_user return db_user
def create_item(*, session: Session, item_in: ItemCreate, owner_id: int) -> Item: 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}) db_item = Item.model_validate(item_in, update={"owner_id": owner_id})
session.add(db_item) session.add(db_item)
session.commit() session.commit()
+6 -4
View File
@@ -1,3 +1,4 @@
import sentry_sdk
from fastapi import FastAPI from fastapi import FastAPI
from fastapi.routing import APIRoute from fastapi.routing import APIRoute
from starlette.middleware.cors import CORSMiddleware from starlette.middleware.cors import CORSMiddleware
@@ -10,6 +11,9 @@ def custom_generate_unique_id(route: APIRoute) -> str:
return f"{route.tags[0]}-{route.name}" 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( app = FastAPI(
title=settings.PROJECT_NAME, title=settings.PROJECT_NAME,
openapi_url=f"{settings.API_V1_STR}/openapi.json", openapi_url=f"{settings.API_V1_STR}/openapi.json",
@@ -17,12 +21,10 @@ app = FastAPI(
) )
# Set all CORS enabled origins # Set all CORS enabled origins
if settings.BACKEND_CORS_ORIGINS: if settings.all_cors_origins:
app.add_middleware( app.add_middleware(
CORSMiddleware, CORSMiddleware,
allow_origins=[ allow_origins=settings.all_cors_origins,
str(origin).strip("/") for origin in settings.BACKEND_CORS_ORIGINS
],
allow_credentials=True, allow_credentials=True,
allow_methods=["*"], allow_methods=["*"],
allow_headers=["*"], allow_headers=["*"],
+38 -37
View File
@@ -1,94 +1,95 @@
import uuid
from pydantic import EmailStr
from sqlmodel import Field, Relationship, SQLModel from sqlmodel import Field, Relationship, SQLModel
# Shared properties # Shared properties
# TODO replace email str with EmailStr when sqlmodel supports it
class UserBase(SQLModel): class UserBase(SQLModel):
email: str = Field(unique=True, index=True) email: EmailStr = Field(unique=True, index=True, max_length=255)
is_active: bool = True is_active: bool = True
is_superuser: bool = False is_superuser: bool = False
full_name: str | None = None full_name: str | None = Field(default=None, max_length=255)
# Properties to receive via API on creation # Properties to receive via API on creation
class UserCreate(UserBase): class UserCreate(UserBase):
password: str password: str = Field(min_length=8, max_length=40)
# TODO replace email str with EmailStr when sqlmodel supports it class UserRegister(SQLModel):
class UserCreateOpen(SQLModel): email: EmailStr = Field(max_length=255)
email: str password: str = Field(min_length=8, max_length=40)
password: str full_name: str | None = Field(default=None, max_length=255)
full_name: str | None = None
# Properties to receive via API on update, all are optional # Properties to receive via API on update, all are optional
# TODO replace email str with EmailStr when sqlmodel supports it
class UserUpdate(UserBase): class UserUpdate(UserBase):
email: str | None = None # type: ignore email: EmailStr | None = Field(default=None, max_length=255) # type: ignore
password: str | None = None password: str | None = Field(default=None, min_length=8, max_length=40)
# TODO replace email str with EmailStr when sqlmodel supports it
class UserUpdateMe(SQLModel): class UserUpdateMe(SQLModel):
full_name: str | None = None full_name: str | None = Field(default=None, max_length=255)
email: str | None = None email: EmailStr | None = Field(default=None, max_length=255)
class UpdatePassword(SQLModel): class UpdatePassword(SQLModel):
current_password: str current_password: str = Field(min_length=8, max_length=40)
new_password: str new_password: str = Field(min_length=8, max_length=40)
# Database model, database table inferred from class name # Database model, database table inferred from class name
class User(UserBase, table=True): class User(UserBase, table=True):
id: int | None = Field(default=None, primary_key=True) id: uuid.UUID = Field(default_factory=uuid.uuid4, primary_key=True)
hashed_password: str hashed_password: str
items: list["Item"] = Relationship(back_populates="owner") items: list["Item"] = Relationship(back_populates="owner", cascade_delete=True)
# Properties to return via API, id is always required # Properties to return via API, id is always required
class UserOut(UserBase): class UserPublic(UserBase):
id: int id: uuid.UUID
class UsersOut(SQLModel): class UsersPublic(SQLModel):
data: list[UserOut] data: list[UserPublic]
count: int count: int
# Shared properties # Shared properties
class ItemBase(SQLModel): class ItemBase(SQLModel):
title: str title: str = Field(min_length=1, max_length=255)
description: str | None = None description: str | None = Field(default=None, max_length=255)
# Properties to receive on item creation # Properties to receive on item creation
class ItemCreate(ItemBase): class ItemCreate(ItemBase):
title: str pass
# Properties to receive on item update # Properties to receive on item update
class ItemUpdate(ItemBase): class ItemUpdate(ItemBase):
title: str | None = None # type: ignore title: str | None = Field(default=None, min_length=1, max_length=255) # type: ignore
# Database model, database table inferred from class name # Database model, database table inferred from class name
class Item(ItemBase, table=True): class Item(ItemBase, table=True):
id: int | None = Field(default=None, primary_key=True) id: uuid.UUID = Field(default_factory=uuid.uuid4, primary_key=True)
title: str title: str = Field(max_length=255)
owner_id: int | None = Field(default=None, foreign_key="user.id", nullable=False) owner_id: uuid.UUID = Field(
foreign_key="user.id", nullable=False, ondelete="CASCADE"
)
owner: User | None = Relationship(back_populates="items") owner: User | None = Relationship(back_populates="items")
# Properties to return via API, id is always required # Properties to return via API, id is always required
class ItemOut(ItemBase): class ItemPublic(ItemBase):
id: int id: uuid.UUID
owner_id: int owner_id: uuid.UUID
class ItemsOut(SQLModel): class ItemsPublic(SQLModel):
data: list[ItemOut] data: list[ItemPublic]
count: int count: int
@@ -105,9 +106,9 @@ class Token(SQLModel):
# Contents of JWT token # Contents of JWT token
class TokenPayload(SQLModel): class TokenPayload(SQLModel):
sub: int | None = None sub: str | None = None
class NewPassword(SQLModel): class NewPassword(SQLModel):
token: str token: str
new_password: str new_password: str = Field(min_length=8, max_length=40)
+13 -11
View File
@@ -1,3 +1,5 @@
import uuid
from fastapi.testclient import TestClient from fastapi.testclient import TestClient
from sqlmodel import Session from sqlmodel import Session
@@ -6,7 +8,7 @@ from app.tests.utils.item import create_random_item
def test_create_item( def test_create_item(
client: TestClient, superuser_token_headers: dict[str, str], db: Session client: TestClient, superuser_token_headers: dict[str, str]
) -> None: ) -> None:
data = {"title": "Foo", "description": "Fighters"} data = {"title": "Foo", "description": "Fighters"}
response = client.post( response = client.post(
@@ -34,15 +36,15 @@ def test_read_item(
content = response.json() content = response.json()
assert content["title"] == item.title assert content["title"] == item.title
assert content["description"] == item.description assert content["description"] == item.description
assert content["id"] == item.id assert content["id"] == str(item.id)
assert content["owner_id"] == item.owner_id assert content["owner_id"] == str(item.owner_id)
def test_read_item_not_found( def test_read_item_not_found(
client: TestClient, superuser_token_headers: dict[str, str], db: Session client: TestClient, superuser_token_headers: dict[str, str]
) -> None: ) -> None:
response = client.get( response = client.get(
f"{settings.API_V1_STR}/items/999", f"{settings.API_V1_STR}/items/{uuid.uuid4()}",
headers=superuser_token_headers, headers=superuser_token_headers,
) )
assert response.status_code == 404 assert response.status_code == 404
@@ -91,16 +93,16 @@ def test_update_item(
content = response.json() content = response.json()
assert content["title"] == data["title"] assert content["title"] == data["title"]
assert content["description"] == data["description"] assert content["description"] == data["description"]
assert content["id"] == item.id assert content["id"] == str(item.id)
assert content["owner_id"] == item.owner_id assert content["owner_id"] == str(item.owner_id)
def test_update_item_not_found( def test_update_item_not_found(
client: TestClient, superuser_token_headers: dict[str, str], db: Session client: TestClient, superuser_token_headers: dict[str, str]
) -> None: ) -> None:
data = {"title": "Updated title", "description": "Updated description"} data = {"title": "Updated title", "description": "Updated description"}
response = client.put( response = client.put(
f"{settings.API_V1_STR}/items/999", f"{settings.API_V1_STR}/items/{uuid.uuid4()}",
headers=superuser_token_headers, headers=superuser_token_headers,
json=data, json=data,
) )
@@ -138,10 +140,10 @@ def test_delete_item(
def test_delete_item_not_found( def test_delete_item_not_found(
client: TestClient, superuser_token_headers: dict[str, str], db: Session client: TestClient, superuser_token_headers: dict[str, str]
) -> None: ) -> None:
response = client.delete( response = client.delete(
f"{settings.API_V1_STR}/items/999", f"{settings.API_V1_STR}/items/{uuid.uuid4()}",
headers=superuser_token_headers, headers=superuser_token_headers,
) )
assert response.status_code == 404 assert response.status_code == 404
+42 -18
View File
@@ -1,7 +1,14 @@
from unittest.mock import patch
from fastapi.testclient import TestClient from fastapi.testclient import TestClient
from pytest_mock import MockerFixture from sqlmodel import Session
from app.core.config import settings from app.core.config import settings
from app.core.security import verify_password
from app.crud import create_user
from app.models import UserCreate
from app.tests.utils.user import user_authentication_headers
from app.tests.utils.utils import random_email, random_lower_string
from app.utils import generate_password_reset_token from app.utils import generate_password_reset_token
@@ -39,18 +46,19 @@ def test_use_access_token(
def test_recovery_password( def test_recovery_password(
client: TestClient, normal_user_token_headers: dict[str, str], mocker: MockerFixture client: TestClient, normal_user_token_headers: dict[str, str]
) -> None: ) -> None:
mocker.patch("app.utils.send_email", return_value=None) with (
mocker.patch("app.core.config.settings.SMTP_HOST", "smtp.example.com") patch("app.core.config.settings.SMTP_HOST", "smtp.example.com"),
mocker.patch("app.core.config.settings.SMTP_USER", "admin@example.com") patch("app.core.config.settings.SMTP_USER", "admin@example.com"),
email = "test@example.com" ):
r = client.post( email = "test@example.com"
f"{settings.API_V1_STR}/password-recovery/{email}", r = client.post(
headers=normal_user_token_headers, f"{settings.API_V1_STR}/password-recovery/{email}",
) headers=normal_user_token_headers,
assert r.status_code == 200 )
assert r.json() == {"message": "Password recovery email sent"} assert r.status_code == 200
assert r.json() == {"message": "Password recovery email sent"}
def test_recovery_password_user_not_exits( def test_recovery_password_user_not_exits(
@@ -64,19 +72,35 @@ def test_recovery_password_user_not_exits(
assert r.status_code == 404 assert r.status_code == 404
def test_reset_password( def test_reset_password(client: TestClient, db: Session) -> None:
client: TestClient, superuser_token_headers: dict[str, str] email = random_email()
) -> None: password = random_lower_string()
token = generate_password_reset_token(email=settings.FIRST_SUPERUSER) new_password = random_lower_string()
data = {"new_password": "changethis", "token": token}
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( r = client.post(
f"{settings.API_V1_STR}/reset-password/", f"{settings.API_V1_STR}/reset-password/",
headers=superuser_token_headers, headers=headers,
json=data, json=data,
) )
assert r.status_code == 200 assert r.status_code == 200
assert r.json() == {"message": "Password updated successfully"} assert r.json() == {"message": "Password updated successfully"}
db.refresh(user)
assert verify_password(new_password, user.hashed_password)
def test_reset_password_invalid_token( def test_reset_password_invalid_token(
client: TestClient, superuser_token_headers: dict[str, str] client: TestClient, superuser_token_headers: dict[str, str]
@@ -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"
+105 -74
View File
@@ -1,10 +1,13 @@
import uuid
from unittest.mock import patch
from fastapi.testclient import TestClient from fastapi.testclient import TestClient
from pytest_mock import MockerFixture from sqlmodel import Session, select
from sqlmodel import Session
from app import crud from app import crud
from app.core.config import settings from app.core.config import settings
from app.models import UserCreate from app.core.security import verify_password
from app.models import User, UserCreate
from app.tests.utils.utils import random_email, random_lower_string from app.tests.utils.utils import random_email, random_lower_string
@@ -31,27 +34,26 @@ def test_get_users_normal_user_me(
def test_create_user_new_email( def test_create_user_new_email(
client: TestClient, client: TestClient, superuser_token_headers: dict[str, str], db: Session
superuser_token_headers: dict[str, str],
db: Session,
mocker: MockerFixture,
) -> None: ) -> None:
mocker.patch("app.utils.send_email") with (
mocker.patch("app.core.config.settings.SMTP_HOST", "smtp.example.com") patch("app.utils.send_email", return_value=None),
mocker.patch("app.core.config.settings.SMTP_USER", "admin@example.com") patch("app.core.config.settings.SMTP_HOST", "smtp.example.com"),
username = random_email() patch("app.core.config.settings.SMTP_USER", "admin@example.com"),
password = random_lower_string() ):
data = {"email": username, "password": password} username = random_email()
r = client.post( password = random_lower_string()
f"{settings.API_V1_STR}/users/", data = {"email": username, "password": password}
headers=superuser_token_headers, r = client.post(
json=data, f"{settings.API_V1_STR}/users/",
) headers=superuser_token_headers,
assert 200 <= r.status_code < 300 json=data,
created_user = r.json() )
user = crud.get_user_by_email(session=db, email=username) assert 200 <= r.status_code < 300
assert user created_user = r.json()
assert user.email == created_user["email"] user = crud.get_user_by_email(session=db, email=username)
assert user
assert user.email == created_user["email"]
def test_get_existing_user( def test_get_existing_user(
@@ -101,10 +103,10 @@ def test_get_existing_user_current_user(client: TestClient, db: Session) -> None
def test_get_existing_user_permissions_error( def test_get_existing_user_permissions_error(
client: TestClient, normal_user_token_headers: dict[str, str], db: Session client: TestClient, normal_user_token_headers: dict[str, str]
) -> None: ) -> None:
r = client.get( r = client.get(
f"{settings.API_V1_STR}/users/999999", f"{settings.API_V1_STR}/users/{uuid.uuid4()}",
headers=normal_user_token_headers, headers=normal_user_token_headers,
) )
assert r.status_code == 403 assert r.status_code == 403
@@ -141,7 +143,7 @@ def test_create_user_by_normal_user(
headers=normal_user_token_headers, headers=normal_user_token_headers,
json=data, json=data,
) )
assert r.status_code == 400 assert r.status_code == 403
def test_retrieve_users( def test_retrieve_users(
@@ -182,6 +184,12 @@ def test_update_user_me(
assert updated_user["email"] == email assert updated_user["email"] == email
assert updated_user["full_name"] == full_name 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( def test_update_password_me(
client: TestClient, superuser_token_headers: dict[str, str], db: Session client: TestClient, superuser_token_headers: dict[str, str], db: Session
@@ -200,6 +208,12 @@ def test_update_password_me(
updated_user = r.json() updated_user = r.json()
assert updated_user["message"] == "Password updated successfully" 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
assert verify_password(new_password, user_db.hashed_password)
# Revert to the old password to keep consistency in test # Revert to the old password to keep consistency in test
old_data = { old_data = {
"current_password": new_password, "current_password": new_password,
@@ -210,11 +224,14 @@ def test_update_password_me(
headers=superuser_token_headers, headers=superuser_token_headers,
json=old_data, json=old_data,
) )
db.refresh(user_db)
assert r.status_code == 200 assert r.status_code == 200
assert verify_password(settings.FIRST_SUPERUSER_PASSWORD, user_db.hashed_password)
def test_update_password_me_incorrect_password( def test_update_password_me_incorrect_password(
client: TestClient, superuser_token_headers: dict[str, str], db: Session client: TestClient, superuser_token_headers: dict[str, str]
) -> None: ) -> None:
new_password = random_lower_string() new_password = random_lower_string()
data = {"current_password": new_password, "new_password": new_password} data = {"current_password": new_password, "new_password": new_password}
@@ -247,7 +264,7 @@ def test_update_user_me_email_exists(
def test_update_password_me_same_password_error( def test_update_password_me_same_password_error(
client: TestClient, superuser_token_headers: dict[str, str], db: Session client: TestClient, superuser_token_headers: dict[str, str]
) -> None: ) -> None:
data = { data = {
"current_password": settings.FIRST_SUPERUSER_PASSWORD, "current_password": settings.FIRST_SUPERUSER_PASSWORD,
@@ -265,14 +282,13 @@ def test_update_password_me_same_password_error(
) )
def test_create_user_open(client: TestClient, mocker: MockerFixture) -> None: def test_register_user(client: TestClient, db: Session) -> None:
mocker.patch("app.core.config.settings.USERS_OPEN_REGISTRATION", True)
username = random_email() username = random_email()
password = random_lower_string() password = random_lower_string()
full_name = random_lower_string() full_name = random_lower_string()
data = {"email": username, "password": password, "full_name": full_name} data = {"email": username, "password": password, "full_name": full_name}
r = client.post( r = client.post(
f"{settings.API_V1_STR}/users/open", f"{settings.API_V1_STR}/users/signup",
json=data, json=data,
) )
assert r.status_code == 200 assert r.status_code == 200
@@ -280,27 +296,15 @@ def test_create_user_open(client: TestClient, mocker: MockerFixture) -> None:
assert created_user["email"] == username assert created_user["email"] == username
assert created_user["full_name"] == full_name assert created_user["full_name"] == full_name
user_query = select(User).where(User.email == username)
def test_create_user_open_forbidden_error( user_db = db.exec(user_query).first()
client: TestClient, mocker: MockerFixture assert user_db
) -> None: assert user_db.email == username
mocker.patch("app.core.config.settings.USERS_OPEN_REGISTRATION", False) assert user_db.full_name == full_name
username = random_email() assert verify_password(password, user_db.hashed_password)
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/open",
json=data,
)
assert r.status_code == 403
assert r.json()["detail"] == "Open user registration is forbidden on this server"
def test_create_user_open_already_exists_error( def test_register_user_already_exists_error(client: TestClient) -> None:
client: TestClient, mocker: MockerFixture
) -> None:
mocker.patch("app.core.config.settings.USERS_OPEN_REGISTRATION", True)
password = random_lower_string() password = random_lower_string()
full_name = random_lower_string() full_name = random_lower_string()
data = { data = {
@@ -309,7 +313,7 @@ def test_create_user_open_already_exists_error(
"full_name": full_name, "full_name": full_name,
} }
r = client.post( r = client.post(
f"{settings.API_V1_STR}/users/open", f"{settings.API_V1_STR}/users/signup",
json=data, json=data,
) )
assert r.status_code == 400 assert r.status_code == 400
@@ -332,15 +336,22 @@ def test_update_user(
) )
assert r.status_code == 200 assert r.status_code == 200
updated_user = r.json() updated_user = r.json()
assert updated_user["full_name"] == "Updated_full_name" 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( def test_update_user_not_exists(
client: TestClient, superuser_token_headers: dict[str, str], db: Session client: TestClient, superuser_token_headers: dict[str, str]
) -> None: ) -> None:
data = {"full_name": "Updated_full_name"} data = {"full_name": "Updated_full_name"}
r = client.patch( r = client.patch(
f"{settings.API_V1_STR}/users/99999999", f"{settings.API_V1_STR}/users/{uuid.uuid4()}",
headers=superuser_token_headers, headers=superuser_token_headers,
json=data, json=data,
) )
@@ -371,24 +382,7 @@ def test_update_user_email_exists(
assert r.json()["detail"] == "User with this email already exists" assert r.json()["detail"] == "User with this email already exists"
def test_delete_user_super_user( def test_delete_user_me(client: TestClient, db: Session) -> None:
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"
def test_delete_user_current_user(client: TestClient, db: Session) -> None:
username = random_email() username = random_email()
password = random_lower_string() password = random_lower_string()
user_in = UserCreate(email=username, password=password) user_in = UserCreate(email=username, password=password)
@@ -405,19 +399,56 @@ def test_delete_user_current_user(client: TestClient, db: Session) -> None:
headers = {"Authorization": f"Bearer {a_token}"} headers = {"Authorization": f"Bearer {a_token}"}
r = client.delete( r = client.delete(
f"{settings.API_V1_STR}/users/{user_id}", f"{settings.API_V1_STR}/users/me",
headers=headers, headers=headers,
) )
assert r.status_code == 200 assert r.status_code == 200
deleted_user = r.json() deleted_user = r.json()
assert deleted_user["message"] == "User deleted successfully" 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( def test_delete_user_not_found(
client: TestClient, superuser_token_headers: dict[str, str], db: Session client: TestClient, superuser_token_headers: dict[str, str]
) -> None: ) -> None:
r = client.delete( r = client.delete(
f"{settings.API_V1_STR}/users/99999999", f"{settings.API_V1_STR}/users/{uuid.uuid4()}",
headers=superuser_token_headers, headers=superuser_token_headers,
) )
assert r.status_code == 404 assert r.status_code == 404
@@ -1,33 +1,33 @@
from unittest.mock import MagicMock from unittest.mock import MagicMock, patch
from pytest_mock import MockerFixture
from sqlmodel import select from sqlmodel import select
from app.backend_pre_start import init, logger from app.backend_pre_start import init, logger
def test_init_successful_connection(mocker: MockerFixture) -> None: def test_init_successful_connection() -> None:
engine_mock = MagicMock() engine_mock = MagicMock()
session_mock = MagicMock() session_mock = MagicMock()
exec_mock = MagicMock(return_value=True) exec_mock = MagicMock(return_value=True)
session_mock.configure_mock(**{"exec.return_value": exec_mock}) session_mock.configure_mock(**{"exec.return_value": exec_mock})
mocker.patch("sqlmodel.Session", return_value=session_mock)
mocker.patch.object(logger, "info") with (
mocker.patch.object(logger, "error") patch("sqlmodel.Session", return_value=session_mock),
mocker.patch.object(logger, "warn") patch.object(logger, "info"),
patch.object(logger, "error"),
patch.object(logger, "warn"),
):
try:
init(engine_mock)
connection_successful = True
except Exception:
connection_successful = False
try: assert (
init(engine_mock) connection_successful
connection_successful = True ), "The database connection should be successful and not raise an exception."
except Exception:
connection_successful = False
assert ( assert session_mock.exec.called_once_with(
connection_successful select(1)
), "The database connection should be successful and not raise an exception." ), "The session should execute a select statement once."
assert session_mock.exec.called_once_with(
select(1)
), "The session should execute a select statement once."
@@ -1,33 +1,33 @@
from unittest.mock import MagicMock from unittest.mock import MagicMock, patch
from pytest_mock import MockerFixture
from sqlmodel import select from sqlmodel import select
from app.tests_pre_start import init, logger from app.tests_pre_start import init, logger
def test_init_successful_connection(mocker: MockerFixture) -> None: def test_init_successful_connection() -> None:
engine_mock = MagicMock() engine_mock = MagicMock()
session_mock = MagicMock() session_mock = MagicMock()
exec_mock = MagicMock(return_value=True) exec_mock = MagicMock(return_value=True)
session_mock.configure_mock(**{"exec.return_value": exec_mock}) session_mock.configure_mock(**{"exec.return_value": exec_mock})
mocker.patch("sqlmodel.Session", return_value=session_mock)
mocker.patch.object(logger, "info") with (
mocker.patch.object(logger, "error") patch("sqlmodel.Session", return_value=session_mock),
mocker.patch.object(logger, "warn") patch.object(logger, "info"),
patch.object(logger, "error"),
patch.object(logger, "warn"),
):
try:
init(engine_mock)
connection_successful = True
except Exception:
connection_successful = False
try: assert (
init(engine_mock) connection_successful
connection_successful = True ), "The database connection should be successful and not raise an exception."
except Exception:
connection_successful = False
assert ( assert session_mock.exec.called_once_with(
connection_successful select(1)
), "The database connection should be successful and not raise an exception." ), "The session should execute a select statement once."
assert session_mock.exec.called_once_with(
select(1)
), "The session should execute a select statement once."
+16 -9
View File
@@ -1,15 +1,20 @@
import logging import logging
from dataclasses import dataclass from dataclasses import dataclass
from datetime import datetime, timedelta from datetime import datetime, timedelta, timezone
from pathlib import Path from pathlib import Path
from typing import Any from typing import Any
import emails # type: ignore import emails # type: ignore
import jwt
from jinja2 import Template from jinja2 import Template
from jose import JWTError, jwt from jwt.exceptions import InvalidTokenError
from app.core import security
from app.core.config import settings from app.core.config import settings
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
@dataclass @dataclass
class EmailData: class EmailData:
@@ -47,7 +52,7 @@ def send_email(
if settings.SMTP_PASSWORD: if settings.SMTP_PASSWORD:
smtp_options["password"] = settings.SMTP_PASSWORD smtp_options["password"] = settings.SMTP_PASSWORD
response = message.send(to=email_to, smtp=smtp_options) response = message.send(to=email_to, smtp=smtp_options)
logging.info(f"send email result: {response}") logger.info(f"send email result: {response}")
def generate_test_email(email_to: str) -> EmailData: def generate_test_email(email_to: str) -> EmailData:
@@ -63,7 +68,7 @@ def generate_test_email(email_to: str) -> EmailData:
def generate_reset_password_email(email_to: str, email: str, token: str) -> EmailData: def generate_reset_password_email(email_to: str, email: str, token: str) -> EmailData:
project_name = settings.PROJECT_NAME project_name = settings.PROJECT_NAME
subject = f"{project_name} - Password recovery for user {email}" subject = f"{project_name} - Password recovery for user {email}"
link = f"{settings.server_host}/reset-password?token={token}" link = f"{settings.FRONTEND_HOST}/reset-password?token={token}"
html_content = render_email_template( html_content = render_email_template(
template_name="reset_password.html", template_name="reset_password.html",
context={ context={
@@ -89,7 +94,7 @@ def generate_new_account_email(
"username": username, "username": username,
"password": password, "password": password,
"email": email_to, "email": email_to,
"link": settings.server_host, "link": settings.FRONTEND_HOST,
}, },
) )
return EmailData(html_content=html_content, subject=subject) return EmailData(html_content=html_content, subject=subject)
@@ -97,20 +102,22 @@ def generate_new_account_email(
def generate_password_reset_token(email: str) -> str: def generate_password_reset_token(email: str) -> str:
delta = timedelta(hours=settings.EMAIL_RESET_TOKEN_EXPIRE_HOURS) delta = timedelta(hours=settings.EMAIL_RESET_TOKEN_EXPIRE_HOURS)
now = datetime.utcnow() now = datetime.now(timezone.utc)
expires = now + delta expires = now + delta
exp = expires.timestamp() exp = expires.timestamp()
encoded_jwt = jwt.encode( encoded_jwt = jwt.encode(
{"exp": exp, "nbf": now, "sub": email}, {"exp": exp, "nbf": now, "sub": email},
settings.SECRET_KEY, settings.SECRET_KEY,
algorithm="HS256", algorithm=security.ALGORITHM,
) )
return encoded_jwt return encoded_jwt
def verify_password_reset_token(token: str) -> str | None: def verify_password_reset_token(token: str) -> str | None:
try: try:
decoded_token = jwt.decode(token, settings.SECRET_KEY, algorithms=["HS256"]) decoded_token = jwt.decode(
token, settings.SECRET_KEY, algorithms=[security.ALGORITHM]
)
return str(decoded_token["sub"]) return str(decoded_token["sub"])
except JWTError: except InvalidTokenError:
return None return None
-2257
View File
File diff suppressed because it is too large Load Diff
+35 -42
View File
@@ -1,57 +1,49 @@
[tool.poetry] [project]
name = "app" name = "app"
version = "0.1.0" version = "0.1.0"
description = "" description = ""
authors = ["Admin <admin@example.com>"] 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",
"passlib[bcrypt]<2.0.0,>=1.7.4",
"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",
# Pin bcrypt until passlib supports the latest
"bcrypt==4.0.1",
"pydantic-settings<3.0.0,>=2.2.1",
"sentry-sdk[fastapi]<2.0.0,>=1.40.6",
"pyjwt<3.0.0,>=2.8.0",
]
[tool.poetry.dependencies] [tool.uv]
python = "^3.10" dev-dependencies = [
uvicorn = {extras = ["standard"], version = "^0.24.0.post1"} "pytest<8.0.0,>=7.4.3",
fastapi = "^0.109.1" "mypy<2.0.0,>=1.8.0",
python-multipart = "^0.0.7" "ruff<1.0.0,>=0.2.2",
email-validator = "^2.1.0.post1" "pre-commit<4.0.0,>=3.6.2",
passlib = {extras = ["bcrypt"], version = "^1.7.4"} "types-passlib<2.0.0.0,>=1.7.7.20240106",
tenacity = "^8.2.3" "coverage<8.0.0,>=7.4.3",
pydantic = ">2.0" ]
emails = "^0.6"
gunicorn = "^21.2.0"
jinja2 = "^3.1.2"
alembic = "^1.12.1"
python-jose = {extras = ["cryptography"], version = "^3.3.0"}
httpx = "^0.25.1"
psycopg = {extras = ["binary"], version = "^3.1.13"}
sqlmodel = "^0.0.16"
# Pin bcrypt until passlib supports the latest
bcrypt = "4.0.1"
pydantic-settings = "^2.2.1"
sentry-sdk = {extras = ["fastapi"], version = "^1.40.6"}
[tool.poetry.group.dev.dependencies]
pytest = "^7.4.3"
pytest-cov = "^4.1.0"
mypy = "^1.8.0"
ruff = "^0.2.2"
pre-commit = "^3.6.2"
pytest-mock = "^3.12.0"
types-python-jose = "^3.3.4.20240106"
types-passlib = "^1.7.7.20240106"
[tool.isort]
multi_line_output = 3
include_trailing_comma = true
force_grid_wrap = 0
line_length = 88
[build-system] [build-system]
requires = ["poetry>=0.12"] requires = ["hatchling"]
build-backend = "poetry.masonry.api" build-backend = "hatchling.build"
[tool.mypy] [tool.mypy]
strict = true strict = true
exclude = ["venv", "alembic"] exclude = ["venv", ".venv", "alembic"]
[tool.ruff] [tool.ruff]
target-version = "py310" target-version = "py310"
exclude = ["alembic"]
[tool.ruff.lint] [tool.ruff.lint]
select = [ select = [
@@ -62,6 +54,7 @@ select = [
"B", # flake8-bugbear "B", # flake8-bugbear
"C4", # flake8-comprehensions "C4", # flake8-comprehensions
"UP", # pyupgrade "UP", # pyupgrade
"ARG001", # unused arguments in functions
] ]
ignore = [ ignore = [
"E501", # line too long, handled by black "E501", # line too long, handled by black
-6
View File
@@ -1,6 +0,0 @@
#!/bin/sh -e
set -x
# Sort imports one per line, so autoflake can remove unused imports
isort --recursive --force-single-line-imports --apply app
sh ./scripts/format.sh
+2 -3
View File
@@ -1,6 +1,5 @@
#!/bin/sh -e #!/bin/sh -e
set -x set -x
autoflake --remove-all-unused-imports --recursive --remove-unused-variables --in-place app --exclude=__init__.py ruff check app scripts --fix
black app ruff format app scripts
isort --recursive --apply app
+1 -1
View File
@@ -4,5 +4,5 @@ set -e
set -x set -x
mypy app mypy app
ruff app ruff check app
ruff format app --check ruff format app --check
@@ -1,10 +1,13 @@
#! /usr/bin/env bash #! /usr/bin/env bash
set -e
set -x
# Let the DB start # Let the DB start
python /app/app/backend_pre_start.py python app/backend_pre_start.py
# Run migrations # Run migrations
alembic upgrade head alembic upgrade head
# Create initial data in DB # Create initial data in DB
python /app/app/initial_data.py python app/initial_data.py
-6
View File
@@ -1,6 +0,0 @@
#!/usr/bin/env bash
set -e
set -x
bash scripts/test.sh --cov-report=html "${@}"
+7
View File
@@ -0,0 +1,7 @@
#! /usr/bin/env bash
set -e
set -x
python app/tests_pre_start.py
bash scripts/test.sh "$@"
-7
View File
@@ -1,7 +0,0 @@
#! /usr/bin/env bash
set -e
set -x
python /app/app/tests_pre_start.py
bash ./scripts/test.sh "$@"
+1554
View File
File diff suppressed because it is too large Load Diff
+1 -3
View File
@@ -63,7 +63,6 @@ _exclude:
# Global # Global
- .vscode - .vscode
- .mypy_cache - .mypy_cache
- poetry.lock
# Python # Python
- __pycache__ - __pycache__
- app.egg-info - app.egg-info
@@ -71,7 +70,6 @@ _exclude:
- .mypy_cache - .mypy_cache
- .coverage - .coverage
- htmlcov - htmlcov
- poetry.lock
- .cache - .cache
- .venv - .venv
# Frontend # Frontend
@@ -99,4 +97,4 @@ _exclude:
_answers_file: .copier/.copier-answers.yml _answers_file: .copier/.copier-answers.yml
_tasks: _tasks:
- "python .copier/update_dotenv.py" - ["{{ _copier_python }}", .copier/update_dotenv.py]
+33 -15
View File
@@ -12,7 +12,7 @@ But you have to configure a couple things first. 🤓
* Have a remote server ready and available. * 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 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 `traefik.fastapi-project.example.com`, `adminer.fastapi-project.example.com`, etc. And also for `staging`, like `staging.fastapi-project.example.com`, `staging.adminer.fastapi-project.example.com`, etc. * 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). * Install and configure [Docker](https://docs.docker.com/engine/install/) on the remote server (Docker Engine, not Docker Desktop).
## Public Traefik ## Public Traefik
@@ -127,11 +127,12 @@ export DOMAIN=fastapi-project.example.com
You can set several variables, like: You can set several variables, like:
* `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. * `BACKEND_CORS_ORIGINS`: A list of allowed CORS origins separated by commas.
* `SECRET_KEY`: The secret key for the FastAPI project, used to sign tokens. * `SECRET_KEY`: The secret key for the FastAPI project, used to sign tokens.
* `FIRST_SUPERUSER`: The email of the first superuser, this superuser will be the one that can create new users. * `FIRST_SUPERUSER`: The email of the first superuser, this superuser will be the one that can create new users.
* `FIRST_SUPERUSER_PASSWORD`: The password of the first superuser. * `FIRST_SUPERUSER_PASSWORD`: The password of the first superuser.
* `USERS_OPEN_REGISTRATION`: Whether to allow open registration of 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_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_USER`: The SMTP server user to send emails.
* `SMTP_PASSWORD`: The SMTP server password to send emails. * `SMTP_PASSWORD`: The SMTP server password to send emails.
@@ -143,6 +144,13 @@ You can set several variables, like:
* `POSTGRES_DB`: The database name to use for this application. You can leave the default of `app`. * `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. * `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.
### Generate secret keys ### Generate secret keys
Some environment variables in the `.env` file have a default value of `changethis`. Some environment variables in the `.env` file have a default value of `changethis`.
@@ -175,22 +183,22 @@ There are already two environments configured, `staging` and `production`. 🚀
### Install GitHub Actions Runner ### Install GitHub Actions Runner
* On your remote server, if you are running as the `root` user, create a user for your GitHub Actions: * On your remote server, create a user for your GitHub Actions:
```bash ```bash
adduser github sudo adduser github
``` ```
* Add Docker permissions to the `github` user: * Add Docker permissions to the `github` user:
```bash ```bash
usermod -aG docker github sudo usermod -aG docker github
``` ```
* Temporarily switch to the `github` user: * Temporarily switch to the `github` user:
```bash ```bash
su - github sudo su - github
``` ```
* Go to the `github` user's home directory: * Go to the `github` user's home directory:
@@ -211,9 +219,15 @@ To make sure it runs on startup and continues running, you can install it as a s
exit exit
``` ```
After you do it, you would be on the `root` user again. And you will be on the previous directory, belonging to the `root` user. After you do it, you will be on the previous user again. And you will be on the previous directory, belonging to that user.
* Go to the `actions-runner` directory inside of the `github` user's home directory: 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 ```bash
cd /home/github/actions-runner cd /home/github/actions-runner
@@ -247,11 +261,15 @@ The current Github Actions workflows expect these secrets:
* `DOMAIN_PRODUCTION` * `DOMAIN_PRODUCTION`
* `DOMAIN_STAGING` * `DOMAIN_STAGING`
* `STACK_NAME_PRODUCTION`
* `STACK_NAME_STAGING`
* `EMAILS_FROM_EMAIL` * `EMAILS_FROM_EMAIL`
* `FIRST_SUPERUSER` * `FIRST_SUPERUSER`
* `FIRST_SUPERUSER_PASSWORD` * `FIRST_SUPERUSER_PASSWORD`
* `POSTGRES_PASSWORD` * `POSTGRES_PASSWORD`
* `SECRET_KEY` * `SECRET_KEY`
* `LATEST_CHANGES`
* `SMOKESHOW_AUTH_KEY`
## GitHub Action Deployment Workflows ## GitHub Action Deployment Workflows
@@ -272,20 +290,20 @@ Traefik UI: `https://traefik.fastapi-project.example.com`
### Production ### Production
Frontend: `https://fastapi-project.example.com` Frontend: `https://dashboard.fastapi-project.example.com`
Backend API docs: `https://fastapi-project.example.com/docs` Backend API docs: `https://api.fastapi-project.example.com/docs`
Backend API base URL: `https://fastapi-project.example.com/api/` Backend API base URL: `https://api.fastapi-project.example.com`
Adminer: `https://adminer.fastapi-project.example.com` Adminer: `https://adminer.fastapi-project.example.com`
### Staging ### Staging
Frontend: `https://staging.fastapi-project.example.com` Frontend: `https://dashboard.staging.fastapi-project.example.com`
Backend API docs: `https://staging.fastapi-project.example.com/docs` Backend API docs: `https://api.staging.fastapi-project.example.com/docs`
Backend API base URL: `https://staging.fastapi-project.example.com/api/` Backend API base URL: `https://api.staging.fastapi-project.example.com`
Adminer: `https://staging.adminer.fastapi-project.example.com` Adminer: `https://adminer.staging.fastapi-project.example.com`
+136 -57
View File
@@ -1,77 +1,100 @@
# FastAPI Project - Development # FastAPI Project - Development
## Development in `localhost` with a custom domain ## Docker Compose
You might want to use something different than `localhost` as the domain. For example, if you are having problems with cookies that need a subdomain, and Chrome is not allowing you to use `localhost`. * Start the local stack with Docker Compose:
In that case, you have two options: you could use the instructions to modify your system `hosts` file with the instructions below in **Development with a custom IP** or you can just use `localhost.tiangolo.com`, it is set up to point to `localhost` (to the IP `127.0.0.1`) and all its subdomains too. And as it is an actual domain, the browsers will store the cookies you set during development, etc. ```bash
docker compose watch
If you used the default CORS enabled domains while generating the project, `localhost.tiangolo.com` was configured to be allowed. If you didn't, you will need to add it to the list in the variable `BACKEND_CORS_ORIGINS` in the `.env` file.
To configure it in your stack, follow the section **Change the development "domain"** below, using the domain `localhost.tiangolo.com`.
After performing those steps you should be able to open: http://localhost.tiangolo.com and it will be served by your stack in `localhost`.
Check all the corresponding available URLs in the section at the end.
## Development with a custom IP
If you are running Docker in an IP address different than `127.0.0.1` (`localhost`), you will need to perform some additional steps. That will be the case if you are running a custom Virtual Machine or your Docker is located in a different machine in your network.
In that case, you will need to use a fake local domain (`dev.example.com`) and make your computer think that the domain is served by the custom IP (e.g. `192.168.99.150`).
If you have a custom domain like that, you need to add it to the list in the variable `BACKEND_CORS_ORIGINS` in the `.env` file.
* Open your `hosts` file with administrative privileges using a text editor:
* **Note for Windows**: If you are in Windows, open the main Windows menu, search for "notepad", right click on it, and select the option "open as Administrator" or similar. Then click the "File" menu, "Open file", go to the directory `c:\Windows\System32\Drivers\etc\`, select the option to show "All files" instead of only "Text (.txt) files", and open the `hosts` file.
* **Note for Mac and Linux**: Your `hosts` file is probably located at `/etc/hosts`, you can edit it in a terminal running `sudo nano /etc/hosts`.
* Additional to the contents it might have, add a new line with the custom IP (e.g. `192.168.99.150`) a space character, and your fake local domain: `dev.example.com`.
The new line might look like:
```
192.168.99.150 dev.example.com
``` ```
* Save the file. * Now you can open your browser and interact with these URLs:
* **Note for Windows**: Make sure you save the file as "All files", without an extension of `.txt`. By default, Windows tries to add the extension. Make sure the file is saved as is, without extension.
...that will make your computer think that the fake local domain is served by that custom IP, and when you open that URL in your browser, it will talk directly to your locally running server when it is asked to go to `dev.example.com` and think that it is a remote server while it is actually running in your computer. Frontend, built with Docker, with routes handled based on the path: http://localhost:5173
To configure it in your stack, follow the section **Change the development "domain"** below, using the domain `dev.example.com`. Backend, JSON based web API based on OpenAPI: http://localhost:8000
After performing those steps you should be able to open: http://dev.example.com and it will be server by your stack in `192.168.99.150`. Automatic interactive documentation with Swagger UI (from the OpenAPI backend): http://localhost:8000/docs
Check all the corresponding available URLs in the section at the end. Adminer, database web administration: http://localhost:8080
## Change the development "domain" Traefik UI, to see how the routes are being handled by the proxy: http://localhost:8090
If you need to use your local stack with a different domain than `localhost`, you need to make sure the domain you use points to the IP where your stack is set up. **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 simplify your Docker Compose setup, for example, so that the API docs (Swagger UI) knows where is your API, you should let it know you are using that domain for development. To check the logs, run (in another terminal):
* Open the file located at `./.env`. It would have a line like: ```bash
docker compose logs
```
DOMAIN=localhost
``` ```
* Change it to the domain you are going to use, e.g.: To check the logs of a specific service, add the name of the service, e.g.:
```bash
docker compose logs backend
``` ```
## 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
cd frontend
npm 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 DOMAIN=localhost.tiangolo.com
``` ```
That variable will be used by the Docker Compose files. That will be used by the Docker Compose files to configure the base domain for the services.
After that, you can restart your stack with: 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 ```bash
docker compose up -d docker compose watch
``` ```
and check all the corresponding available URLs in the section at the end. 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 `docker-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 ## Docker Compose files and env vars
@@ -83,6 +106,12 @@ These Docker Compose files use the `.env` file containing configurations to be i
They also use some additional configurations taken from environment variables set in the scripts before calling the `docker compose` command. 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
The `.env` file is the one that contains all your configurations, generated keys and passwords, etc. The `.env` file is the one that contains all your configurations, generated keys and passwords, etc.
@@ -91,6 +120,52 @@ Depending on your workflow, you could want to exclude it from Git, for example i
One way to do it could be to add each environment variable to your CI/CD system, and updating the `docker-compose.yml` file to read that specific env var instead of reading the `.env` file. One way to do it could be to add each environment variable to your CI/CD system, and updating the `docker-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 [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 pre-commit to run automatically
`pre-commit` is already part of the dependencies of the project, but you could also install it globally if you prefer to, following [the official pre-commit docs](https://pre-commit.com/).
After having the `pre-commit` 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:
```bash
❯ uv run pre-commit install
pre-commit installed at .git/hooks/pre-commit
```
Now whenever you try to commit, e.g. with:
```bash
git commit
```
...pre-commit 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 pre-commit hooks manually
you can also run `pre-commit` manually on all the files, you can do it using `uv` with:
```bash
❯ uv run pre-commit run --all-files
check for added large files..............................................Passed
check toml...............................................................Passed
check yaml...............................................................Passed
ruff.....................................................................Passed
ruff-format..............................................................Passed
eslint...................................................................Passed
prettier.................................................................Passed
```
## URLs ## URLs
The production or staging URLs would use these same paths, but with your own domain. The production or staging URLs would use these same paths, but with your own domain.
@@ -99,30 +174,34 @@ The production or staging URLs would use these same paths, but with your own dom
Development URLs, for local development. Development URLs, for local development.
Frontend: http://localhost Frontend: http://localhost:5173
Backend: http://localhost/api/ Backend: http://localhost:8000
Automatic Interactive Docs (Swagger UI): https://localhost/docs Automatic Interactive Docs (Swagger UI): http://localhost:8000/docs
Automatic Alternative Docs (ReDoc): https://localhost/redoc Automatic Alternative Docs (ReDoc): http://localhost:8000/redoc
Adminer: http://localhost:8080 Adminer: http://localhost:8080
Traefik UI: http://localhost:8090 Traefik UI: http://localhost:8090
### Development in localhost with a custom domain URLs MailCatcher: http://localhost:1080
### Development URLs with `localhost.tiangolo.com` Configured
Development URLs, for local development. Development URLs, for local development.
Frontend: http://localhost.tiangolo.com Frontend: http://dashboard.localhost.tiangolo.com
Backend: http://localhost.tiangolo.com/api/ Backend: http://api.localhost.tiangolo.com
Automatic Interactive Docs (Swagger UI): https://localhost.tiangolo.com/docs Automatic Interactive Docs (Swagger UI): http://api.localhost.tiangolo.com/docs
Automatic Alternative Docs (ReDoc): https://localhost.tiangolo.com/redoc Automatic Alternative Docs (ReDoc): http://api.localhost.tiangolo.com/redoc
Adminer: http://localhost.tiangolo.com:8080 Adminer: http://localhost.tiangolo.com:8080
Traefik UI: http://localhost.tiangolo.com:8090 Traefik UI: http://localhost.tiangolo.com:8090
MailCatcher: http://localhost.tiangolo.com:1080
+67 -9
View File
@@ -1,8 +1,12 @@
version: "3.3"
services: 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: proxy:
image: traefik:v2.3 image: traefik:3.0
volumes: volumes:
- /var/run/docker.sock:/var/run/docker.sock - /var/run/docker.sock:/var/run/docker.sock
ports: ports:
@@ -37,6 +41,9 @@ services:
# Dummy https-redirect middleware that doesn't really redirect, only to # Dummy https-redirect middleware that doesn't really redirect, only to
# allow running it locally # allow running it locally
- traefik.http.middlewares.https-redirect.contenttype.autodetect=false - traefik.http.middlewares.https-redirect.contenttype.autodetect=false
networks:
- traefik-public
- default
db: db:
restart: "no" restart: "no"
@@ -51,24 +58,75 @@ services:
backend: backend:
restart: "no" restart: "no"
ports: ports:
- "8888:8888" - "8000:8000"
volumes:
- ./backend/:/app
build: build:
context: ./backend context: ./backend
args:
INSTALL_DEV: ${INSTALL_DEV-true}
# command: sleep infinity # Infinite loop to keep container alive doing nothing # command: sleep infinity # Infinite loop to keep container alive doing nothing
command: /start-reload.sh command:
- fastapi
- run
- --reload
- "app/main.py"
develop:
watch:
- path: ./backend
action: sync
target: /app
ignore:
- ./backend/.venv
- .venv
- path: ./backend/pyproject.toml
action: rebuild
# TODO: remove once coverage is done locally
volumes:
- ./backend/htmlcov:/app/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: frontend:
restart: "no" restart: "no"
ports:
- "5173:80"
build: build:
context: ./frontend context: ./frontend
args: args:
- VITE_API_URL=http://${DOMAIN?Variable not set} - VITE_API_URL=http://localhost:8000
- NODE_ENV=development - NODE_ENV=development
playwright:
build:
context: ./frontend
dockerfile: 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/blob-report
- ./frontend/test-results:/app/test-results
ports:
- 9323:9323
networks: networks:
traefik-public: traefik-public:
# For local dev, don't expect an external Traefik network # For local dev, don't expect an external Traefik network
+1 -1
View File
@@ -1,6 +1,6 @@
services: services:
traefik: traefik:
image: traefik:v2.3 image: traefik:3.0
ports: ports:
# Listen on port 80, default for HTTP, necessary to redirect to HTTPS # Listen on port 80, default for HTTP, necessary to redirect to HTTPS
- 80:80 - 80:80
+64 -26
View File
@@ -1,8 +1,14 @@
version: "3.3"
services: services:
db: db:
image: postgres:12 image: postgres:12
restart: always restart: always
healthcheck:
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER} -d ${POSTGRES_DB}"]
interval: 10s
retries: 5
start_period: 30s
timeout: 10s
volumes: volumes:
- app-db-data:/var/lib/postgresql/data/pgdata - app-db-data:/var/lib/postgresql/data/pgdata
env_file: env_file:
@@ -36,24 +42,28 @@ services:
- traefik.http.routers.${STACK_NAME?Variable not set}-adminer-https.tls.certresolver=le - 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 - traefik.http.services.${STACK_NAME?Variable not set}-adminer.loadbalancer.server.port=8080
backend: prestart:
image: '${DOCKER_IMAGE_BACKEND?Variable not set}:${TAG-latest}' image: '${DOCKER_IMAGE_BACKEND?Variable not set}:${TAG-latest}'
restart: always build:
context: ./backend
networks: networks:
- traefik-public - traefik-public
- default - default
depends_on: depends_on:
- db db:
condition: service_healthy
restart: true
command: bash scripts/prestart.sh
env_file: env_file:
- .env - .env
environment: environment:
- DOMAIN=${DOMAIN} - DOMAIN=${DOMAIN}
- FRONTEND_HOST=${FRONTEND_HOST?Variable not set}
- ENVIRONMENT=${ENVIRONMENT} - ENVIRONMENT=${ENVIRONMENT}
- BACKEND_CORS_ORIGINS=${BACKEND_CORS_ORIGINS} - BACKEND_CORS_ORIGINS=${BACKEND_CORS_ORIGINS}
- SECRET_KEY=${SECRET_KEY?Variable not set} - SECRET_KEY=${SECRET_KEY?Variable not set}
- FIRST_SUPERUSER=${FIRST_SUPERUSER?Variable not set} - FIRST_SUPERUSER=${FIRST_SUPERUSER?Variable not set}
- FIRST_SUPERUSER_PASSWORD=${FIRST_SUPERUSER_PASSWORD?Variable not set} - FIRST_SUPERUSER_PASSWORD=${FIRST_SUPERUSER_PASSWORD?Variable not set}
- USERS_OPEN_REGISTRATION=${USERS_OPEN_REGISTRATION}
- SMTP_HOST=${SMTP_HOST} - SMTP_HOST=${SMTP_HOST}
- SMTP_USER=${SMTP_USER} - SMTP_USER=${SMTP_USER}
- SMTP_PASSWORD=${SMTP_PASSWORD} - SMTP_PASSWORD=${SMTP_PASSWORD}
@@ -65,27 +75,64 @@ services:
- POSTGRES_PASSWORD=${POSTGRES_PASSWORD?Variable not set} - POSTGRES_PASSWORD=${POSTGRES_PASSWORD?Variable not set}
- SENTRY_DSN=${SENTRY_DSN} - 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: build:
context: ./backend context: ./backend
args:
INSTALL_DEV: ${INSTALL_DEV-false}
labels: labels:
- traefik.enable=true - traefik.enable=true
- traefik.docker.network=traefik-public - traefik.docker.network=traefik-public
- traefik.constraint-label=traefik-public - traefik.constraint-label=traefik-public
- traefik.http.services.${STACK_NAME?Variable not set}-backend.loadbalancer.server.port=80 - 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(`${DOMAIN?Variable not set}`, `www.${DOMAIN?Variable not set}`) && PathPrefix(`/api`, `/docs`, `/redoc`) - 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-http.entrypoints=http
- traefik.http.routers.${STACK_NAME?Variable not set}-backend-https.rule=Host(`${DOMAIN?Variable not set}`, `www.${DOMAIN?Variable not set}`) && PathPrefix(`/api`, `/docs`, `/redoc`) - 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.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=true
- traefik.http.routers.${STACK_NAME?Variable not set}-backend-https.tls.certresolver=le - traefik.http.routers.${STACK_NAME?Variable not set}-backend-https.tls.certresolver=le
- traefik.http.routers.${STACK_NAME?Variable not set}-backend-http.middlewares=https-redirect,${STACK_NAME?Variable not set}-www-redirect # Enable redirection for HTTP and HTTPS
- traefik.http.routers.${STACK_NAME?Variable not set}-backend-https.middlewares=${STACK_NAME?Variable not set}-www-redirect - traefik.http.routers.${STACK_NAME?Variable not set}-backend-http.middlewares=https-redirect
frontend: frontend:
image: '${DOCKER_IMAGE_FRONTEND?Variable not set}:${TAG-latest}' image: '${DOCKER_IMAGE_FRONTEND?Variable not set}:${TAG-latest}'
@@ -96,7 +143,7 @@ services:
build: build:
context: ./frontend context: ./frontend
args: args:
- VITE_API_URL=https://${DOMAIN?Variable not set} - VITE_API_URL=https://api.${DOMAIN?Variable not set}
- NODE_ENV=production - NODE_ENV=production
labels: labels:
- traefik.enable=true - traefik.enable=true
@@ -105,25 +152,16 @@ services:
- traefik.http.services.${STACK_NAME?Variable not set}-frontend.loadbalancer.server.port=80 - 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(`${DOMAIN?Variable not set}`, `www.${DOMAIN?Variable not set}`) - 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-http.entrypoints=http
- traefik.http.routers.${STACK_NAME?Variable not set}-frontend-https.rule=Host(`${DOMAIN?Variable not set}`, `www.${DOMAIN?Variable not set}`) - 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.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=true
- traefik.http.routers.${STACK_NAME?Variable not set}-frontend-https.tls.certresolver=le - traefik.http.routers.${STACK_NAME?Variable not set}-frontend-https.tls.certresolver=le
# Handle domain with and without "www" to redirect to only one # Enable redirection for HTTP and HTTPS
# To disable www redirection remove the next line - traefik.http.routers.${STACK_NAME?Variable not set}-frontend-http.middlewares=https-redirect
- traefik.http.middlewares.${STACK_NAME?Variable not set}-www-redirect.redirectregex.regex=^http(s)?://www.(${DOMAIN?Variable not set})/(.*)
# Redirect a domain with www to non-www
# To disable it remove the next line
- traefik.http.middlewares.${STACK_NAME?Variable not set}-www-redirect.redirectregex.replacement=http$${1}://${DOMAIN?Variable not set}/$${3}
# Middleware to redirect www, to disable it remove the next line
- traefik.http.routers.${STACK_NAME?Variable not set}-frontend-https.middlewares=${STACK_NAME?Variable not set}-www-redirect
# Middleware to redirect www, and redirect HTTP to HTTPS
# to disable www redirection remove the section: ${STACK_NAME?Variable not set}-www-redirect,
- traefik.http.routers.${STACK_NAME?Variable not set}-frontend-http.middlewares=https-redirect,${STACK_NAME?Variable not set}-www-redirect
volumes: volumes:
app-db-data: app-db-data:
+2 -1
View File
@@ -1 +1,2 @@
VITE_API_URL=http://localhost VITE_API_URL=http://localhost:8000
MAILCATCHER_HOST=http://localhost:1080
-18
View File
@@ -1,18 +0,0 @@
module.exports = {
root: true,
env: { browser: true, es2020: true },
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:react-hooks/recommended',
],
ignorePatterns: ['dist', '.eslintrc.cjs'],
parser: '@typescript-eslint/parser',
plugins: ['react-refresh'],
rules: {
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true },
],
},
}
+5
View File
@@ -23,3 +23,8 @@ openapi.json
*.njsproj *.njsproj
*.sln *.sln
*.sw? *.sw?
/test-results/
/playwright-report/
/blob-report/
/playwright/.cache/
/playwright/.auth/
+1 -1
View File
@@ -1 +1 @@
18.x.x 20
-1
View File
@@ -1 +0,0 @@
src/client/
-8
View File
@@ -1,8 +0,0 @@
{
"bracketSpacing": true,
"semi": false,
"singleQuote": true,
"trailingComma": "all",
"printWidth": 80,
"tabWidth": 2
}
+1 -1
View File
@@ -1,5 +1,5 @@
# Stage 0, "build-stage", based on Node.js, to build and compile the frontend # Stage 0, "build-stage", based on Node.js, to build and compile the frontend
FROM node:20 as build-stage FROM node:20 AS build-stage
WORKDIR /app WORKDIR /app
+13
View File
@@ -0,0 +1,13 @@
FROM node:20
WORKDIR /app
COPY package*.json /app/
RUN npm install
RUN npx -y playwright install --with-deps
COPY ./ /app/
ARG VITE_API_URL=${VITE_API_URL}
+47 -10
View File
@@ -4,7 +4,7 @@ The frontend is built with [Vite](https://vitejs.dev/), [React](https://reactjs.
## Frontend development ## Frontend development
Before you begin, ensure that you have either the Node Version Manager (nvm) or Fast Node Manager (fnm) installed on your system. Before you begin, ensure that you have either the Node Version Manager (nvm) or Fast Node Manager (fnm) installed on your system.
* To install fnm follow the [official fnm guide](https://github.com/Schniz/fnm#installation). If you prefer nvm, you can install it using the [official nvm guide](https://github.com/nvm-sh/nvm#installing-and-updating). * To install fnm follow the [official fnm guide](https://github.com/Schniz/fnm#installation). If you prefer nvm, you can install it using the [official nvm guide](https://github.com/nvm-sh/nvm#installing-and-updating).
@@ -27,7 +27,7 @@ nvm install
```bash ```bash
# If using fnm # If using fnm
fnm use fnm use
# If using nvm # If using nvm
nvm use nvm use
@@ -59,7 +59,7 @@ If you are developing an API-only app and want to remove the frontend, you can d
* In the `docker-compose.yml` file, remove the whole service / section `frontend`. * In the `docker-compose.yml` file, remove the whole service / section `frontend`.
* In the `docker-compose.override.yml` file, remove the whole service / section `frontend`. * In the `docker-compose.override.yml` file, remove the whole service / section `frontend` and `playwright`.
Done, you have a frontend-less (api-only) app. 🤓 Done, you have a frontend-less (api-only) app. 🤓
@@ -74,16 +74,23 @@ But it would be only to clean them up, leaving them won't really have any effect
## Generate Client ## Generate Client
### Automatically
* Activate the backend virtual environment.
* From the top level project directory, run the script:
```bash
./scripts/generate-client.sh
```
* Commit the changes.
### Manually
* Start the Docker Compose stack. * 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. * 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 simplify the names in the generated frontend client code, modify the `openapi.json` file by running the following script:
```bash
node modify-openapi-operationids.js
```
* To generate the frontend client, run: * To generate the frontend client, run:
```bash ```bash
@@ -99,7 +106,7 @@ Notice that everytime the backend changes (changing the OpenAPI schema), you sho
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: 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 ```env
VITE_API_URL=https://my-remote-api.example.com 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. Then, when you run the frontend, it will use that URL as the base URL for the API.
@@ -115,3 +122,33 @@ The frontend code is structured as follows:
* `frontend/src/hooks` - Custom hooks. * `frontend/src/hooks` - Custom hooks.
* `frontend/src/routes` - The different routes of the frontend which include the pages. * `frontend/src/routes` - The different routes of the frontend which include the pages.
* `theme.tsx` - The Chakra UI custom theme. * `theme.tsx` - The Chakra UI custom theme.
## 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
npx playwright test
```
You can also run your tests in UI mode to see the browser and interact with it running:
```bash
npx 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).
+36
View File
@@ -0,0 +1,36 @@
{
"$schema": "https://biomejs.dev/schemas/1.6.1/schema.json",
"organizeImports": {
"enabled": true
},
"files": {
"ignore": [
"node_modules",
"src/routeTree.gen.ts",
"playwright.config.ts",
"playwright-report"
]
},
"linter": {
"enabled": true,
"rules": {
"recommended": true,
"suspicious": {
"noExplicitAny": "off",
"noArrayIndexKey": "off"
},
"style": {
"noNonNullAssertion": "off"
}
}
},
"formatter": {
"indentStyle": "space"
},
"javascript": {
"formatter": {
"quoteStyle": "double",
"semicolons": "asNeeded"
}
}
}
+1 -1
View File
@@ -5,7 +5,7 @@
<link rel="icon" type="image/svg+xml" href="/vite.svg" /> <link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Full Stack FastAPI Project</title> <title>Full Stack FastAPI Project</title>
<link rel="icon" type="image/x-icon" href="./src/assets/images/favicon.png" /> <link rel="icon" type="image/x-icon" href="/assets/images/favicon.png" />
</head> </head>
<body> <body>
<div id="root"></div> <div id="root"></div>
-29
View File
@@ -1,29 +0,0 @@
import * as fs from "fs";
const filePath = "./openapi.json";
fs.readFile(filePath, (err, data) => {
const openapiContent = JSON.parse(data);
if (err) throw err;
const paths = openapiContent.paths;
Object.keys(paths).forEach((pathKey) => {
const pathData = paths[pathKey];
Object.keys(pathData).forEach((method) => {
const operation = pathData[method];
if (operation.tags && operation.tags.length > 0) {
const tag = operation.tags[0];
const operationId = operation.operationId;
const toRemove = `${tag}-`;
if (operationId.startsWith(toRemove)) {
const newOperationId = operationId.substring(toRemove.length);
operation.operationId = newOperationId;
}
}
});
});
fs.writeFile(filePath, JSON.stringify(openapiContent, null, 2), (err) => {
if (err) throw err;
});
});
+1 -1
View File
@@ -4,7 +4,7 @@ server {
location / { location / {
root /usr/share/nginx/html; root /usr/share/nginx/html;
index index.html index.htm; index index.html index.htm;
try_files $uri $uri/ /index.html =404; try_files $uri /index.html =404;
} }
include /etc/nginx/extra-conf.d/*.conf; include /etc/nginx/extra-conf.d/*.conf;
+28
View File
@@ -0,0 +1,28 @@
import { defineConfig } from "@hey-api/openapi-ts"
export default defineConfig({
client: "legacy/axios",
input: "./openapi.json",
output: "./src/client",
// exportSchemas: true,
plugins: [
{
name: "@hey-api/sdk",
// NOTE: this doesn't allow tree-shaking
asClass: true,
operationId: true,
methodNameBuilder: (operation) => {
// @ts-ignore
let name: string = operation.name
// @ts-ignore
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)
},
},
],
})
+3508 -5642
View File
File diff suppressed because it is too large Load Diff
+17 -22
View File
@@ -5,43 +5,38 @@
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
"build": "tsc && vite build", "build": "tsc -p tsconfig.build.json && vite build",
"lint": "eslint ./src --ext .ts,.tsx --fix", "lint": "biome check --apply-unsafe --no-errors-on-unmatched --files-ignore-unknown=true ./",
"format": "prettier --write ./src/**/*.{ts,tsx,js,jsx,json,md} --ignore-path .prettierignore",
"preview": "vite preview", "preview": "vite preview",
"generate-client": "openapi --input ./openapi.json --useOptions --useUnionTypes --output ./src/client --client axios --exportSchemas true" "generate-client": "openapi-ts"
}, },
"dependencies": { "dependencies": {
"@chakra-ui/icons": "2.1.1", "@chakra-ui/react": "^3.8.0",
"@chakra-ui/react": "2.8.2", "@emotion/react": "^11.14.0",
"@emotion/react": "11.11.3", "@tanstack/react-query": "^5.28.14",
"@emotion/styled": "11.11.0", "@tanstack/react-query-devtools": "^5.28.14",
"@tanstack/react-router": "1.19.1", "@tanstack/react-router": "1.19.1",
"axios": "1.6.2", "axios": "1.7.4",
"form-data": "4.0.0", "form-data": "4.0.0",
"framer-motion": "10.16.16", "next-themes": "^0.4.4",
"react": "^18.2.0", "react": "^18.2.0",
"react-dom": "^18.2.0", "react-dom": "^18.2.0",
"react-error-boundary": "^4.0.13",
"react-hook-form": "7.49.3", "react-hook-form": "7.49.3",
"react-icons": "5.0.1", "react-icons": "^5.4.0"
"react-query": "3.39.3",
"zustand": "4.5.0"
}, },
"devDependencies": { "devDependencies": {
"@biomejs/biome": "1.6.1",
"@hey-api/openapi-ts": "^0.57.0",
"@playwright/test": "^1.45.2",
"@tanstack/router-devtools": "1.19.1", "@tanstack/router-devtools": "1.19.1",
"@tanstack/router-vite-plugin": "1.19.0", "@tanstack/router-vite-plugin": "1.19.0",
"@types/node": "20.10.5", "@types/node": "^20.10.5",
"@types/react": "^18.2.37", "@types/react": "^18.2.37",
"@types/react-dom": "^18.2.15", "@types/react-dom": "^18.2.15",
"@typescript-eslint/eslint-plugin": "^6.10.0",
"@typescript-eslint/parser": "^6.10.0",
"@vitejs/plugin-react-swc": "^3.5.0", "@vitejs/plugin-react-swc": "^3.5.0",
"eslint": "^8.53.0", "dotenv": "^16.4.5",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.4",
"openapi-typescript-codegen": "0.25.0",
"prettier": "3.2.5",
"typescript": "^5.2.2", "typescript": "^5.2.2",
"vite": "^5.0.12" "vite": "^5.4.14"
} }
} }
+91
View File
@@ -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: 'npm run dev',
url: 'http://localhost:5173',
reuseExistingServer: !process.env.CI,
},
});

Before

Width:  |  Height:  |  Size: 6.2 KiB

After

Width:  |  Height:  |  Size: 6.2 KiB

Before

Width:  |  Height:  |  Size: 4.9 KiB

After

Width:  |  Height:  |  Size: 4.9 KiB

+20 -20
View File
@@ -1,25 +1,25 @@
/* generated using openapi-typescript-codegen -- do no edit */ import type { ApiRequestOptions } from "./ApiRequestOptions"
/* istanbul ignore file */ import type { ApiResult } from "./ApiResult"
/* tslint:disable */
/* eslint-disable */
import type { ApiRequestOptions } from './ApiRequestOptions';
import type { ApiResult } from './ApiResult';
export class ApiError extends Error { export class ApiError extends Error {
public readonly url: string; public readonly url: string
public readonly status: number; public readonly status: number
public readonly statusText: string; public readonly statusText: string
public readonly body: any; public readonly body: unknown
public readonly request: ApiRequestOptions; public readonly request: ApiRequestOptions
constructor(request: ApiRequestOptions, response: ApiResult, message: string) { constructor(
super(message); request: ApiRequestOptions,
response: ApiResult,
message: string,
) {
super(message)
this.name = 'ApiError'; this.name = "ApiError"
this.url = response.url; this.url = response.url
this.status = response.status; this.status = response.status
this.statusText = response.statusText; this.statusText = response.statusText
this.body = response.body; this.body = response.body
this.request = request; this.request = request
} }
} }
+21 -17
View File
@@ -1,17 +1,21 @@
/* generated using openapi-typescript-codegen -- do no edit */ export type ApiRequestOptions<T = unknown> = {
/* istanbul ignore file */ readonly body?: any
/* tslint:disable */ readonly cookies?: Record<string, unknown>
/* eslint-disable */ readonly errors?: Record<number | string, string>
export type ApiRequestOptions = { readonly formData?: Record<string, unknown> | any[] | Blob | File
readonly method: 'GET' | 'PUT' | 'POST' | 'DELETE' | 'OPTIONS' | 'HEAD' | 'PATCH'; readonly headers?: Record<string, unknown>
readonly url: string; readonly mediaType?: string
readonly path?: Record<string, any>; readonly method:
readonly cookies?: Record<string, any>; | "DELETE"
readonly headers?: Record<string, any>; | "GET"
readonly query?: Record<string, any>; | "HEAD"
readonly formData?: Record<string, any>; | "OPTIONS"
readonly body?: any; | "PATCH"
readonly mediaType?: string; | "POST"
readonly responseHeader?: string; | "PUT"
readonly errors?: Record<number, string>; readonly path?: Record<string, unknown>
}; readonly query?: Record<string, unknown>
readonly responseHeader?: string
readonly responseTransformer?: (data: unknown) => Promise<T>
readonly url: string
}
+7 -11
View File
@@ -1,11 +1,7 @@
/* generated using openapi-typescript-codegen -- do no edit */ export type ApiResult<TData = any> = {
/* istanbul ignore file */ readonly body: TData
/* tslint:disable */ readonly ok: boolean
/* eslint-disable */ readonly status: number
export type ApiResult = { readonly statusText: string
readonly url: string; readonly url: string
readonly ok: boolean; }
readonly status: number;
readonly statusText: string;
readonly body: any;
};
+111 -116
View File
@@ -1,131 +1,126 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export class CancelError extends Error { export class CancelError extends Error {
constructor(message: string) {
super(message)
this.name = "CancelError"
}
constructor(message: string) { public get isCancelled(): boolean {
super(message); return true
this.name = 'CancelError'; }
}
public get isCancelled(): boolean {
return true;
}
} }
export interface OnCancel { export interface OnCancel {
readonly isResolved: boolean; readonly isResolved: boolean
readonly isRejected: boolean; readonly isRejected: boolean
readonly isCancelled: boolean; readonly isCancelled: boolean
(cancelHandler: () => void): void; (cancelHandler: () => void): void
} }
export class CancelablePromise<T> implements Promise<T> { export class CancelablePromise<T> implements Promise<T> {
#isResolved: boolean; private _isResolved: boolean
#isRejected: boolean; private _isRejected: boolean
#isCancelled: boolean; private _isCancelled: boolean
readonly #cancelHandlers: (() => void)[]; readonly cancelHandlers: (() => void)[]
readonly #promise: Promise<T>; readonly promise: Promise<T>
#resolve?: (value: T | PromiseLike<T>) => void; private _resolve?: (value: T | PromiseLike<T>) => void
#reject?: (reason?: any) => void; private _reject?: (reason?: unknown) => void
constructor( constructor(
executor: ( executor: (
resolve: (value: T | PromiseLike<T>) => void, resolve: (value: T | PromiseLike<T>) => void,
reject: (reason?: any) => void, reject: (reason?: unknown) => void,
onCancel: OnCancel onCancel: OnCancel,
) => void ) => void,
) { ) {
this.#isResolved = false; this._isResolved = false
this.#isRejected = false; this._isRejected = false
this.#isCancelled = false; this._isCancelled = false
this.#cancelHandlers = []; this.cancelHandlers = []
this.#promise = new Promise<T>((resolve, reject) => { this.promise = new Promise<T>((resolve, reject) => {
this.#resolve = resolve; this._resolve = resolve
this.#reject = reject; this._reject = reject
const onResolve = (value: T | PromiseLike<T>): void => { const onResolve = (value: T | PromiseLike<T>): void => {
if (this.#isResolved || this.#isRejected || this.#isCancelled) { if (this._isResolved || this._isRejected || this._isCancelled) {
return; return
}
this.#isResolved = true;
this.#resolve?.(value);
};
const onReject = (reason?: any): void => {
if (this.#isResolved || this.#isRejected || this.#isCancelled) {
return;
}
this.#isRejected = true;
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<TResult1 = T, TResult2 = never>(
onFulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null,
onRejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null
): Promise<TResult1 | TResult2> {
return this.#promise.then(onFulfilled, onRejected);
}
public catch<TResult = never>(
onRejected?: ((reason: any) => TResult | PromiseLike<TResult>) | null
): Promise<T | TResult> {
return this.#promise.catch(onRejected);
}
public finally(onFinally?: (() => void) | null): Promise<T> {
return this.#promise.finally(onFinally);
}
public cancel(): void {
if (this.#isResolved || this.#isRejected || this.#isCancelled) {
return;
} }
this.#isCancelled = true; this._isResolved = true
if (this.#cancelHandlers.length) { if (this._resolve) this._resolve(value)
try { }
for (const cancelHandler of this.#cancelHandlers) {
cancelHandler();
}
} catch (error) {
console.warn('Cancellation threw an error', error);
return;
}
}
this.#cancelHandlers.length = 0;
this.#reject?.(new CancelError('Request aborted'));
}
public get isCancelled(): boolean { const onReject = (reason?: unknown): void => {
return this.#isCancelled; 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<TResult1 = T, TResult2 = never>(
onFulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null,
onRejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null,
): Promise<TResult1 | TResult2> {
return this.promise.then(onFulfilled, onRejected)
}
public catch<TResult = never>(
onRejected?: ((reason: unknown) => TResult | PromiseLike<TResult>) | null,
): Promise<T | TResult> {
return this.promise.catch(onRejected)
}
public finally(onFinally?: (() => void) | null): Promise<T> {
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
}
} }
+52 -27
View File
@@ -1,32 +1,57 @@
/* generated using openapi-typescript-codegen -- do no edit */ import type { AxiosRequestConfig, AxiosResponse } from "axios"
/* istanbul ignore file */ import type { ApiRequestOptions } from "./ApiRequestOptions"
/* tslint:disable */
/* eslint-disable */
import type { ApiRequestOptions } from './ApiRequestOptions';
type Resolver<T> = (options: ApiRequestOptions) => Promise<T>; type Headers = Record<string, string>
type Headers = Record<string, string>; type Middleware<T> = (value: T) => T | Promise<T>
type Resolver<T> = (options: ApiRequestOptions<T>) => Promise<T>
export class Interceptors<T> {
_fns: Middleware<T>[]
constructor() {
this._fns = []
}
eject(fn: Middleware<T>): 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<T>): void {
this._fns = [...this._fns, fn]
}
}
export type OpenAPIConfig = { export type OpenAPIConfig = {
BASE: string; BASE: string
VERSION: string; CREDENTIALS: "include" | "omit" | "same-origin"
WITH_CREDENTIALS: boolean; ENCODE_PATH?: ((path: string) => string) | undefined
CREDENTIALS: 'include' | 'omit' | 'same-origin'; HEADERS?: Headers | Resolver<Headers> | undefined
TOKEN?: string | Resolver<string> | undefined; PASSWORD?: string | Resolver<string> | undefined
USERNAME?: string | Resolver<string> | undefined; TOKEN?: string | Resolver<string> | undefined
PASSWORD?: string | Resolver<string> | undefined; USERNAME?: string | Resolver<string> | undefined
HEADERS?: Headers | Resolver<Headers> | undefined; VERSION: string
ENCODE_PATH?: ((path: string) => string) | undefined; WITH_CREDENTIALS: boolean
}; interceptors: {
request: Interceptors<AxiosRequestConfig>
response: Interceptors<AxiosResponse>
}
}
export const OpenAPI: OpenAPIConfig = { export const OpenAPI: OpenAPIConfig = {
BASE: '', BASE: "",
VERSION: '0.1.0', CREDENTIALS: "include",
WITH_CREDENTIALS: false, ENCODE_PATH: undefined,
CREDENTIALS: 'include', HEADERS: undefined,
TOKEN: undefined, PASSWORD: undefined,
USERNAME: undefined, TOKEN: undefined,
PASSWORD: undefined, USERNAME: undefined,
HEADERS: undefined, VERSION: "0.1.0",
ENCODE_PATH: undefined, WITH_CREDENTIALS: false,
}; interceptors: {
request: new Interceptors(),
response: new Interceptors(),
},
}
+335 -267
View File
@@ -1,283 +1,325 @@
/* generated using openapi-typescript-codegen -- do no edit */ import axios from "axios"
/* istanbul ignore file */ import type {
/* tslint:disable */ AxiosError,
/* eslint-disable */ AxiosRequestConfig,
import axios from 'axios'; AxiosResponse,
import type { AxiosError, AxiosRequestConfig, AxiosResponse, AxiosInstance } from 'axios'; AxiosInstance,
import FormData from 'form-data'; } from "axios"
import { ApiError } from './ApiError'; import { ApiError } from "./ApiError"
import type { ApiRequestOptions } from './ApiRequestOptions'; import type { ApiRequestOptions } from "./ApiRequestOptions"
import type { ApiResult } from './ApiResult'; import type { ApiResult } from "./ApiResult"
import { CancelablePromise } from './CancelablePromise'; import { CancelablePromise } from "./CancelablePromise"
import type { OnCancel } from './CancelablePromise'; import type { OnCancel } from "./CancelablePromise"
import type { OpenAPIConfig } from './OpenAPI'; import type { OpenAPIConfig } from "./OpenAPI"
export const isDefined = <T>(value: T | null | undefined): value is Exclude<T, null | undefined> => { export const isString = (value: unknown): value is string => {
return value !== undefined && value !== null; return typeof value === "string"
}; }
export const isString = (value: any): value is string => { export const isStringWithValue = (value: unknown): value is string => {
return typeof value === 'string'; return isString(value) && value !== ""
}; }
export const isStringWithValue = (value: any): value is string => {
return isString(value) && value !== '';
};
export const isBlob = (value: any): value is Blob => { export const isBlob = (value: any): value is Blob => {
return ( return value instanceof Blob
typeof value === 'object' && }
typeof value.type === 'string' &&
typeof value.stream === 'function' &&
typeof value.arrayBuffer === 'function' &&
typeof value.constructor === 'function' &&
typeof value.constructor.name === 'string' &&
/^(Blob|File)$/.test(value.constructor.name) &&
/^(Blob|File)$/.test(value[Symbol.toStringTag])
);
};
export const isFormData = (value: any): value is FormData => { export const isFormData = (value: unknown): value is FormData => {
return value instanceof FormData; return value instanceof FormData
}; }
export const isSuccess = (status: number): boolean => { export const isSuccess = (status: number): boolean => {
return status >= 200 && status < 300; return status >= 200 && status < 300
}; }
export const base64 = (str: string): string => { export const base64 = (str: string): string => {
try { try {
return btoa(str); return btoa(str)
} catch (err) { } catch (err) {
// @ts-ignore // @ts-ignore
return Buffer.from(str).toString('base64'); return Buffer.from(str).toString("base64")
} }
}; }
export const getQueryString = (params: Record<string, any>): string => { export const getQueryString = (params: Record<string, unknown>): string => {
const qs: string[] = []; const qs: string[] = []
const append = (key: string, value: any) => { const append = (key: string, value: unknown) => {
qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`); qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`)
}; }
const process = (key: string, value: any) => { const encodePair = (key: string, value: unknown) => {
if (isDefined(value)) { if (value === undefined || value === null) {
if (Array.isArray(value)) { return
value.forEach(v => {
process(key, v);
});
} else if (typeof value === 'object') {
Object.entries(value).forEach(([k, v]) => {
process(`${key}[${k}]`, v);
});
} else {
append(key, value);
}
}
};
Object.entries(params).forEach(([key, value]) => {
process(key, value);
});
if (qs.length > 0) {
return `?${qs.join('&')}`;
} }
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 getUrl = (config: OpenAPIConfig, options: ApiRequestOptions): string => {
const encoder = config.ENCODE_PATH || encodeURI; const encoder = config.ENCODE_PATH || encodeURI
const path = options.url const path = options.url
.replace('{api-version}', config.VERSION) .replace("{api-version}", config.VERSION)
.replace(/{(.*?)}/g, (substring: string, group: string) => { .replace(/{(.*?)}/g, (substring: string, group: string) => {
if (options.path?.hasOwnProperty(group)) { if (options.path?.hasOwnProperty(group)) {
return encoder(String(options.path[group])); return encoder(String(options.path[group]))
} }
return substring; return substring
});
const url = `${config.BASE}${path}`;
if (options.query) {
return `${url}${getQueryString(options.query)}`;
}
return url;
};
export const getFormData = (options: ApiRequestOptions): FormData | undefined => {
if (options.formData) {
const formData = new FormData();
const process = (key: string, value: any) => {
if (isString(value) || isBlob(value)) {
formData.append(key, value);
} else {
formData.append(key, JSON.stringify(value));
}
};
Object.entries(options.formData)
.filter(([_, value]) => isDefined(value))
.forEach(([key, value]) => {
if (Array.isArray(value)) {
value.forEach(v => process(key, v));
} else {
process(key, value);
}
});
return formData;
}
return undefined;
};
type Resolver<T> = (options: ApiRequestOptions) => Promise<T>;
export const resolve = async <T>(options: ApiRequestOptions, resolver?: T | Resolver<T>): Promise<T | undefined> => {
if (typeof resolver === 'function') {
return (resolver as Resolver<T>)(options);
}
return resolver;
};
export const getHeaders = async (config: OpenAPIConfig, options: ApiRequestOptions, formData?: FormData): Promise<Record<string, string>> => {
const token = await resolve(options, config.TOKEN);
const username = await resolve(options, config.USERNAME);
const password = await resolve(options, config.PASSWORD);
const additionalHeaders = await resolve(options, config.HEADERS);
const formHeaders = typeof formData?.getHeaders === 'function' && formData?.getHeaders() || {}
const headers = Object.entries({
Accept: 'application/json',
...additionalHeaders,
...options.headers,
...formHeaders,
}) })
.filter(([_, value]) => isDefined(value))
.reduce((headers, [key, value]) => ({ 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<T> = (options: ApiRequestOptions<T>) => Promise<T>
export const resolve = async <T>(
options: ApiRequestOptions<T>,
resolver?: T | Resolver<T>,
): Promise<T | undefined> => {
if (typeof resolver === "function") {
return (resolver as Resolver<T>)(options)
}
return resolver
}
export const getHeaders = async <T>(
config: OpenAPIConfig,
options: ApiRequestOptions<T>,
): Promise<Record<string, string>> => {
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, ...headers,
[key]: String(value), [key]: String(value),
}), {} as Record<string, string>); }),
{} as Record<string, string>,
)
if (isStringWithValue(token)) { if (isStringWithValue(token)) {
headers['Authorization'] = `Bearer ${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 (isStringWithValue(username) && isStringWithValue(password)) { if (options.mediaType) {
const credentials = base64(`${username}:${password}`); headers["Content-Type"] = options.mediaType
headers['Authorization'] = `Basic ${credentials}`;
} }
}
if (options.body) { return headers
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';
}
}
return headers; export const getRequestBody = (options: ApiRequestOptions): unknown => {
}; if (options.body) {
return options.body
export const getRequestBody = (options: ApiRequestOptions): any => { }
if (options.body) { return undefined
return options.body; }
}
return undefined;
};
export const sendRequest = async <T>( export const sendRequest = async <T>(
config: OpenAPIConfig, config: OpenAPIConfig,
options: ApiRequestOptions, options: ApiRequestOptions<T>,
url: string, url: string,
body: any, body: unknown,
formData: FormData | undefined, formData: FormData | undefined,
headers: Record<string, string>, headers: Record<string, string>,
onCancel: OnCancel, onCancel: OnCancel,
axiosClient: AxiosInstance axiosClient: AxiosInstance,
): Promise<AxiosResponse<T>> => { ): Promise<AxiosResponse<T>> => {
const source = axios.CancelToken.source(); const controller = new AbortController()
const requestConfig: AxiosRequestConfig = { let requestConfig: AxiosRequestConfig = {
url, data: body ?? formData,
headers, headers,
data: body ?? formData, method: options.method,
method: options.method, signal: controller.signal,
withCredentials: config.WITH_CREDENTIALS, url,
cancelToken: source.token, withCredentials: config.WITH_CREDENTIALS,
}; }
onCancel(() => source.cancel('The user aborted a request.')); onCancel(() => controller.abort())
try { for (const fn of config.interceptors.request._fns) {
return await axiosClient.request(requestConfig); requestConfig = await fn(requestConfig)
} catch (error) { }
const axiosError = error as AxiosError<T>;
if (axiosError.response) { try {
return axiosError.response; return await axiosClient.request(requestConfig)
} } catch (error) {
throw error; const axiosError = error as AxiosError<T>
if (axiosError.response) {
return axiosError.response
} }
}; throw error
}
}
export const getResponseHeader = (response: AxiosResponse<any>, responseHeader?: string): string | undefined => { export const getResponseHeader = (
if (responseHeader) { response: AxiosResponse<unknown>,
const content = response.headers[responseHeader]; responseHeader?: string,
if (isString(content)) { ): string | undefined => {
return content; if (responseHeader) {
} const content = response.headers[responseHeader]
if (isString(content)) {
return content
} }
return undefined; }
}; return undefined
}
export const getResponseBody = (response: AxiosResponse<any>): any => { export const getResponseBody = (response: AxiosResponse<unknown>): unknown => {
if (response.status !== 204) { if (response.status !== 204) {
return response.data; return response.data
} }
return undefined; return undefined
}; }
export const catchErrorCodes = (options: ApiRequestOptions, result: ApiResult): void => { export const catchErrorCodes = (
const errors: Record<number, string> = { options: ApiRequestOptions,
400: 'Bad Request', result: ApiResult,
401: 'Unauthorized', ): void => {
403: 'Forbidden', const errors: Record<number, string> = {
404: 'Not Found', 400: "Bad Request",
500: 'Internal Server Error', 401: "Unauthorized",
502: 'Bad Gateway', 402: "Payment Required",
503: 'Service Unavailable', 403: "Forbidden",
...options.errors, 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]; const error = errors[result.status]
if (error) { if (error) {
throw new ApiError(options, result, error); throw new ApiError(options, result, error)
} }
if (!result.ok) { if (!result.ok) {
const errorStatus = result.status ?? 'unknown'; const errorStatus = result.status ?? "unknown"
const errorStatusText = result.statusText ?? 'unknown'; const errorStatusText = result.statusText ?? "unknown"
const errorBody = (() => { const errorBody = (() => {
try { try {
return JSON.stringify(result.body, null, 2); return JSON.stringify(result.body, null, 2)
} catch (e) { } catch (e) {
return undefined; return undefined
} }
})(); })()
throw new ApiError(options, result, throw new ApiError(
`Generic Error: status: ${errorStatus}; status text: ${errorStatusText}; body: ${errorBody}` options,
); result,
} `Generic Error: status: ${errorStatus}; status text: ${errorStatusText}; body: ${errorBody}`,
}; )
}
}
/** /**
* Request method * Request method
@@ -287,33 +329,59 @@ export const catchErrorCodes = (options: ApiRequestOptions, result: ApiResult):
* @returns CancelablePromise<T> * @returns CancelablePromise<T>
* @throws ApiError * @throws ApiError
*/ */
export const request = <T>(config: OpenAPIConfig, options: ApiRequestOptions, axiosClient: AxiosInstance = axios): CancelablePromise<T> => { export const request = <T>(
return new CancelablePromise(async (resolve, reject, onCancel) => { config: OpenAPIConfig,
try { options: ApiRequestOptions<T>,
const url = getUrl(config, options); axiosClient: AxiosInstance = axios,
const formData = getFormData(options); ): CancelablePromise<T> => {
const body = getRequestBody(options); return new CancelablePromise(async (resolve, reject, onCancel) => {
const headers = await getHeaders(config, options, formData); try {
const url = getUrl(config, options)
const formData = getFormData(options)
const body = getRequestBody(options)
const headers = await getHeaders(config, options)
if (!onCancel.isCancelled) { if (!onCancel.isCancelled) {
const response = await sendRequest<T>(config, options, url, body, formData, headers, onCancel, axiosClient); let response = await sendRequest<T>(
const responseBody = getResponseBody(response); config,
const responseHeader = getResponseHeader(response, options.responseHeader); options,
url,
body,
formData,
headers,
onCancel,
axiosClient,
)
const result: ApiResult = { for (const fn of config.interceptors.response._fns) {
url, response = await fn(response)
ok: isSuccess(response.status),
status: response.status,
statusText: response.statusText,
body: responseHeader ?? responseBody,
};
catchErrorCodes(options, result);
resolve(result.body);
}
} catch (error) {
reject(error);
} }
});
}; 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)
}
})
}
+6 -49
View File
@@ -1,49 +1,6 @@
/* generated using openapi-typescript-codegen -- do no edit */ // This file is auto-generated by @hey-api/openapi-ts
/* istanbul ignore file */ export { ApiError } from "./core/ApiError"
/* tslint:disable */ export { CancelablePromise, CancelError } from "./core/CancelablePromise"
/* eslint-disable */ export { OpenAPI, type OpenAPIConfig } from "./core/OpenAPI"
export { ApiError } from './core/ApiError'; export * from "./sdk.gen"
export { CancelablePromise, CancelError } from './core/CancelablePromise'; export * from "./types.gen"
export { OpenAPI } from './core/OpenAPI';
export type { OpenAPIConfig } from './core/OpenAPI';
export type { Body_login_login_access_token } from './models/Body_login_login_access_token';
export type { HTTPValidationError } from './models/HTTPValidationError';
export type { ItemCreate } from './models/ItemCreate';
export type { ItemOut } from './models/ItemOut';
export type { ItemsOut } from './models/ItemsOut';
export type { ItemUpdate } from './models/ItemUpdate';
export type { Message } from './models/Message';
export type { NewPassword } from './models/NewPassword';
export type { Token } from './models/Token';
export type { UpdatePassword } from './models/UpdatePassword';
export type { UserCreate } from './models/UserCreate';
export type { UserCreateOpen } from './models/UserCreateOpen';
export type { UserOut } from './models/UserOut';
export type { UsersOut } from './models/UsersOut';
export type { UserUpdate } from './models/UserUpdate';
export type { UserUpdateMe } from './models/UserUpdateMe';
export type { ValidationError } from './models/ValidationError';
export { $Body_login_login_access_token } from './schemas/$Body_login_login_access_token';
export { $HTTPValidationError } from './schemas/$HTTPValidationError';
export { $ItemCreate } from './schemas/$ItemCreate';
export { $ItemOut } from './schemas/$ItemOut';
export { $ItemsOut } from './schemas/$ItemsOut';
export { $ItemUpdate } from './schemas/$ItemUpdate';
export { $Message } from './schemas/$Message';
export { $NewPassword } from './schemas/$NewPassword';
export { $Token } from './schemas/$Token';
export { $UpdatePassword } from './schemas/$UpdatePassword';
export { $UserCreate } from './schemas/$UserCreate';
export { $UserCreateOpen } from './schemas/$UserCreateOpen';
export { $UserOut } from './schemas/$UserOut';
export { $UsersOut } from './schemas/$UsersOut';
export { $UserUpdate } from './schemas/$UserUpdate';
export { $UserUpdateMe } from './schemas/$UserUpdateMe';
export { $ValidationError } from './schemas/$ValidationError';
export { ItemsService } from './services/ItemsService';
export { LoginService } from './services/LoginService';
export { UsersService } from './services/UsersService';
export { UtilsService } from './services/UtilsService';
@@ -1,13 +0,0 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
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);
};
@@ -1,10 +0,0 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
import type { ValidationError } from './ValidationError';
export type HTTPValidationError = {
detail?: Array<ValidationError>;
};
-9
View File
@@ -1,9 +0,0 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type ItemCreate = {
title: string;
description?: (string | null);
};
-11
View File
@@ -1,11 +0,0 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type ItemOut = {
title: string;
description?: (string | null);
id: number;
owner_id: number;
};
-9
View File
@@ -1,9 +0,0 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type ItemUpdate = {
title?: (string | null);
description?: (string | null);
};
-11
View File
@@ -1,11 +0,0 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
import type { ItemOut } from './ItemOut';
export type ItemsOut = {
data: Array<ItemOut>;
count: number;
};
-8
View File
@@ -1,8 +0,0 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type Message = {
message: string;
};
@@ -1,9 +0,0 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type NewPassword = {
token: string;
new_password: string;
};

Some files were not shown because too many files have changed in this diff Show More