Compare commits

...
365 Commits
Author SHA1 Message Date
Sebastián Ramírez 1b8b78415f 📝 Update release notes 2024-03-12 21:55:11 +01:00
Sebastián Ramírez 52b602681d 🔖 Release version 0.6.0 2024-03-12 21:51:56 +01:00
github-actions dd4efc1687 📝 Update release notes 2024-03-12 20:46:30 +00:00
AlejandraandSebastián Ramírez cffdd96fa8 🦇 Add dark mode to README.md (#703)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2024-03-12 20:46:08 +00:00
github-actions c432e5140c 📝 Update release notes 2024-03-12 20:06:19 +00:00
Sebastián Ramírez dad8959597 📌 Upgrade Poetry lock dependencies (#702) 2024-03-12 20:06:02 +00:00
Sebastián Ramírez 655261742b 📝 Update release notes 2024-03-12 21:01:30 +01:00
github-actions f01617a982 📝 Update release notes 2024-03-12 19:48:31 +00:00
Sebastián Ramírez a69c22334e 🍱 Update GitHub image (#701) 2024-03-12 19:48:13 +00:00
github-actions 3cce5b0fa5 📝 Update release notes 2024-03-12 19:42:08 +00:00
Sebastián Ramírez b95bdca83e 🍱 Add GitHub image (#700) 2024-03-12 19:41:48 +00:00
github-actions 76b28895e0 📝 Update release notes 2024-03-12 19:23:40 +00:00
Sebastián Ramírez b32dea360c 🚚 Rename project to Full Stack FastAPI Template (#699) 2024-03-12 19:23:20 +00:00
github-actions 964e605bcd 📝 Update release notes 2024-03-12 18:57:22 +00:00
Sebastián Ramírez c2555c363f 🔒️ Ensure the default values of "changethis" are not deployed (#698) 2024-03-12 18:57:02 +00:00
github-actions 6ed353a072 📝 Update release notes 2024-03-12 18:56:37 +00:00
Alejandra 12202b6f4d ◀ Revert "📸 Rename Dashboard to Home and update screenshots" (#697)
This reverts commit 5cf7ab0a6b.
2024-03-12 18:56:17 +00:00
github-actions 461a257713 📝 Update release notes 2024-03-12 18:24:52 +00:00
Alejandra 03eb49aa4d 🐛 Fix allowing a user to update the email to the same email they already have (#696) 2024-03-12 19:24:35 +01:00
github-actions 55245e1ca4 📝 Update release notes 2024-03-12 18:24:17 +00:00
Alejandra 5cf7ab0a6b 📸 Rename Dashboard to Home and update screenshots (#693) 2024-03-12 19:23:58 +01:00
github-actions 73a1300464 📝 Update release notes 2024-03-12 18:23:54 +00:00
Esteban Maya 98c78e4683 🐛 Fixed items count when retrieving data for all items by user (#695) 2024-03-12 18:23:33 +00:00
github-actions 5373286d8a 📝 Update release notes 2024-03-12 18:19:21 +00:00
Sebastián Ramírez 1e256bce5d 🔥 Remove Celery and Flower, they are currently not used nor recommended (#694) 2024-03-12 19:19:03 +01:00
github-actions 63eb8b5ef8 📝 Update release notes 2024-03-12 17:42:42 +00:00
Alejandra 204f46d651 📝 Update README.md (#691) 2024-03-12 18:42:20 +01:00
github-actions 208a541160 📝 Update release notes 2024-03-12 17:31:14 +00:00
Sebastián Ramírez 37a6e350d1 Migrate from pgAdmin to Adminer (#692) 2024-03-12 18:30:54 +01:00
github-actions 237c5a31c8 📝 Update release notes 2024-03-12 17:02:14 +00:00
Alejandra a62b1682e0 Add test for deleting user without privileges (#690) 2024-03-12 17:01:51 +00:00
github-actions fdf45a00c8 📝 Update release notes 2024-03-12 16:32:41 +00:00
dependabot[bot] 559812a9b2 Bump python-multipart from 0.0.6 to 0.0.7 in /backend (#686)
Bumps [python-multipart](https://github.com/andrew-d/python-multipart) from 0.0.6 to 0.0.7.
- [Release notes](https://github.com/andrew-d/python-multipart/releases)
- [Changelog](https://github.com/Kludex/python-multipart/blob/master/CHANGELOG.md)
- [Commits](https://github.com/andrew-d/python-multipart/compare/0.0.6...0.0.7)

---
updated-dependencies:
- dependency-name: python-multipart
  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-03-12 17:32:21 +01:00
github-actions b8d03f455a 📝 Update release notes 2024-03-12 16:30:08 +00:00
Alejandra f67af697eb ♻️ Refactor user update (#689) 2024-03-12 17:29:49 +01:00
github-actions 22a7d7a09b 📝 Update release notes 2024-03-12 16:06:07 +00:00
dependabot[bot] 66e26e1bfb Bump fastapi from 0.104.1 to 0.109.1 in /backend (#687)
Bumps [fastapi](https://github.com/tiangolo/fastapi) from 0.104.1 to 0.109.1.
- [Release notes](https://github.com/tiangolo/fastapi/releases)
- [Commits](https://github.com/tiangolo/fastapi/compare/0.104.1...0.109.1)

---
updated-dependencies:
- dependency-name: fastapi
  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-03-12 17:05:48 +01:00
github-actions ee092bdad8 📝 Update release notes 2024-03-12 15:09:48 +00:00
Sebastián Ramírez 691443c7cd 👷 Add Lint to GitHub Actions outside of tests (#688) 2024-03-12 15:09:27 +00:00
github-actions 87099ec8c3 📝 Update release notes 2024-03-12 14:51:38 +00:00
Sebastián Ramírez 5e5e4edd8c 📌 Add Poetry lock to git (#685) 2024-03-12 14:51:21 +00:00
github-actions ee03380284 📝 Update release notes 2024-03-12 14:14:24 +00:00
graue70andSebastián Ramírez ab7d6df725 ✏ Fix typo in development.md (#309)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2024-03-12 14:14:04 +00:00
github-actions f6fce60ffc 📝 Update release notes 2024-03-12 14:02:36 +00:00
dependabot[bot] 7e59206936 ⬆ Bump dawidd6/action-download-artifact from 2.28.0 to 3.1.2 (#643)
Bumps [dawidd6/action-download-artifact](https://github.com/dawidd6/action-download-artifact) from 2.28.0 to 3.1.2.
- [Release notes](https://github.com/dawidd6/action-download-artifact/releases)
- [Commits](https://github.com/dawidd6/action-download-artifact/compare/v2.28.0...v3.1.2)

---
updated-dependencies:
- dependency-name: dawidd6/action-download-artifact
  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-03-12 15:02:19 +01:00
github-actions daaa2aff78 📝 Update release notes 2024-03-12 14:02:13 +00:00
dependabot[bot] 2db5805622 ⬆ Bump actions/upload-artifact from 3 to 4 (#642)
Bumps [actions/upload-artifact](https://github.com/actions/upload-artifact) from 3 to 4.
- [Release notes](https://github.com/actions/upload-artifact/releases)
- [Commits](https://github.com/actions/upload-artifact/compare/v3...v4)

---
updated-dependencies:
- dependency-name: actions/upload-artifact
  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-03-12 15:01:55 +01:00
github-actions 0885aabc65 📝 Update release notes 2024-03-12 14:01:12 +00:00
dependabot[bot] e15531674f Bump follow-redirects from 1.15.3 to 1.15.5 in /frontend (#654) 2024-03-12 15:00:54 +01:00
github-actions 2b7d3c296a 📝 Update release notes 2024-03-12 14:00:19 +00:00
dependabot[bot] 5ea1695e1c Bump vite from 5.0.4 to 5.0.12 in /frontend (#653) 2024-03-12 14:59:55 +01:00
github-actions aa481ff89e 📝 Update release notes 2024-03-12 13:59:03 +00:00
Alejandra d360b92bc6 🎨 Adjust color and spacing (#684) 2024-03-12 14:58:44 +01:00
github-actions cc0ea3c3b5 📝 Update release notes 2024-03-12 13:57:10 +00:00
Esteban Maya 709f1d4ab2 👷 Avoid creating unnecessary *.pyc files with PYTHONDONTWRITEBYTECODE=1 (#677) 2024-03-12 14:56:49 +01:00
github-actions 15ce944a37 📝 Update release notes 2024-03-12 13:53:45 +00:00
dependabot[bot] 069cb30b71 ⬆ Bump actions/setup-python from 4 to 5 (#641)
Bumps [actions/setup-python](https://github.com/actions/setup-python) from 4 to 5.
- [Release notes](https://github.com/actions/setup-python/releases)
- [Commits](https://github.com/actions/setup-python/compare/v4...v5)

---
updated-dependencies:
- dependency-name: actions/setup-python
  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-03-12 14:53:25 +01:00
github-actions 49bc9b33c9 📝 Update release notes 2024-03-12 13:40:14 +00:00
5ad33845c9 Add support for setting POSTGRES_PORT (#333)
Co-authored-by: Martin Conraux <rhodes@protonmail.com>
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2024-03-12 14:39:53 +01:00
github-actions c3f77eb713 📝 Update release notes 2024-03-12 13:03:23 +00:00
Chandler RosenthalandSebastián Ramírez 2f027567c6 🔧 Add SMTP_SSL option for older SMTP servers (#365)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2024-03-12 13:03:04 +00:00
github-actions a4358db5bc 📝 Update release notes 2024-03-12 12:31:48 +00:00
Sebastián Ramírez 4e2c6bd6ba ♻️ Refactor logic to allow running pytest tests locally (#683) 2024-03-12 12:31:31 +00:00
github-actions 64e21bb0d5 📝 Update release notes 2024-03-12 12:25:26 +00:00
Dong-hyeon ShinandSebastián Ramírez 11fe2a00ed ♻ Update error messages (#417)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2024-03-12 12:25:03 +00:00
github-actions 1e08434ca9 📝 Update release notes 2024-03-12 09:53:41 +00:00
Sebastián Ramírez 6adafdc13d 🔧 Add a default Flower password (#682) 2024-03-12 10:53:25 +01:00
github-actions 6d5db02b35 📝 Update release notes 2024-03-12 09:45:34 +00:00
8131bb3bab ⬆ Upgrade Flower version and command (#447)
Co-authored-by: Mauro Bruni <mauro@satellogic.com>
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2024-03-12 09:45:14 +00:00
github-actions 6f48d6a2a8 📝 Update release notes 2024-03-12 09:00:58 +00:00
Sebastián Ramírez 381227d2dc 📝 Add docs for wildcard domains (#681) 2024-03-12 09:00:38 +00:00
github-actions f3b9d07337 📝 Update release notes 2024-03-11 19:54:39 +00:00
Sebastián Ramírez 3527df959e 📝 Add the required GitHub Actions secrets to docs (#679) 2024-03-11 19:54:22 +00:00
github-actions 209992a929 📝 Update release notes 2024-03-11 19:35:22 +00:00
Alejandra 2a20c4bac6 📝 Update README.md and deployment.md (#678) 2024-03-11 19:34:59 +00:00
github-actions 36f1082f20 📝 Update release notes 2024-03-11 17:45:32 +00:00
619b230e47 ⬆ Add uvicorn[standard] to include watchgod and uvloop` (#438)
Co-authored-by: AlonMenczer <alonm@spotnix.io>
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2024-03-11 17:45:10 +00:00
github-actions 4617e2e7e4 📝 Update release notes 2024-03-11 17:09:13 +00:00
Sebastián Ramírez 10f7b23c9c 🔧 Update VS Code debug config (#676) 2024-03-11 17:08:53 +00:00
github-actions c60938013d 📝 Update release notes 2024-03-11 17:06:52 +00:00
Alejandra 8fedbd17b8 📝 Update frontend README.md (#675) 2024-03-11 17:06:35 +00:00
github-actions 63b0a0e05d 📝 Update release notes 2024-03-11 16:57:15 +00:00
Alejandra eed628a43e 🎨 Improve styles (#673) 2024-03-11 16:56:59 +00:00
github-actions 6b40df55d4 📝 Update release notes 2024-03-11 16:49:53 +00:00
Sebastián Ramírez ed9958bc1e ♻️ Refactor code structure for tests (#674) 2024-03-11 16:49:35 +00:00
github-actions 20f6020c7c 📝 Update release notes 2024-03-11 15:52:14 +00:00
Sebastián Ramírez e56cee9c1d 👷 Tweak test GitHub Action names (#672) 2024-03-11 15:51:57 +00:00
github-actions d43918eebf 📝 Update release notes 2024-03-11 15:51:04 +00:00
Alejandra 7cf9577ebb 🎨 Update theme (#666) 2024-03-11 15:50:46 +00:00
github-actions 4ef4b27b10 📝 Update release notes 2024-03-11 15:50:27 +00:00
Alejandra 710e2f8c2b 🔧 Set TanStack Router devtools only in dev mode (#668) 2024-03-11 15:50:10 +00:00
github-actions 8f9650b661 📝 Update release notes 2024-03-11 15:48:12 +00:00
Sebastián Ramírez 6851eea1fe 🐛 Set up Sentry only when used (#671) 2024-03-11 15:47:51 +00:00
github-actions d52fc65491 📝 Update release notes 2024-03-11 15:46:21 +00:00
Sebastián Ramírez e12262078a 📝 Update deployment docs to use a different directory for traefik-public (#670) 2024-03-11 15:46:01 +00:00
github-actions e165897df7 📝 Update release notes 2024-03-11 15:34:35 +00:00
Sebastián Ramírez b9cbb4f8f4 👷 Add continuous deployment and refactors needed for it (#667) 2024-03-11 15:34:18 +00:00
github-actions bb7da40c87 📝 Update release notes 2024-03-10 19:47:39 +00:00
Esteban MayaandSebastián Ramírez a230f4fb2c 🏷️ Add mypy to the GitHub Action for tests and fixed types in the whole project (#655)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2024-03-10 19:47:21 +00:00
github-actions 6607eaded4 📝 Update release notes 2024-03-10 19:46:50 +00:00
Esteban Maya be82eb585c 🔧 Add .gitattributes file to ensure LF endings for .sh files (#658) 2024-03-10 19:46:34 +00:00
github-actions f3571b6b52 📝 Update release notes 2024-03-09 23:54:02 +00:00
Alejandra f5ccd4a59c Create endpoint to show password recovery email content and update email template (#664) 2024-03-09 23:53:46 +00:00
github-actions 449889b994 📝 Update release notes 2024-03-09 23:53:18 +00:00
Alejandra d04f758433 🔥 Remove unnecessary validation (#662) 2024-03-09 23:53:03 +00:00
github-actions 6d1c47e67d 📝 Update release notes 2024-03-09 23:02:52 +00:00
Sebastián Ramírez d4e35a0dfd ♻️ Refactor email logic to allow re-using util functions for testing and development (#663) 2024-03-09 23:02:36 +00:00
github-actions c048a61d81 📝 Update release notes 2024-03-09 20:13:47 +00:00
AlejandraandSebastián Ramírez 9989016c56 💬 Improve Delete Account description and confirmation (#661)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2024-03-09 20:13:31 +00:00
github-actions d8e529a4c2 📝 Update release notes 2024-03-09 00:42:21 +00:00
Alejandra 4de4777e4b ♻️ Refactor email templates (#659) 2024-03-09 00:41:58 +00:00
github-actions 424d66b791 📝 Update release notes 2024-03-09 00:41:36 +00:00
Sebastián Ramírez 07064ae5e0 📝 Update deployment files and docs (#660) 2024-03-09 00:41:13 +00:00
github-actions 3de18e5fc0 📝 Update release notes 2024-03-08 19:48:15 +00:00
Alejandra 38e59c0efd 📸 Add new screenshots (#657) 2024-03-08 19:47:58 +00:00
github-actions d25af0f79c 📝 Update release notes 2024-03-08 19:46:11 +00:00
Alejandra 7f87c0f5d5 🔥 Remove unused schemas (#656) 2024-03-08 19:45:49 +00:00
github-actions 44c1be1008 📝 Update release notes 2024-03-08 18:24:16 +00:00
Alejandra 9d703df254 🚚 Move new-frontend to frontend (#652) 2024-03-08 18:23:54 +00:00
github-actions 3b44537361 📝 Update release notes 2024-03-08 16:45:50 +00:00
Alejandra 5e48da384e 🔧 Add script for ESLint 2024-03-08 11:45:34 -05:00
github-actions 21fdff93c6 📝 Update release notes 2024-03-08 16:43:41 +00:00
Alejandra 4900b2e676 🐛 Fix but when editing own user (#651) 2024-03-08 16:43:21 +00:00
github-actions c5da9752fb 📝 Update release notes 2024-03-08 14:44:21 +00:00
Sebastián Ramírez 458d712d44 🔥 Remove old frontend (#649) 2024-03-08 14:44:04 +00:00
github-actions 55c19b3196 📝 Update release notes 2024-03-08 14:26:46 +00:00
Alejandra fba645a30a Ignore client folder (#648) 2024-03-08 09:26:29 -05:00
github-actions 88c162ba01 📝 Update release notes 2024-03-08 14:10:48 +00:00
Alejandra 0231740213 ⚙️ Add Prettier config (#647) 2024-03-08 14:10:28 +00:00
github-actions 75adf755b4 📝 Update release notes 2024-03-08 13:58:54 +00:00
Alejandra 2d138b4622 🎨 Format with Prettier (#646) 2024-03-08 13:58:36 +00:00
github-actions 6a3e47b7c9 📝 Update release notes 2024-03-08 13:43:19 +00:00
Alejandra 3398a77ad1 🔧 Update pre-commit config (#645) 2024-03-08 13:43:02 +00:00
github-actions 2482ceb159 📝 Update release notes 2024-03-08 13:10:26 +00:00
Alejandra fd9e8e0803 Revert "⚙️ Add Prettier and ESLint config with pre-commit" (#644)
This reverts commit 1b8b42cee5.
2024-03-08 13:10:09 +00:00
github-actions 92a5550011 📝 Update release notes 2024-03-07 23:22:02 +00:00
Esteban MayaandSebastián Ramírez 541dd75ce9 Add tests to raise coverage to at least 90% and fix recover password logic (#632)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2024-03-07 23:21:46 +00:00
github-actions c6703e41b2 📝 Update release notes 2024-03-07 23:08:24 +00:00
Alejandra 1b8b42cee5 ⚙️ Add Prettier and ESLint config with pre-commit (#640) 2024-03-07 23:08:07 +00:00
github-actions 6c41e30263 📝 Update release notes 2024-03-07 23:03:32 +00:00
Esteban MayaandSebastián Ramírez 7e2e724c4a 👷 Add coverage with Smokeshow to CI and badge (#638)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2024-03-07 23:03:15 +00:00
github-actions cfb42d1bef 📝 Update release notes 2024-03-07 19:50:03 +00:00
Sebastián Ramírez 4c1f75ce72 📝 Refactor README into separate README.md files for backend, frontend, deployment, development (#639) 2024-03-07 19:49:43 +00:00
github-actions 7a82434ab5 📝 Update release notes 2024-03-07 18:16:47 +00:00
Alejandra 11c09b50b2 Migrate to TanStack Query (React Query) and TanStack Router (#637) 2024-03-07 18:16:23 +00:00
github-actions 7c2b617c09 📝 Update release notes 2024-03-07 17:51:31 +00:00
Esteban MayaandSebastián Ramírez a44d2fd666 🐛 Fix copier to handle string vars with spaces in quotes (#631)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2024-03-07 17:51:14 +00:00
github-actions f3d6b1c435 📝 Update release notes 2024-03-07 16:35:51 +00:00
Esteban MayaandSebastián Ramírez 8558cf00a2 ♻ Move project source files to top level from src, update Sentry dependency (#630)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2024-03-07 16:35:33 +00:00
github-actions ae83b89113 📝 Update release notes 2024-03-02 10:02:20 +00:00
Esteban MayaandSebastián Ramírez 06766f3cb3 ♻ Refactor Python folder tree (#629)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2024-03-02 10:01:59 +00:00
github-actions 0ca52bfca9 📝 Update release notes 2024-03-01 20:18:33 +00:00
Sebastián Ramírez cab869eac2 📝 Update README (#628) 2024-03-01 20:18:16 +00:00
github-actions 0ebd1de9f4 📝 Update release notes 2024-03-01 17:26:25 +00:00
Esteban MayaandSebastián Ramírez e6a6819c57 Add setup and teardown database for tests (#626)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2024-03-01 17:26:05 +00:00
github-actions d0c9a6831c 📝 Update release notes 2024-03-01 17:13:27 +00:00
Alejandra a22da4b1b5 Update new-frontend client (#625) 2024-03-01 17:12:55 +00:00
github-actions 1893602d61 📝 Update release notes 2024-02-29 22:31:16 +00:00
Alejandra 01c40d4bda Add password reset functionality (#624) 2024-02-29 23:30:58 +01:00
github-actions 7bc569f006 📝 Update release notes 2024-02-29 20:43:13 +00:00
Alejandra 2d0f77421f ♻️ Refactor old CRUD utils and tests (#622) 2024-02-29 21:42:55 +01:00
github-actions ad0abb08ef 📝 Update release notes 2024-02-29 14:47:35 +00:00
AlejandraandEsteban Maya Cadavid 4531952aa7 Add private/public routing (#621)
Co-authored-by: Esteban Maya Cadavid <emaya@trueblue.com>
2024-02-29 15:47:13 +01:00
github-actions 732ab9c3e6 📝 Update release notes 2024-02-29 13:19:32 +00:00
Sebastián Ramírez f0c433ae5f 🔧 Add VS Code debug configs (#620) 2024-02-29 13:19:11 +00:00
github-actions c49bf29b0e 📝 Update release notes 2024-02-29 13:00:32 +00:00
Sebastián Ramírez a4b151112b 👷 Update GitHub Action latest-changes and move release notes to independent file (#619) 2024-02-29 13:00:15 +00:00
github-actions 14f63707c4 📝 Update release notes 2024-02-29 01:09:41 +00:00
Sebastián Ramírez 0122fa2f11 🔧 Update .env to allow local debug for the backend (#618) 2024-02-29 01:09:24 +00:00
github-actions 5b802e96bb 📝 Update release notes 2024-02-29 01:03:45 +00:00
Sebastián Ramírez cfd66d2eee ♻️ Refactor and update CORS, remove trailing slash from new Pydantic v2 (#617) 2024-02-29 01:03:23 +00:00
github-actions 53a0aebadf 📝 Update release notes 2024-02-28 23:57:06 +00:00
github-actions 0dd6ce699f 📝 Update release notes 2024-02-28 23:57:02 +00:00
github-actions 9fc4045bc0 📝 Update release notes 2024-02-28 23:56:48 +00:00
github-actions 9fccee6fd5 📝 Update release notes 2024-02-28 23:56:38 +00:00
github-actions bb124f91ff 📝 Update release notes 2024-02-28 23:56:32 +00:00
github-actions aa678e92a9 📝 Update release notes 2024-02-28 23:56:29 +00:00
github-actions 0602722f8c 📝 Update release notes 2024-02-28 23:56:21 +00:00
github-actions 52ee514d8c 📝 Update release notes 2024-02-28 23:56:18 +00:00
github-actions 9507f4b54b 📝 Update release notes 2024-02-28 23:56:13 +00:00
github-actions 76081da4c3 📝 Update release notes 2024-02-28 23:54:19 +00:00
github-actions d5cef0da2d 📝 Update release notes 2024-02-28 23:54:13 +00:00
github-actions c0d9e6e701 📝 Update release notes 2024-02-28 23:54:08 +00:00
github-actions 9cff2434a9 📝 Update release notes 2024-02-28 23:53:56 +00:00
github-actions 922bf1f6ce 📝 Update release notes 2024-02-28 23:53:43 +00:00
github-actions 61ea8fcee3 📝 Update release notes 2024-02-28 23:53:41 +00:00
github-actions 701eb4815c 📝 Update release notes 2024-02-28 23:53:37 +00:00
github-actions 7a8870b7b2 📝 Update release notes 2024-02-28 23:53:29 +00:00
github-actions 26fac55651 📝 Update release notes 2024-02-28 23:53:22 +00:00
github-actions 84c1a8fd68 📝 Update release notes 2024-02-28 23:53:19 +00:00
github-actions dbd2050362 📝 Update release notes 2024-02-28 23:53:07 +00:00
github-actions f71706b077 📝 Update release notes 2024-02-28 23:49:28 +00:00
Alejandra e4a4bed5b6 Add form validation to Admin, Items and Login (#616) 2024-02-29 00:30:59 +01:00
Esteban Maya 08395759fe ⬆ Upgrade code to support pydantic V2 (#615) 2024-02-28 23:24:24 +01:00
AlejandraandEsteban Maya Cadavid 2346b81c51 Support delete own account and other tweaks (#614)
Co-authored-by: Esteban Maya Cadavid <emaya@trueblue.com>
2024-02-27 21:47:42 +01:00
Alejandra e44777f919 Restructure folders, allow editing of users/items, and implement other refactors and improvements (#603)
* Reorganize project directory structure

* Allow edit users/items, add useAuth and useCustomToast, password confirmation

* Minor improvements for consistency

* Add 'Cancel' button to UserInformation in editMode

* Refactor UserSettings

* Enable user password changes and improve error handling

* Enable user information update

* Add logout to Sidebar in mobile devices, conditional tabs depending on role and other improvements

* Add badges

* Remove comment

* Appearance tab updates

* Change badge color

* Reset inputs when clicking on 'Cancel' button

* Disable actions menu for Superuser when logged in

* Modify Logout and update stores
2024-02-26 15:39:09 +01:00
Sebastián Ramírez 544f89f253 📝 Update internal README and referred files (#613) 2024-02-25 21:51:56 +01:00
Sebastián Ramírez 42726193d0 Add Copier, migrate from Cookiecutter, in a way that supports using the project as is, forking or cloning it (#612)
* 🔧 Add first Copier config

* 🔧 Add custom copier answers file

* 🔨 Add Copier script to update .env after generating/copying

* 🙈 Update .gitignores from Copier updates

* 🔧 Update .env, restructure in order of relevance

* 🔧 Remove Copier config for SMTP port, if necessary, it can be overwritten in .env

* ♻️ Refactor Copier files, make them less visible

* 🔧 Update Copier config

* 🔥 Remove Cookiecutter files
2024-02-25 21:20:20 +01:00
Sebastián Ramírez 0cc802eec8 🎨 Format files with pre-commit and Ruff (#611) 2024-02-25 19:39:33 +01:00
Sebastián Ramírez 2802a4df9e Replace black, isort, flake8, autoflake with ruff and upgrade mypy (#610) 2024-02-25 19:29:00 +01:00
Sebastián Ramírez 73b2884057 🚚 Refactor and simplify backend file structure (#609) 2024-02-25 18:48:02 +01:00
Sebastián Ramírez a065f9c9e8 🔥 Clean up old files no longer relevant (#608) 2024-02-25 17:50:12 +01:00
Sebastián Ramírez 72f835a6b4 ♻ Re-structure Docker Compose files, discard Docker Swarm specific logic (#607) 2024-02-25 17:28:26 +01:00
f41f4432fe ♻ Refactor items and services endpoints to return count and data, and add CI tests (#599)
Co-authored-by: Esteban Maya Cadavid <emaya@trueblue.com>
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2024-02-25 16:04:47 +01:00
Alejandra 176b6fb1c9 ♻️ Refactor update endpoints and regenerate client for new-frontend (#602) 2024-02-22 00:55:19 +04:00
Sebastián Ramírez fe95750e3a Add support for updating items and upgrade SQLModel to 0.0.16 (which supports model object updates) (#601) 2024-02-17 21:29:15 +01:00
Alejandra 93e03184d6 Add dark mode to new-frontend and conditional sidebar items (#600) 2024-02-16 19:38:00 +01:00
AlejandraandSebastián Ramírez b470f59ce2 Migrate to RouterProvider and other refactors (#598)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2024-02-15 23:17:26 +01:00
Alejandra b18783f642 Add Not Found page (#595) 2024-02-13 21:06:57 +01:00
Alejandra a88f637ed8 Add delete_user; refactor delete_item (#594) 2024-02-13 15:25:58 +01:00
AlejandraandSebastián Ramírez b4a1da918d Add new pages, components, panels, modals, and theme; refactor and improvements in existing components (#593)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2024-02-12 22:46:51 +01:00
Alejandra 2014a3bcf5 Add state store to new frontend (#592) 2024-02-12 20:03:08 +01:00
dependabot[bot] 889d97f057 ⬆ Bump tiangolo/issue-manager from 0.2.0 to 0.5.0 (#591)
Bumps [tiangolo/issue-manager](https://github.com/tiangolo/issue-manager) from 0.2.0 to 0.5.0.
- [Release notes](https://github.com/tiangolo/issue-manager/releases)
- [Commits](https://github.com/tiangolo/issue-manager/compare/0.2.0...0.5.0)

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-02-01 17:09:46 +01:00
github-actions 78b4d5d5fa 📝 Update release notes 2024-01-29 22:42:30 +00:00
Alejandra cbba08d565 🐛 Add onClose to SidebarItems (#589) 2024-01-29 23:42:09 +01:00
github-actions 4bbab503cd 📝 Update release notes 2024-01-29 22:11:07 +00:00
Alejandra b950fd7389 Add Layout to App (#588) 2024-01-29 23:10:46 +01:00
github-actions 16f26df0c6 📝 Update release notes 2024-01-29 21:40:31 +00:00
Alejandra 68ae0970f1 Add Sidebar to new frontend (#587) 2024-01-29 22:40:11 +01:00
github-actions fa473bed72 📝 Update release notes 2024-01-23 16:49:17 +00:00
Alejandra 52150b3d10 Add Login to new frontend (#585) 2024-01-23 20:48:56 +04:00
github-actions bd54967db8 📝 Update release notes 2024-01-22 20:21:50 +00:00
Alejandra 6ecc8a06ec Include schemas in generated frontend client (#584) 2024-01-22 21:16:21 +01:00
github-actions d91ed067a8 📝 Update release notes 2023-12-27 19:51:08 +00:00
Alejandra 7966d3fb1b Regenerate frontend client with recent changes (#575) 2023-12-27 20:50:48 +01:00
github-actions 5a4b0ed2e4 📝 Update release notes 2023-12-27 19:40:02 +00:00
Alejandra 6faa5f66d5 ♻️ Re-enable user update path operations for frontend client generation (#574) 2023-12-27 20:39:42 +01:00
github-actions 47d30b75c3 📝 Update release notes 2023-12-27 18:49:56 +00:00
Alejandra d5982236ac ♻️ Refactor API in utils.py (#573) 2023-12-27 19:49:36 +01:00
github-actions 570ca7b9d9 📝 Update release notes 2023-12-27 18:37:23 +00:00
Alejandra 047e6884be ♻️ Remove type ignores and add response_model (#572) 2023-12-27 19:37:05 +01:00
github-actions 73798ba60c 📝 Update release notes 2023-12-27 18:07:13 +00:00
Sebastián Ramírez c1538fd1fb Update code for login API (#571)
*  Update models for login API

*  Add authenticate simplified CRUD

* ♻️ Refactor get_current_user dependency, integrate is_active

*  Refactor and upgrade login API code
2023-12-27 19:06:47 +01:00
github-actions 5679d04a29 📝 Update release notes 2023-12-26 15:52:06 +00:00
Alejandra 49d610e443 Add client in frontend and client generation (#569) 2023-12-26 16:51:46 +01:00
github-actions 311939e640 📝 Update release notes 2023-12-04 22:09:34 +00:00
Alejandra 8155761cf4 🐳 Set up Docker config for new-frontend (#564) 2023-12-04 23:09:14 +01:00
github-actions 229191061a 📝 Update release notes 2023-11-30 21:16:52 +00:00
Alejandra 28808e071c Set up new frontend with Vite, TypeScript and React (#563) 2023-11-30 22:16:32 +01:00
github-actions 1864e7e5b0 📝 Update release notes 2023-11-29 22:22:34 +00:00
Alejandra 3f109aee1f 🐛 Fix positional argument bug in init_db.py (#562) 2023-11-29 23:22:15 +01:00
github-actions 85de4ce362 📝 Update release notes 2023-11-29 17:13:36 +00:00
AlejandraandSebastián Ramírez 6f29eb2438 ♻️ Refactor Users API and dependencies (#561)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2023-11-29 18:13:15 +01:00
github-actions 2189b9f43b 📝 Update release notes 2023-11-24 23:11:25 +00:00
Sebastián Ramírez 870d45fa36 Upgrade items router with new SQLModel models, simplified logic, and new FastAPI Annotated dependencies (#560) 2023-11-25 00:11:02 +01:00
github-actions 9befa33a9f 📝 Update release notes 2023-11-24 23:08:46 +00:00
Sebastián Ramírez a66a9256dd Adopt SQLModel, create models, start using it (#559)
* 🔥 Remove old SQLAlchemy models

*  Add new SQLModel models

* 🔧 Update Alembic configs to work with SQLModel

*  Re-generate initial Alembic migration

* 🔧 Update PostgreSQL driver connection string URL

*  Create new SQLModel engine

* 🔥 Remove old unneeded SQLAlchemy-specific files

* ♻️ Update init_db

* ♻️ Use new SQLModel session

* ♻️ Update conftest with new DB Session

* ♻️ Update pre-start scripts to use SQLModel session

* ♻️ Import new SQLModel models

*  Create new simplified create_user crud util

* ♻️ Update import in CRUDBase class (soon to be removed)

* 🙈 Update .gitignore with Python files
2023-11-25 00:08:22 +01:00
github-actions 2d92cd70a4 📝 Update release notes 2023-11-24 22:48:38 +00:00
Sebastián Ramírez e4877b7a9f ⬆️ Upgrade Python version and dependencies (#558) 2023-11-24 23:48:21 +01:00
github-actions bd2236b842 📝 Update release notes 2023-11-15 22:02:28 +00:00
Sebastián Ramírez fa4ea018c3 ♻️ Refactor frontend Docker build setup, use plain NodeJS, use custom Nginx config, fix build for old Vue (#555) 2023-11-15 23:02:09 +01:00
github-actions 02223e1e1b 📝 Update release notes 2023-11-15 21:15:42 +00:00
8b317cafd1 📌 Fix flower Docker image, pin version (#396)
Co-authored-by: Kyler <39353605+fisher60@users.noreply.github.com>
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2023-11-15 22:15:23 +01:00
github-actions 68d48be306 📝 Update release notes 2023-11-15 21:04:53 +00:00
Oskar BechtoldandSebastián Ramírez 7705fe89df 🐛 Fix Celery worker command (#443)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2023-11-15 22:04:34 +01:00
github-actions edae7ba371 📝 Update release notes 2023-11-15 20:58:15 +00:00
Sebastián Ramírez c892fc200e 🔧 Add missing dotenv variables (#554) 2023-11-15 21:57:55 +01:00
github-actions 9fb69ba140 📝 Update release notes 2023-11-15 20:20:48 +00:00
Sebastián Ramírez 455de4d9a9 ♻️ Refactor project generation, discard cookiecutter, use plain git/clone/fork (#553) 2023-11-15 21:20:29 +01:00
github-actions 30c722339b 📝 Update release notes 2023-11-15 20:03:57 +00:00
Sebastián Ramírez dceca9c1e5 📝 Update README with in construction notice (#552) 2023-11-15 21:03:37 +01:00
github-actions 370b5c1345 📝 Update release notes 2023-11-15 19:51:12 +00:00
Alejandra S 64e4d37ee2 📌 Add NodeJS version management and instructions (#551) 2023-11-15 20:50:50 +01:00
github-actions ef615cf8e9 📝 Update release notes 2023-11-14 20:14:36 +00:00
f3823edaed 🐛 Fix Poetry installation in Dockerfile and upgrade Python version and packages to fix Docker build (#480)
Co-authored-by: lidong293 <lidong310@jd.com>
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2023-11-14 21:14:19 +01:00
github-actions 6c9f70281b 📝 Update release notes 2023-11-04 03:30:07 +00:00
Sebastián Ramírez e0db713f6b 👷 Add dependabot (#547) 2023-11-04 07:29:47 +04:00
Sebastián Ramírez 04664a9ce9 📝 Update release notes 2023-11-04 07:28:38 +04:00
github-actions ea544e903c 📝 Update release notes 2023-11-04 03:25:36 +00:00
github-actions 5c5de0fa5d 📝 Update release notes 2023-11-04 03:24:58 +00:00
Sebastián Ramírez 6e5c3375c7 📝 Update release notes 2023-11-04 07:15:05 +04:00
github-actions 20d93b0284 📝 Update release notes 2023-11-04 03:11:34 +00:00
Sebastián Ramírez d148958782 👷 Fix latest-changes GitHub Action token, strike 2 (#546) 2023-11-04 07:11:15 +04:00
Sebastián Ramírez b57ae43bcf 👷 Fix latest-changes GitHub Action token config (#545) 2023-11-04 06:35:32 +04:00
Sebastián Ramírez 5729eceb83 👷 Add latest-changes GitHub Action (#544) 2023-11-04 06:32:02 +04:00
Sebastián Ramírez 490c554e23 📝 Update release notes 2020-06-05 19:12:34 +02:00
Sebastián Ramírez aab833bae2 ⬆️ Update issue-manager (#211) 2020-06-05 19:11:45 +02:00
Sebastián Ramírez 45fdd880ce 📝 Update release notes 2020-05-25 08:44:17 +02:00
Sebastián Ramírez 27fabe01ea Add GitHub Sponsors button (#201) 2020-05-25 08:43:24 +02:00
Sebastián Ramírez 6967ce1b0c 📝 Update release notes 2020-05-25 08:34:31 +02:00
Sebastián Ramírez 20fa4ce8fb 🔊 Add consistent errors for env vars not set (#200) 2020-05-25 08:33:36 +02:00
Sebastián Ramírez 1a64656267 📝 Update release notes 2020-05-24 23:37:01 +02:00
Sebastián Ramírez e4c668d7cd Upgrade Traefik to version 2 (#199)
* 🔧 Add STACK_NAME to .env for Traefik labels

*  Upgrade Docker Compose to use Traefik v2

*  Enable Traefik v2 in Docker Compose override for local development

* 🐛 Use internal HTTPS redirect in case the deployment is not through DockerSwarm.rocks
2020-05-24 23:35:49 +02:00
Sebastián Ramírez bdc40a17f6 📝 Update release notes 2020-04-20 20:46:13 +02:00
Sebastián Ramírez b88a0fc5fa 📝 Add docs about reporting coverage in HTML (#161) 2020-04-20 20:45:32 +02:00
Sebastián Ramírez b02e4633dc 📝 Update relase notes 2020-04-20 20:32:26 +02:00
Sebastián Ramírez 43d5b49bd1 Test using the TestClient (#160) 2020-04-20 20:31:29 +02:00
Sebastián Ramírez 41a2f15d8f 🎨 Format fixes (#159)
* 📝 Update release notes

* 🎨 Update format and structure
2020-04-20 19:27:45 +02:00
Sebastián Ramírez 7b768879f5 📝 Update release notes 2020-04-20 19:15:01 +02:00
Sebastián Ramírez eed33d276d ♻️ Refactor backend, settings, DB sessions, types, configs, plugins (#158)
* ♻️ Refactor backend, update DB session handling

*  Add mypy config and plugins

*  Use Python-jose instead of PyJWT

as it has some extra functionalities and features

*  Add/update scripts for test, lint, format

* 🔧 Update lint and format configs

* 🎨 Update import format, comments, and types

* 🎨 Add types to config

*  Add types for all the code, and small fixes

* 🎨 Use global imports to simplify exploring with Jupyter

* ♻️ Import schemas and models, instead of each class

* 🚚 Rename db_session to db for simplicity

* 📌 Update dependencies installation for testing
2020-04-20 19:03:13 +02:00
Sebastián Ramírez 4b80bdfdce 📝 Update release notes 2020-04-19 21:01:11 +02:00
Sebastián Ramírez 7d57876bda 📝 Add docs about removing the frontend (#156) 2020-04-19 21:00:31 +02:00
Sebastián Ramírez 3678eb9d57 📝 Update release notes 2020-04-19 20:20:32 +02:00
Sebastián Ramírez f09fb854bf 🔧 Simplify scripts and development (#155)
* 🔧 Update scripts and configs

* 🔧 Add shebang to script

* 🔥 Remove test and dev configs, pass inline

*  Add local development dev-link set up

* 📝 Update generated docs with refactor

* 📝 Add Contributing guide
2020-04-19 20:19:25 +02:00
Sebastián Ramírez a7fd258e18 📝 Update release notes 2020-04-19 16:45:30 +02:00
Sebastián Ramírez 2afe4159ab ♻️ Simplify Docker Compose files and deployment (#153)
* ♻️ Simplify Docker Compose files and deployment

* 🔧 Remove TRAEFIK_PUBLIC_NETWORK_IS_EXTERNAL from .env
2020-04-19 16:44:12 +02:00
Sebastián Ramírez 283bc7c95b ♻️ Simplify tests, run in same backend service (#152)
remove backend-tests
2020-04-19 12:34:03 +02:00
Sebastián Ramírez 8f9c2bac42 📝 Update release notes 2020-04-19 09:18:19 +02:00
Sebastián Ramírez a7d3671a72 ♻️ Simplify env files, merge to one .env (#151) 2020-04-19 09:17:14 +02:00
Sebastián Ramírez 894b0a5587 📝 Update Travis badge 2020-04-19 08:54:23 +02:00
Sebastián Ramírez a25f2c14e4 🔖 Release version 0.5.0 2020-04-19 08:52:11 +02:00
Sebastián Ramírez 122d983415 📝 Update release notes 2020-04-19 08:51:36 +02:00
Sebastián Ramírez d08d9314ce 📌 Make the public Traefik network a fixed default (#150)
to simplify development
2020-04-19 08:50:00 +02:00
Sebastián Ramírez ff55b778ba 📝 Update release notes 2020-04-19 07:57:18 +02:00
Ruslan Samoylov 8812ca6635 ⬆️ Upgrade to Postgres 12 (#148) 2020-04-19 07:56:05 +02:00
Sebastián Ramírez 2e8da3a590 📝 Update release notes 2020-04-18 23:30:01 +02:00
Sebastián Ramírez 00297f974f 🙈 Update gitignore with Poetry 2020-04-18 23:29:44 +02:00
Ruslan SamoylovandSebastián Ramírez c8bcc0ba0a Use Poetry for package management (#144)
* use poetry insted of Pipfile

* fix python black version

* set prepare.sh as executable

* revert postgres 11

* use multi-build stage in docker

* fix poetry path

* 🔥 Remove uneeded changes

* 🔧 Move and update Poetry file

* 🙈 Update gitignore

* 🐳 Update Dockerfiles to use Poetry

* 🐳 Update Dockerfiles with Poetry

* 🔧 Add SERVER_NAME required by Celery worker

* 🐳 Update Poetry install to avoid env conflicts

*  Add Pytest to Poetry dependencies

Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2020-04-18 23:27:48 +02:00
Sebastián Ramírez 0a194b3b00 📝 Update README, sync with FastAPI docs 2020-04-18 17:48:48 +02:00
Sebastián Ramírez 94b2474438 📝 Update release notes 2020-04-18 10:16:16 +02:00
Sebastián Ramírez af4e0cfe10 🐛 Fix Windows line endings for shell scripts after generation (#149) 2020-04-18 10:15:00 +02:00
Sebastián Ramírez 001dbda103 📝 Update release notes 2020-04-17 16:35:15 +02:00
Brendon SmithandSebastián Ramírez 34f6f9ae54 ⬆️ Upgrade to Vue CLI 4 (#120)
* Upgrade to Vue CLI 4

https://cli.vuejs.org/migrating-from-v3

* 🔥 Remove package-lock.json that varies by system

Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2020-04-17 16:33:51 +02:00
Sebastián Ramírez 0c8e682a90 📝 Update release notes 2020-04-17 14:56:05 +02:00
Matthew ShuandSebastián Ramírez 67b384f308 🔥 Remove duplicate 'login' tag (#135)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2020-04-17 14:54:47 +02:00
Sebastián Ramírez 4bd791c11d 📝 Update release notes 2020-04-17 14:34:37 +02:00
Radek Lonka 697b4da6b0 🐛 Fix welcome message to show email if full name doe not exists (#129) 2020-04-17 14:31:30 +02:00
Sebastián Ramírez 854cc709d1 📝 Update release notes 2020-04-17 14:22:02 +02:00
Brendon Smith 21c4d11659 🎨 Bring Python code into compliance with Black and Flake8 (#121)
* Ignore Flake8 unused import error F401

https://flake8.readthedocs.io/en/latest/user/error-codes.html

The apparently unused imports may be needed for SQLAlchemy.

As the code comment says:

make sure all SQL Alchemy models are imported before initializing DB
otherwise, SQL Alchemy might fail to initialize properly relationships

See GitHub 28 and 29

* Ignore Flake8 unused variable error F841

https://flake8.readthedocs.io/en/latest/user/error-codes.html

The apparently unused variables may be needed for tests.

* Bring line length into compliance with Black

Should be 88 characters.

* Format alembic code with Black
2020-04-17 14:20:48 +02:00
Sebastián Ramírez bcee2427b9 📝 Update release notes 2020-04-17 09:41:34 +02:00
Albert IribarneandSebastián Ramírez 8a2252f654 ♻️ Simplify DB base class declaration (#117)
* Simplify DB base class declaration

* ♻️ Remove object inheritance

Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2020-04-17 09:39:25 +02:00
Sebastián Ramírez 8ff61e813e 📝 Update release notes 2020-04-17 09:21:32 +02:00
fb874fea35 Update CRUD utils for users handling password hashing (#106)
* Add some information how to run backand test for local backand development

* Bug fixes in backend app

* 🎨 Update format

*  Use random_email for test_update_user

Co-authored-by: Mocsar Kalman <mocsar.kalman@gravityrd.com>
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2020-04-17 09:20:00 +02:00
Sebastián Ramírez 2b9ed9333a 📝 Update release notes 2020-04-17 08:07:39 +02:00
gcharbon 45510b4f80 ♻️ Use . instead of source in build-push.sh (#98) 2020-04-17 08:04:42 +02:00
Sebastián Ramírez 5a79f4e427 📝 Update release notes 2020-04-17 08:01:35 +02:00
Stephen Brown IIandSebastián Ramírez 79631c7619 Use Pydantic BaseSettings for config settings (#87)
* Use Pydantic BaseSettings for config settings

* Update fastapi dep to >=0.47.0 and email_validator to email-validator

* Fix deprecation warning for Pydantic >=1.0

* Properly support old-format comma separated strings for BACKEND_CORS_ORIGINS

Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2020-04-17 07:56:10 +02:00
Sebastián Ramírez cd875e5bef 👷 Add GitHub action issue-manager 2020-04-12 13:10:38 +02:00
Sebastián Ramírez 1a92a0a6f1 🔥 Remove package-lock.json 2020-04-06 17:28:53 +02:00
Sebastián Ramírez 2eb5b030bd 📝 Update release notes 2020-04-06 12:39:26 +02:00
Sebastián Ramírez 7c2c2276d9 ♻️ Simplify Traefik labels in services (#139) 2020-04-06 12:38:28 +02:00
Sebastián Ramírez baf584a6cd 📝 Update release notes 2020-04-06 11:37:52 +02:00
Teomor SzczurekandSebastián Ramírez 970a182ec8 Add email validation (#40)
* modify tests

*  Add email-validator to Dockerfiles

* ♻️ Update random email generation

* ♻️ Re-apply email validation after rebase

Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2020-04-06 11:36:29 +02:00
Sebastián Ramírez 1d8678235d 📝 Update release notes 2020-02-07 23:17:38 +01:00
Ashton Shears 71f430616c ✏️ Fix typo (#83) 2020-02-07 21:46:09 +01:00
Abhishek S 43e508239c :✏️ Fix typo (#80) 2020-02-07 21:44:37 +01:00
Cristobal Aguirre dc712ac4ec 🐛 Fix typo in read_item GET view (#74) 2020-02-07 21:28:45 +01:00
Sebastián Ramírez 141f6cdb6e 📝 Update release notes 2020-02-07 21:17:28 +01:00
Daniel Butler fc403c9bc1 ✏️ Correct grammar (#70) 2020-02-07 21:15:10 +01:00
David Montague 4b93dc709f 🐛 Fix docker configuration for flower (#37) 2020-02-07 21:04:02 +01:00
Sebastián Ramírez 2db416d3c1 📝 Update release notes 2020-01-19 22:49:17 +01:00
Manu ab46165387 Add base class to simplify CRUD (#23) 2020-01-19 22:40:50 +01:00
Sebastián Ramírez 1c975c7f2d 📝 Update release notes 2020-01-19 13:27:07 +01:00
Manu 248ea56c6e Add normal-user fixture for testing (#20) 2020-01-19 13:25:17 +01:00
Sebastián Ramírez 44d8a4358b 🔖 Release version 0.4.0 2019-05-29 09:49:17 +04:00
Sebastián Ramírez 9b4108fdae 📝 Update release notes 2019-05-29 09:48:28 +04:00
Sebastián Ramírez b4fa418e65 🔒 Receive token as body in reset password (#34) 2019-05-29 09:47:59 +04:00
Sebastián Ramírez a612765b83 📝 Update release notes, clarify text 2019-05-29 09:35:13 +04:00
Sebastián Ramírez de7140f1e7 📝 Update release notes 2019-05-29 09:27:04 +04:00
dmontagu 546dc8bdcb 🔒 Update login.py to receive password as body (#33)
Change `new_password` from a query parameter to a body parameter for security.

(Why this is problematic is discussed in the top answer to https://stackoverflow.com/questions/2629222/are-querystring-parameters-secure-in-https-http-ssl)
2019-05-29 09:24:09 +04:00
Sebastián Ramírez eae33cda72 📝 Update release notes 2019-05-22 15:30:51 +04:00
Manu 1d30172e7a 🗃️ Fix SQLAlchemy class lookup (#29) 2019-05-22 15:29:24 +04:00
Sebastián Ramírez 6fc9a37eb5 📝 Update release notes 2019-05-22 15:21:02 +04:00
Manu 170231783a 🗃️ Fix SQLAlchemy operation error after database restarts (#32) 2019-05-22 15:18:59 +04:00
Sebastián Ramírez 5216fcfd77 📝 Update release notes 2019-05-04 00:04:30 +04:00
Manu 8bf3607d2b 📝 Fix the paths of the scripts in README (#19)
* removed postgres_password from alembic.ini, read it from env var instead

* ♻️ use f-strings for PostgreSQL URL

* fix path to scripts
2019-05-03 23:57:12 +04:00
Sebastián Ramírez 8ce745b7ef 📝 Update release notes 2019-05-03 23:52:42 +04:00
Sebastián Ramírez 6bbd58c76f 📝 Update docs for running tests live 2019-05-03 23:52:23 +04:00
Manu 1aeb3208bf Use extra pytest arguments forwarded from shell (#17)
* removed postgres_password from alembic.ini, read it from env var instead

* ♻️ use f-strings for PostgreSQL URL

* passes given args
2019-05-03 23:44:18 +04:00
Sebastián Ramírez 45317e54c7 📝 Update release notes 2019-04-24 22:46:09 +04:00
Sebastián Ramírez 47e0fe56e3 ⬆️ Upgrade Jupyter to use Lab, update util/env var for local development 2019-04-24 22:45:20 +04:00
Sebastián Ramírez 42ee0fe0ba 📝 Update release notes 2019-04-20 19:59:47 +04:00
Sebastián Ramírez 92b757fc96 ♻️ Create Item from all fields in Pydantic model 2019-04-20 19:57:34 +04:00
Manu bece399368 ♻️ removed postgres_password from alembic.ini (#9)
♻️ removed postgres_password from alembic.ini (#9)
2019-04-20 19:56:50 +04:00
Sebastián Ramírez 5dd83c6350 🔧 Update development scripts 2019-04-20 19:24:57 +04:00
360 changed files with 20063 additions and 19616 deletions
+1
View File
@@ -0,0 +1 @@
{{ _copier_answers|to_json -}}
+26
View File
@@ -0,0 +1,26 @@
from pathlib import Path
import json
# Update the .env file with the answers from the .copier-answers.yml file
# without using Jinja2 templates in the .env file, this way the code works as is
# without needing Copier, but if Copier is used, the .env file will be updated
root_path = Path(__file__).parent.parent
answers_path = Path(__file__).parent / ".copier-answers.yml"
answers = json.loads(answers_path.read_text())
env_path = root_path / ".env"
env_content = env_path.read_text()
lines = []
for line in env_content.splitlines():
for key, value in answers.items():
upper_key = key.upper()
if line.startswith(f"{upper_key}="):
if " " in value:
content = f"{upper_key}={value!r}"
else:
content = f"{upper_key}={value}"
new_line = line.replace(line, content)
lines.append(new_line)
break
else:
lines.append(line)
env_path.write_text("\n".join(lines))
+38
View File
@@ -0,0 +1,38 @@
# Domain
# This would be set to the production domain with an env var on deployment
DOMAIN=localhost
# Environment: local, staging, production
ENVIRONMENT=local
PROJECT_NAME="Full Stack FastAPI Project"
STACK_NAME=full-stack-fastapi-project
# Backend
BACKEND_CORS_ORIGINS="http://localhost,http://localhost:5173,https://localhost,https://localhost:5173,http://localhost.tiangolo.com"
SECRET_KEY=changethis
FIRST_SUPERUSER=admin@example.com
FIRST_SUPERUSER_PASSWORD=changethis
USERS_OPEN_REGISTRATION=False
# Emails
SMTP_HOST=
SMTP_USER=
SMTP_PASSWORD=
EMAILS_FROM_EMAIL=info@example.com
SMTP_TLS=True
SMTP_SSL=False
SMTP_PORT=587
# Postgres
POSTGRES_SERVER=localhost
POSTGRES_PORT=5432
POSTGRES_DB=app
POSTGRES_USER=postgres
POSTGRES_PASSWORD=changethis
SENTRY_DSN=
# Configure these with your own Docker registry images
DOCKER_IMAGE_BACKEND=backend
DOCKER_IMAGE_FRONTEND=frontend
+2
View File
@@ -0,0 +1,2 @@
* text=auto
*.sh text eol=lf
+1
View File
@@ -0,0 +1 @@
github: [tiangolo]
+16
View File
@@ -0,0 +1,16 @@
version: 2
updates:
# GitHub Actions
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "daily"
commit-message:
prefix:
# Python
- package-ecosystem: "pip"
directory: "/"
schedule:
interval: "daily"
commit-message:
prefix:
+29
View File
@@ -0,0 +1,29 @@
name: Deploy to Production
on:
release:
types:
- published
jobs:
deploy:
runs-on:
- self-hosted
- production
env:
ENVIRONMENT: production
DOMAIN: ${{ secrets.DOMAIN_PRODUCTION }}
SECRET_KEY: ${{ secrets.SECRET_KEY }}
FIRST_SUPERUSER: ${{ secrets.FIRST_SUPERUSER }}
FIRST_SUPERUSER_PASSWORD: ${{ secrets.FIRST_SUPERUSER_PASSWORD }}
SMTP_HOST: ${{ secrets.SMTP_HOST }}
SMTP_USER: ${{ secrets.SMTP_USER }}
SMTP_PASSWORD: ${{ secrets.SMTP_PASSWORD }}
EMAILS_FROM_EMAIL: ${{ secrets.EMAILS_FROM_EMAIL }}
POSTGRES_PASSWORD: ${{ secrets.POSTGRES_PASSWORD }}
SENTRY_DSN: ${{ secrets.SENTRY_DSN }}
steps:
- name: Checkout
uses: actions/checkout@v4
- run: docker compose -f docker-compose.yml build
- run: docker compose -f docker-compose.yml up -d
+29
View File
@@ -0,0 +1,29 @@
name: Deploy to Staging
on:
push:
branches:
- master
jobs:
deploy:
runs-on:
- self-hosted
- staging
env:
ENVIRONMENT: staging
DOMAIN: ${{ secrets.DOMAIN_STAGING }}
SECRET_KEY: ${{ secrets.SECRET_KEY }}
FIRST_SUPERUSER: ${{ secrets.FIRST_SUPERUSER }}
FIRST_SUPERUSER_PASSWORD: ${{ secrets.FIRST_SUPERUSER_PASSWORD }}
SMTP_HOST: ${{ secrets.SMTP_HOST }}
SMTP_USER: ${{ secrets.SMTP_USER }}
SMTP_PASSWORD: ${{ secrets.SMTP_PASSWORD }}
EMAILS_FROM_EMAIL: ${{ secrets.EMAILS_FROM_EMAIL }}
POSTGRES_PASSWORD: ${{ secrets.POSTGRES_PASSWORD }}
SENTRY_DSN: ${{ secrets.SENTRY_DSN }}
steps:
- name: Checkout
uses: actions/checkout@v4
- run: docker compose -f docker-compose.yml build
- run: docker compose -f docker-compose.yml up -d
+28
View File
@@ -0,0 +1,28 @@
name: Issue Manager
on:
schedule:
- cron: "0 0 * * *"
issue_comment:
types:
- created
- edited
issues:
types:
- labeled
jobs:
issue-manager:
runs-on: ubuntu-latest
steps:
- uses: tiangolo/issue-manager@0.5.0
with:
token: ${{ secrets.GITHUB_TOKEN }}
config: >
{
"answered": {
"users": ["tiangolo"],
"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."
}
}
+39
View File
@@ -0,0 +1,39 @@
name: Latest Changes
on:
pull_request_target:
branches:
- master
types:
- closed
workflow_dispatch:
inputs:
number:
description: PR number
required: true
debug_enabled:
description: 'Run the build with tmate debugging enabled (https://github.com/marketplace/actions/debugging-with-tmate)'
required: false
default: 'false'
jobs:
latest-changes:
runs-on: ubuntu-latest
steps:
- name: Dump GitHub context
env:
GITHUB_CONTEXT: ${{ toJson(github) }}
run: echo "$GITHUB_CONTEXT"
- uses: actions/checkout@v4
with:
# To allow latest-changes to commit to the main branch
token: ${{ secrets.FULL_STACK_FASTAPI_POSTGRESQL_LATEST_CHANGES }}
- uses: docker://tiangolo/latest-changes:0.3.0
# - uses: tiangolo/latest-changes@main
with:
token: ${{ secrets.GITHUB_TOKEN }}
latest_changes_file: ./release-notes.md
latest_changes_header: '## Latest Changes'
end_regex: '^## '
debug_logs: true
label_header_prefix: '### '
+35
View File
@@ -0,0 +1,35 @@
name: Smokeshow
on:
workflow_run:
workflows: [Test]
types: [completed]
permissions:
statuses: write
jobs:
smokeshow:
if: ${{ github.event.workflow_run.conclusion == 'success' }}
runs-on: ubuntu-latest
steps:
- uses: actions/setup-python@v5
with:
python-version: '3.9'
- run: pip install smokeshow
- uses: dawidd6/action-download-artifact@v3.1.2
with:
workflow: test.yml
commit: ${{ github.event.workflow_run.head_sha }}
- run: smokeshow upload coverage-html
env:
SMOKESHOW_GITHUB_STATUS_DESCRIPTION: Coverage {coverage-percentage}
SMOKESHOW_GITHUB_COVERAGE_THRESHOLD: 90
SMOKESHOW_GITHUB_CONTEXT: coverage
SMOKESHOW_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
SMOKESHOW_GITHUB_PR_HEAD_SHA: ${{ github.event.workflow_run.head_sha }}
SMOKESHOW_AUTH_KEY: ${{ secrets.SMOKESHOW_AUTH_KEY }}
+49
View File
@@ -0,0 +1,49 @@
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) }}
-2
View File
@@ -1,3 +1 @@
.vscode .vscode
testing-project
.mypy_cache
+23
View File
@@ -0,0 +1,23 @@
# See https://pre-commit.com for more information
# See https://pre-commit.com/hooks.html for more hooks
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
hooks:
- id: check-added-large-files
- id: check-toml
- id: check-yaml
args:
- --unsafe
- id: end-of-file-fixer
- id: trailing-whitespace
- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: v0.2.2
hooks:
- id: ruff
args:
- --fix
- id: ruff-format
ci:
autofix_commit_msg: 🎨 [pre-commit.ci] Auto format from pre-commit.com hooks
autoupdate_commit_msg: ⬆ [pre-commit.ci] pre-commit autoupdate
-12
View File
@@ -1,12 +0,0 @@
sudo: required
language: python
install:
- pip install cookiecutter
services:
- docker
script:
- bash ./test.sh
+28
View File
@@ -0,0 +1,28 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Debug FastAPI Project backend: Python Debugger",
"type": "debugpy",
"request": "launch",
"module": "uvicorn",
"args": [
"app.main:app",
"--reload"
],
"cwd": "${workspaceFolder}/backend",
"jinja": true,
"envFile": "${workspaceFolder}/.env",
},
{
"type": "chrome",
"request": "launch",
"name": "Debug Frontend: Launch Chrome against http://localhost:5173",
"url": "http://localhost:5173",
"webRoot": "${workspaceFolder}/frontend"
},
]
}
+120 -156
View File
@@ -1,204 +1,168 @@
# Full Stack FastAPI and PostgreSQL - Base Project Generator # Full Stack FastAPI Template
[![Build Status](https://travis-ci.org/tiangolo/full-stack-fastapi-postgresql.svg?branch=master)](https://travis-ci.org/tiangolo/full-stack-fastapi-postgresql) <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://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>
Generate a backend and frontend stack using Python, including interactive API documentation. ### Dashboard - Dark Mode
### Interactive API documentation [![API docs](img/dashboard-dark.png)](https://github.com/tiangolo/full-stack-fastapi-postgresql)
[![API docs](img/docs.png)](https://github.com/tiangolo/full-stack-fastapi-postgresql) ## Technology Stack and Features
### Alternative API documentation
[![API docs](img/redoc.png)](https://github.com/tiangolo/full-stack-fastapi-postgresql)
- ⚡ [**FastAPI**](https://fastapi.tiangolo.com) for the Python backend API.
- 🧰 [SQLModel](https://sqlmodel.tiangolo.com) for the Python SQL database interactions (ORM).
- 🔍 [Pydantic](https://docs.pydantic.dev), used by FastAPI, for the data validation and settings management.
- 💾 [PostgreSQL](https://www.postgresql.org) as the SQL database.
- 🚀 [React](https://react.dev) for the frontend.
- 💃 Using TypeScript, hooks, Vite, and other parts of a modern frontend stack.
- 🎨 [Chakra UI](https://chakra-ui.com) for the frontend components.
- 🤖 An automatically generated frontend client.
- 🦇 Dark mode support.
- 🐋 [Docker Compose](https://www.docker.com) for development and production.
- 🔒 Secure password hashing by default.
- 🔑 JWT token authentication.
- 📫 Email based password recovery.
- ✅ Tests with [Pytest](https://pytest.org).
- 📞 [Traefik](https://traefik.io) as a reverse proxy / load balancer.
- 🚢 Deployment instructions using Docker Compose, including how to set up a frontend Traefik proxy to handle automatic HTTPS certificates.
- 🏭 CI (continuous integration) and CD (continuous deployment) based on GitHub Actions.
### Dashboard Login ### Dashboard Login
[![API docs](img/login.png)](https://github.com/tiangolo/full-stack-fastapi-postgresql) [![API docs](img/login.png)](https://github.com/tiangolo/full-stack-fastapi-template)
### Dashboard - Admin
[![API docs](img/dashboard.png)](https://github.com/tiangolo/full-stack-fastapi-template)
### Dashboard - Create User ### Dashboard - Create User
[![API docs](img/dashboard.png)](https://github.com/tiangolo/full-stack-fastapi-postgresql) [![API docs](img/dashboard-create.png)](https://github.com/tiangolo/full-stack-fastapi-template)
### Dashboard - Items
[![API docs](img/dashboard-items.png)](https://github.com/tiangolo/full-stack-fastapi-template)
### Dashboard - User Settings
[![API docs](img/dashboard-user-settings.png)](https://github.com/tiangolo/full-stack-fastapi-template)
### Interactive API documentation
[![API docs](img/docs.png)](https://github.com/tiangolo/full-stack-fastapi-template)
## Features
* Full **Docker** integration (Docker based).
* Docker Swarm Mode deployment.
* **Docker Compose** integration and optimization for local development
* **Production ready** Python web server using Uvicorn and Gunicorn.
* Python **[FastAPI](https://github.com/tiangolo/fastapi)** backend:
* **Fast**: Very high performance, on par with **NodeJS** and **Go** (thanks to Starlette and Pydantic).
* **Intuitive**: Great editor support. <abbr title="also known as auto-complete, autocompletion, IntelliSense">Completion</abbr> everywhere. Less time debugging.
* **Easy**: Designed to be easy to use and learn. Less time reading docs.
* **Short**: Minimize code duplication. Multiple features from each parameter declaration.
* **Robust**: Get production-ready code. With automatic interactive documentation.
* **Standards-based**: Based on (and fully compatible with) the open standards for APIs: <a href="https://github.com/OAI/OpenAPI-Specification" target="_blank">OpenAPI</a> and <a href="http://json-schema.org/" target="_blank">JSON Schema</a>.
* [**Many other features**](https://github.com/tiangolo/fastapi) including automatic validation, serialization, interactive documentation, authentication with OAuth2 JWT tokens, etc.
* **Secure password** hashing by default.
* **JWT token** authentication.
* **SQLAlchemy** models (independent of Flask extensions, so they can be used with Celery workers directly).
* Basic starting models for users (modify and remove as you need).
* **Alembic** migrations.
* **CORS** (Cross Origin Resource Sharing).
* **Celery** worker that can import and use models and code from the rest of the backend selectively (you don't have to install the complete app in each worker).
* REST backend tests based on **Pytest**, integrated with Docker, so you can test the full API interaction, independent on the database. As it runs in Docker, it can build a new data store from scratch each time (so you can use ElasticSearch, MongoDB, CouchDB, or whatever you want, and just test that the API works).
* Easy Python integration with **Jupyter Kernels** for remote or in-Docker development with extensions like Atom Hydrogen or Visual Studio Code Jupyter.
* **Vue** frontend:
* Generated with Vue CLI.
* **JWT Authentication** handling.
* Login view.
* After login, main dashboard view.
* Main dashboard with user creation and edition.
* Self user edition.
* **Vuex**.
* **Vue-router**.
* **Vuetify** for beautiful material design components.
* **TypeScript**.
* Docker server based on **Nginx** (configured to play nicely with Vue-router).
* Docker multi-stage building, so you don't need to save or commit compiled code.
* Frontend tests ran at build time (can be disabled too).
* Made as modular as possible, so it works out of the box, but you can re-generate with Vue CLI or create it as you need, and re-use what you want.
* **PGAdmin** for PostgreSQL database, you can modify it to use PHPMyAdmin and MySQL easily.
* **Flower** for Celery jobs monitoring.
* Load balancing between frontend and backend with **Traefik**, so you can have both under the same domain, separated by path, but served by different containers.
* Traefik integration, including Let's Encrypt **HTTPS** certificates automatic generation.
* GitLab **CI** (continuous integration), including frontend and backend testing.
## How to use it ## How to use it
Go to the directoy where you want to create your project and run: You can **just fork or clone** this repository and use it as is.
✨ It just works. ✨
### Configure
You can then update configs in the `.env` files to customize your configurations.
Before deploying it, make sure you change at least the values for:
- `SECRET_KEY`
- `FIRST_SUPERUSER_PASSWORD`
- `POSTGRES_PASSWORD`
### Generate secret keys
Some environment variables in the `.env` file have a default value of `changethis`.
You have to change them with a secret key, to generate secret keys you can run the following command:
```bash ```bash
pip install cookiecutter python -c "import secrets; print(secrets.token_urlsafe(32))"
cookiecutter https://github.com/tiangolo/full-stack-fastapi-postgresql
``` ```
### Generate passwords Copy the content and use that as password / secret key. And run that again to generate another secure key.
You will be asked to provide passwords and secret keys for several components. Open another terminal and run: ## How to use it - alternative with Copier
This repository also supports generating a new project using [Copier](https://copier.readthedocs.io).
It will copy all the files, ask you configuration questions, and update the `.env` files with your answers.
### Install Copier
You can install Copier with:
```bash ```bash
openssl rand -hex 32 pip install copier
# Outputs something like: 99d3b1f01aa639e4a76f4fc281fc834747a543720ba4c8a8648ba755aef9be7f
``` ```
Copy the contents and use that as password / secret key. And run that again to generate another secure key. Or better, if you have [`pipx`](https://pipx.pypa.io/), you can run it with:
```bash
pipx install copier
```
**Note**: If you have `pipx`, installing copier is optional, you could run it directly.
### Generate a Project with Copier
Decide a name for your new project's directory, you will use it below. For example, `my-awesome-project`.
Go to the directory that will be the parent of your project, and run the command with your project's name:
```bash
copier copy https://github.com/tiangolo/full-stack-fastapi-template my-awesome-project --trust
```
If you have `pipx` and you didn't install `copier`, you can run it directly:
```bash
pipx run copier copy https://github.com/tiangolo/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.
### Input variables ### Input variables
The generator (cookiecutter) 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.
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`: The name of the project - `project_name`: (default: `"FastAPI Project"`) The name of the project, shown to API users (in .env).
* `project_slug`: The development friendly name of the project. By default, based on the project name - `stack_name`: (default: `"fastapi-project"`) The name of the stack used for Docker Compose labels (no spaces) (in .env).
* `domain_main`: The domain in where to deploy the project for production (from the branch `production`), used by the load balancer, backend, etc. By default, based on the project slug. - `secret_key`: (default: `"changethis"`) The secret key for the project, used for security, stored in .env, you can generate one with the method above.
* `domain_staging`: The domain in where to deploy while staging (before production) (from the branch `master`). By default, based on the main domain. - `first_superuser`: (default: `"admin@example.com"`) The email of the first superuser (in .env).
- `first_superuser_password`: (default: `"changethis"`) The password of the first superuser (in .env).
- `smtp_host`: (default: "") The SMTP server host to send emails, you can set it later in .env.
- `smtp_user`: (default: "") The SMTP server user to send emails, you can set it later in .env.
- `smtp_password`: (default: "") The SMTP server password to send emails, you can set it later in .env.
- `emails_from_email`: (default: `"info@example.com"`) The email account to send emails from, you can set it later in .env.
- `postgres_password`: (default: `"changethis"`) The password for the PostgreSQL database, stored in .env, you can generate one with the method above.
- `sentry_dsn`: (default: "") The DSN for Sentry, if you are using it, you can set it later in .env.
* `docker_swarm_stack_name_main`: The name of the stack while deploying to Docker in Swarm mode for production. By default, based on the domain. ## Backend Development
* `docker_swarm_stack_name_staging`: The name of the stack while deploying to Docker in Swarm mode for staging. By default, based on the domain.
* `secret_key`: Backend server secret key. Use the method above to generate it. Backend docs: [backend/README.md](./backend/README.md).
* `first_superuser`: The first superuser generated, with it you will be able to create more users, etc. By default, based on the domain.
* `first_superuser_password`: First superuser password. Use the method above to generate it.
* `backend_cors_origins`: Origins (domains, more or less) that are enabled for CORS (Cross Origin Resource Sharing). This allows a frontend in one domain (e.g. `https://dashboard.example.com`) to communicate with this backend, that could be living in another domain (e.g. `https://api.example.com`). It can also be used to allow your local frontend (with a custom `hosts` domain mapping, as described in the project's `README.md`) that could be living in `http://dev.example.com:8080` to cummunicate with the backend at `https://stag.example.com`. Notice the `http` vs `https` and the `dev.` prefix for local development vs the "staging" `stag.` prefix. By default, it includes origins for production, staging and development, with ports commonly used during local development by several popular frontend frameworks (Vue with `:8080`, React, Angular).
* `smtp_port`: Port to use to send emails via SMTP. By default `587`.
* `smtp_host`: Host to use to send emails, it would be given by your email provider, like Mailgun, Sparkpost, etc.
* `smtp_user`: The user to use in the SMTP connection. The value will be given by your email provider.
* `smtp_password`: The password to be used in the SMTP connection. The value will be given by the email provider.
* `smtp_emails_from_email`: The email account to use as the sender in the notification emails, it would be something like `info@your-custom-domain.com`.
* `postgres_password`: Postgres database password. Use the method above to generate it. (You could easily modify it to use MySQL, MariaDB, etc). ## Frontend Development
* `pgadmin_default_user`: PGAdmin default user, to log-in to the PGAdmin interface.
* `pgadmin_default_user_password`: PGAdmin default user password. Generate it with the method above.
* `traefik_constraint_tag`: The tag to be used by the internal Traefik load balancer (for example, to divide requests between backend and frontend) for production. Used to separate this stack from any other stack you might have. This should identify each stack in each environment (production, staging, etc). Frontend docs: [frontend/README.md](./frontend/README.md).
* `traefik_constraint_tag_staging`: The Traefik tag to be used while on staging.
* `traefik_public_network`: This assumes you have another separate publicly facing Traefik at the server / cluster level. This is the network that main Traefik lives in.
* `traefik_public_constraint_tag`: The tag that should be used by stack services that should communicate with the public.
* `flower_auth`: Basic HTTP authentication for flower, in the form`user:password`. By default: "`root:changethis`". ## Deployment
* `sentry_dsn`: Key URL (DSN) of Sentry, for live error reporting. If you are not using it yet, you should, is open source. E.g.: `https://1234abcd:5678ef@sentry.example.com/30`. Deployment docs: [deployment.md](./deployment.md).
* `docker_image_prefix`: Prefix to use for Docker image names. If you are using GitLab Docker registry it would be based on your code repository. E.g.: `git.example.com/development-team/my-awesome-project/`. ## Development
* `docker_image_backend`: Docker image name for the backend. By default, it will be based on your Docker image prefix, e.g.: `git.example.com/development-team/my-awesome-project/backend`. And depending on your environment, a different tag will be appended ( `prod`, `stag`, `branch` ). So, the final image names used will be like: `git.example.com/development-team/my-awesome-project/backend:prod`.
* `docker_image_celeryworker`: Docker image for the celery worker. By default, based on your Docker image prefix.
* `docker_image_frontend`: Docker image for the frontend. By default, based on your Docker image prefix.
## How to deploy General development docs: [development.md](./development.md).
This stack can be adjusted and used with several deployment options that are compatible with Docker Compose, but it is designed to be used in a cluster controlled with pure Docker in Swarm Mode with a Traefik main load balancer proxy handling automatic HTTPS certificates, using the ideas from <a href="https://dockerswarm.rocks" target="_blank">DockerSwarm.rocks</a>. This includes using Docker Compose, custom local domains, `.env` configurations, etc.
Please refer to <a href="https://dockerswarm.rocks" target="_blank">DockerSwarm.rocks</a> to see how to deploy such a cluster in 20 minutes.
## More details
After using this generator, your new project (the directory created) will contain an extensive `README.md` with instructions for development, deployment, etc. You can pre-read [the project `README.md` template here too](./{{cookiecutter.project_slug}}/README.md).
## Sibling project generators
* Based on Couchbase: [https://github.com/tiangolo/full-stack-fastapi-couchbase](https://github.com/tiangolo/full-stack-fastapi-couchbase).
## Release Notes ## Release Notes
### Next release Check the file [release-notes.md](./release-notes.md).
### 0.3.0
* PR <a href="https://github.com/tiangolo/full-stack-fastapi-postgresql/pull/14" target="_blank">#14</a>:
* Update CRUD utils to use types better.
* Simplify Pydantic model names, from `UserInCreate` to `UserCreate`, etc.
* Upgrade packages.
* Add new generic "Items" models, crud utils, endpoints, and tests. To facilitate re-using them to create new functionality. As they are simple and generic (not like Users), it's easier to copy-paste and adapt them to each use case.
* Update endpoints/*path operations* to simplify code and use new utilities, prefix and tags in `include_router`.
* Update testing utils.
* Update linting rules, relax vulture to reduce false positives.
* Update migrations to include new Items.
* Update project README.md with tips about how to start with backend.
* Upgrade Python to 3.7 as Celery is now compatible too. <a href="https://github.com/tiangolo/full-stack-fastapi-postgresql/pull/10" target="_blank">PR #10</a> by <a href="https://github.com/ebreton" target="_blank">@ebreton</a>.
### 0.2.2
* Fix frontend hijacking /docs in development. Using latest https://github.com/tiangolo/node-frontend with custom Nginx configs in frontend. <a href="https://github.com/tiangolo/full-stack-fastapi-postgresql/pull/6" target="_blank">PR #6</a>.
### 0.2.1
* Fix documentation for *path operation* to get user by ID. <a href="https://github.com/tiangolo/full-stack-fastapi-postgresql/pull/4" target="_blank">PR #4</a> by <a href="https://github.com/mpclarkson" target="_blank">@mpclarkson</a> in FastAPI.
* Set `/start-reload.sh` as a command override for development by default.
* Update generated README.
### 0.2.0
**<a href="https://github.com/tiangolo/full-stack-fastapi-postgresql/pull/2" target="_blank">PR #2</a>**:
* Simplify and update backend `Dockerfile`s.
* Refactor and simplify backend code, improve naming, imports, modules and "namespaces".
* Improve and simplify Vuex integration with TypeScript accessors.
* Standardize frontend components layout, buttons order, etc.
* Add local development scripts (to develop this project generator itself).
* Add logs to startup modules to detect errors early.
* Improve FastAPI dependency utilities, to simplify and reduce code (to require a superuser).
### 0.1.2
* Fix path operation to update self-user, set parameters as body payload.
### 0.1.1
Several bug fixes since initial publication, including:
* Order of path operations for users.
* Frontend sending login data in the correct format.
* Add https://localhost variants to CORS.
## License ## License
This project is licensed under the terms of the MIT license. The Full Stack FastAPI Template is licensed under the terms of the MIT license.
+8
View File
@@ -0,0 +1,8 @@
# Python
__pycache__
app.egg-info
*.pyc
.mypy_cache
.coverage
htmlcov
.venv
+8
View File
@@ -0,0 +1,8 @@
__pycache__
app.egg-info
*.pyc
.mypy_cache
.coverage
htmlcov
.cache
.venv
+28
View File
@@ -0,0 +1,28 @@
FROM tiangolo/uvicorn-gunicorn-fastapi:python3.10
WORKDIR /app/
# Install Poetry
RUN curl -sSL https://install.python-poetry.org | POETRY_HOME=/opt/poetry python && \
cd /usr/local/bin && \
ln -s /opt/poetry/bin/poetry && \
poetry config virtualenvs.create false
# Copy poetry.lock* in case it doesn't exist in the repo
COPY ./pyproject.toml ./poetry.lock* /app/
# Allow installing dev dependencies to run tests
ARG INSTALL_DEV=false
RUN bash -c "if [ $INSTALL_DEV == 'true' ] ; then poetry install --no-root ; else poetry install --no-root --only main ; fi"
ENV PYTHONPATH=/app
COPY ./scripts/ /app/
COPY ./alembic.ini /app/
COPY ./prestart.sh /app/
COPY ./tests-start.sh /app/
COPY ./app /app/app
+198
View File
@@ -0,0 +1,198 @@
# FastAPI Project - Backend
## Requirements
* [Docker](https://www.docker.com/).
* [Poetry](https://python-poetry.org/) for Python package and environment management.
## Local Development
* Start the stack with Docker Compose:
```bash
docker compose up -d
```
* Now you can open your browser and interact with these URLs:
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:
```console
$ poetry install
```
Then you can start a shell session with the new environment with:
```console
$ poetry shell
```
Make sure your editor is using the correct Python virtual environment.
Modify or add SQLModel models for data and SQL tables in `./backend/app/models.py`, API endpoints in `./backend/app/api/`, CRUD (Create, Read, Update, Delete) utils in `./backend/app/crud.py`.
### VS Code
There are already configurations in place to run the backend through the VS Code debugger, so that you can use breakpoints, pause and explore variables, etc.
The setup is also already configured so you can run the tests through the VS Code Python tests tab.
### Docker Compose Override
During development, you can change Docker Compose settings that will only affect the local development environment in the file `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.
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.
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:
```console
$ docker compose up -d
```
There is also a commented out `command` override, you can uncomment it and comment the default one. It makes the backend container run a process that does "nothing", but keeps the container alive. That allows you to get inside your running container and execute commands inside, for example a Python interpreter to test installed dependencies, or start the development server that reloads when it detects changes.
To get inside the container with a `bash` session you can start the stack with:
```console
$ docker compose up -d
```
and then `exec` inside the running container:
```console
$ docker compose exec backend bash
```
You should see an output like:
```console
root@7f2607af31c3:/app#
```
that means that you are in a `bash` session inside your container, as a `root` user, under the `/app` directory, this directory has another directory called "app" inside, that's where your code lives inside the container: `/app/app`.
There you can use the script `/start-reload.sh` to run the debug live reloading server. You can run that script from inside the container with:
```console
$ bash /start-reload.sh
```
...it will look like:
```console
root@7f2607af31c3:/app# bash /start-reload.sh
```
and then hit enter. That runs the live reloading server that auto reloads when it detects code changes.
Nevertheless, if it doesn't detect a change but a syntax error, it will just stop with an error. But as the container is still alive and you are in a Bash session, you can quickly restart it after fixing the error, running the same command ("up arrow" and "Enter").
...this previous detail is what makes it useful to have the container alive doing nothing and then, in a Bash session, make it run the live reload server.
### Backend tests
To test the backend run:
```console
$ bash ./scripts/test.sh
```
The tests run with Pytest, modify and add tests to `./backend/app/tests/`.
If you use GitHub Actions the tests will run automatically.
#### Test running stack
If your stack is already up and you just want to run the tests, you can use:
```bash
docker compose exec backend bash /app/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.
For example, to stop on first error:
```bash
docker compose exec backend bash /app/tests-start.sh -x
```
#### Test Coverage
When the tests are run, a file `htmlcov/index.html` is generated, you can open it in your browser to see the coverage of the tests.
### Migrations
As during local development your app directory is mounted as a volume inside the container, you can also run the migrations with `alembic` commands inside the container and the migration code will be in your app directory (instead of being only inside the container). So you can add it to your git repository.
Make sure you create a "revision" of your models and that you "upgrade" your database with that revision every time you change them. As this is what will update the tables in your database. Otherwise, your application will have errors.
* Start an interactive session in the backend container:
```console
$ docker compose exec backend bash
```
* Alembic is already configured to import your SQLModel models from `./backend/app/models.py`.
* After changing a model (for example, adding a column), inside the container, create a revision, e.g.:
```console
$ alembic revision --autogenerate -m "Add column last_name to User model"
```
* Commit to the git repository the files generated in the alembic directory.
* After creating the revision, run the migration in the database (this is what will actually change the database):
```console
$ alembic upgrade head
```
If you don't want to use migrations at all, uncomment the lines in the file at `./backend/app/db/init_db.py` that end in:
```python
SQLModel.metadata.create_all(engine)
```
and comment the line in the file `prestart.sh` that contains:
```console
$ alembic upgrade head
```
If you don't want to start with the default models and want to remove them / modify them, from the beginning, without having any previous revision, you can remove the revision files (`.py` Python files) under `./backend/app/alembic/versions/`. And then create a first migration as described above.
@@ -2,7 +2,7 @@
[alembic] [alembic]
# path to migration scripts # path to migration scripts
script_location = alembic script_location = app/alembic
# template used to generate migration files # template used to generate migration files
# file_template = %%(rev)s_%%(slug)s # file_template = %%(rev)s_%%(slug)s
@@ -35,9 +35,6 @@ script_location = alembic
# are written from script.py.mako # are written from script.py.mako
# output_encoding = utf-8 # output_encoding = utf-8
sqlalchemy.url = postgresql://postgres:{{cookiecutter.postgres_password}}@db/app
# Logging configuration # Logging configuration
[loggers] [loggers]
keys = root,sqlalchemy,alembic keys = root,sqlalchemy,alembic
+1
View File
@@ -0,0 +1 @@
Generic single-database configuration.
@@ -1,7 +1,8 @@
from __future__ import with_statement import os
from logging.config import fileConfig
from alembic import context from alembic import context
from sqlalchemy import engine_from_config, pool from sqlalchemy import engine_from_config, pool
from logging.config import fileConfig
# this is the Alembic Config object, which provides # this is the Alembic Config object, which provides
# access to the values within the .ini file in use. # access to the values within the .ini file in use.
@@ -17,9 +18,9 @@ fileConfig(config.config_file_name)
# target_metadata = mymodel.Base.metadata # target_metadata = mymodel.Base.metadata
# target_metadata = None # target_metadata = None
from app.db.base import Base # noqa from app.models import SQLModel # noqa
target_metadata = Base.metadata target_metadata = SQLModel.metadata
# other values from the config, defined by the needs of env.py, # other values from the config, defined by the needs of env.py,
# can be acquired: # can be acquired:
@@ -27,6 +28,15 @@ target_metadata = Base.metadata
# ... etc. # ... etc.
def get_url():
user = os.getenv("POSTGRES_USER", "postgres")
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():
"""Run migrations in 'offline' mode. """Run migrations in 'offline' mode.
@@ -39,7 +49,7 @@ def run_migrations_offline():
script output. script output.
""" """
url = config.get_main_option("sqlalchemy.url") url = get_url()
context.configure( context.configure(
url=url, target_metadata=target_metadata, literal_binds=True, compare_type=True url=url, target_metadata=target_metadata, literal_binds=True, compare_type=True
) )
@@ -55,8 +65,10 @@ def run_migrations_online():
and associate a connection with the context. and associate a connection with the context.
""" """
configuration = config.get_section(config.config_ini_section)
configuration["sqlalchemy.url"] = get_url()
connectable = engine_from_config( connectable = engine_from_config(
config.get_section(config.config_ini_section), configuration,
prefix="sqlalchemy.", prefix="sqlalchemy.",
poolclass=pool.NullPool, poolclass=pool.NullPool,
) )
@@ -7,6 +7,7 @@ Create Date: ${create_date}
""" """
from alembic import op from alembic import op
import sqlalchemy as sa import sqlalchemy as sa
import sqlmodel.sql.sqltypes
${imports if imports else ""} ${imports if imports else ""}
# revision identifiers, used by Alembic. # revision identifiers, used by Alembic.
@@ -0,0 +1,54 @@
"""Initialize models
Revision ID: e2412789c190
Revises:
Create Date: 2023-11-24 22:55:43.195942
"""
import sqlalchemy as sa
import sqlmodel.sql.sqltypes
from alembic import op
# revision identifiers, used by Alembic.
revision = "e2412789c190"
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table(
"user",
sa.Column("email", sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column("is_active", sa.Boolean(), nullable=False),
sa.Column("is_superuser", sa.Boolean(), nullable=False),
sa.Column("full_name", sqlmodel.sql.sqltypes.AutoString(), nullable=True),
sa.Column("id", sa.Integer(), nullable=False),
sa.Column(
"hashed_password", sqlmodel.sql.sqltypes.AutoString(), nullable=False
),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(op.f("ix_user_email"), "user", ["email"], unique=True)
op.create_table(
"item",
sa.Column("description", sqlmodel.sql.sqltypes.AutoString(), nullable=True),
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("title", sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column("owner_id", sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(
["owner_id"],
["user.id"],
),
sa.PrimaryKeyConstraint("id"),
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table("item")
op.drop_index(op.f("ix_user_email"), table_name="user")
op.drop_table("user")
# ### end Alembic commands ###
+56
View File
@@ -0,0 +1,56 @@
from collections.abc import Generator
from typing import Annotated
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from jose import JWTError, jwt
from pydantic import ValidationError
from sqlmodel import Session
from app.core import security
from app.core.config import settings
from app.core.db import engine
from app.models import TokenPayload, User
reusable_oauth2 = OAuth2PasswordBearer(
tokenUrl=f"{settings.API_V1_STR}/login/access-token"
)
def get_db() -> Generator[Session, None, None]:
with Session(engine) as session:
yield session
SessionDep = Annotated[Session, Depends(get_db)]
TokenDep = Annotated[str, Depends(reusable_oauth2)]
def get_current_user(session: SessionDep, token: TokenDep) -> User:
try:
payload = jwt.decode(
token, settings.SECRET_KEY, algorithms=[security.ALGORITHM]
)
token_data = TokenPayload(**payload)
except (JWTError, ValidationError):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Could not validate credentials",
)
user = session.get(User, token_data.sub)
if not user:
raise HTTPException(status_code=404, detail="User not found")
if not user.is_active:
raise HTTPException(status_code=400, detail="Inactive user")
return user
CurrentUser = Annotated[User, Depends(get_current_user)]
def get_current_active_superuser(current_user: CurrentUser) -> User:
if not current_user.is_superuser:
raise HTTPException(
status_code=400, detail="The user doesn't have enough privileges"
)
return current_user
@@ -1,6 +1,6 @@
from fastapi import APIRouter from fastapi import APIRouter
from app.api.api_v1.endpoints import items, login, users, utils from app.api.routes import items, login, users, utils
api_router = APIRouter() api_router = APIRouter()
api_router.include_router(login.router, tags=["login"]) api_router.include_router(login.router, tags=["login"])
+102
View File
@@ -0,0 +1,102 @@
from typing import Any
from fastapi import APIRouter, HTTPException
from sqlmodel import func, select
from app.api.deps import CurrentUser, SessionDep
from app.models import Item, ItemCreate, ItemOut, ItemsOut, ItemUpdate, Message
router = APIRouter()
@router.get("/", response_model=ItemsOut)
def read_items(
session: SessionDep, current_user: CurrentUser, skip: int = 0, limit: int = 100
) -> Any:
"""
Retrieve items.
"""
if current_user.is_superuser:
statment = select(func.count()).select_from(Item)
count = session.exec(statment).one()
statement = select(Item).offset(skip).limit(limit)
items = session.exec(statement).all()
else:
statment = (
select(func.count())
.select_from(Item)
.where(Item.owner_id == current_user.id)
)
count = session.exec(statment).one()
statement = (
select(Item)
.where(Item.owner_id == current_user.id)
.offset(skip)
.limit(limit)
)
items = session.exec(statement).all()
return ItemsOut(data=items, count=count)
@router.get("/{id}", response_model=ItemOut)
def read_item(session: SessionDep, current_user: CurrentUser, id: int) -> Any:
"""
Get item by ID.
"""
item = session.get(Item, id)
if not item:
raise HTTPException(status_code=404, detail="Item not found")
if not current_user.is_superuser and (item.owner_id != current_user.id):
raise HTTPException(status_code=400, detail="Not enough permissions")
return item
@router.post("/", response_model=ItemOut)
def create_item(
*, session: SessionDep, current_user: CurrentUser, item_in: ItemCreate
) -> Any:
"""
Create new item.
"""
item = Item.model_validate(item_in, update={"owner_id": current_user.id})
session.add(item)
session.commit()
session.refresh(item)
return item
@router.put("/{id}", response_model=ItemOut)
def update_item(
*, session: SessionDep, current_user: CurrentUser, id: int, item_in: ItemUpdate
) -> Any:
"""
Update an item.
"""
item = session.get(Item, id)
if not item:
raise HTTPException(status_code=404, detail="Item not found")
if not current_user.is_superuser and (item.owner_id != current_user.id):
raise HTTPException(status_code=400, detail="Not enough permissions")
update_dict = item_in.model_dump(exclude_unset=True)
item.sqlmodel_update(update_dict)
session.add(item)
session.commit()
session.refresh(item)
return item
@router.delete("/{id}")
def delete_item(session: SessionDep, current_user: CurrentUser, id: int) -> Message:
"""
Delete an item.
"""
item = session.get(Item, id)
if not item:
raise HTTPException(status_code=404, detail="Item not found")
if not current_user.is_superuser and (item.owner_id != current_user.id):
raise HTTPException(status_code=400, detail="Not enough permissions")
session.delete(item)
session.commit()
return Message(message="Item deleted successfully")
+124
View File
@@ -0,0 +1,124 @@
from datetime import timedelta
from typing import Annotated, Any
from fastapi import APIRouter, Depends, HTTPException
from fastapi.responses import HTMLResponse
from fastapi.security import OAuth2PasswordRequestForm
from app import crud
from app.api.deps import CurrentUser, SessionDep, get_current_active_superuser
from app.core import security
from app.core.config import settings
from app.core.security import get_password_hash
from app.models import Message, NewPassword, Token, UserOut
from app.utils import (
generate_password_reset_token,
generate_reset_password_email,
send_email,
verify_password_reset_token,
)
router = APIRouter()
@router.post("/login/access-token")
def login_access_token(
session: SessionDep, form_data: Annotated[OAuth2PasswordRequestForm, Depends()]
) -> Token:
"""
OAuth2 compatible token login, get an access token for future requests
"""
user = crud.authenticate(
session=session, email=form_data.username, password=form_data.password
)
if not user:
raise HTTPException(status_code=400, detail="Incorrect email or password")
elif not user.is_active:
raise HTTPException(status_code=400, detail="Inactive user")
access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
return Token(
access_token=security.create_access_token(
user.id, expires_delta=access_token_expires
)
)
@router.post("/login/test-token", response_model=UserOut)
def test_token(current_user: CurrentUser) -> Any:
"""
Test access token
"""
return current_user
@router.post("/password-recovery/{email}")
def recover_password(email: str, session: SessionDep) -> Message:
"""
Password Recovery
"""
user = crud.get_user_by_email(session=session, email=email)
if not user:
raise HTTPException(
status_code=404,
detail="The user with this email does not exist in the system.",
)
password_reset_token = generate_password_reset_token(email=email)
email_data = generate_reset_password_email(
email_to=user.email, email=email, token=password_reset_token
)
send_email(
email_to=user.email,
subject=email_data.subject,
html_content=email_data.html_content,
)
return Message(message="Password recovery email sent")
@router.post("/reset-password/")
def reset_password(session: SessionDep, body: NewPassword) -> Message:
"""
Reset password
"""
email = verify_password_reset_token(token=body.token)
if not email:
raise HTTPException(status_code=400, detail="Invalid token")
user = crud.get_user_by_email(session=session, email=email)
if not user:
raise HTTPException(
status_code=404,
detail="The user with this email does not exist in the system.",
)
elif not user.is_active:
raise HTTPException(status_code=400, detail="Inactive user")
hashed_password = get_password_hash(password=body.new_password)
user.hashed_password = hashed_password
session.add(user)
session.commit()
return Message(message="Password updated successfully")
@router.post(
"/password-recovery-html-content/{email}",
dependencies=[Depends(get_current_active_superuser)],
response_class=HTMLResponse,
)
def recover_password_html_content(email: str, session: SessionDep) -> Any:
"""
HTML Content for Password Recovery
"""
user = crud.get_user_by_email(session=session, email=email)
if not user:
raise HTTPException(
status_code=404,
detail="The user with this username does not exist in the system.",
)
password_reset_token = generate_password_reset_token(email=email)
email_data = generate_reset_password_email(
email_to=user.email, email=email, token=password_reset_token
)
return HTMLResponse(
content=email_data.html_content, headers={"subject:": email_data.subject}
)
+219
View File
@@ -0,0 +1,219 @@
from typing import Any
from fastapi import APIRouter, Depends, HTTPException
from sqlmodel import col, delete, func, select
from app import crud
from app.api.deps import (
CurrentUser,
SessionDep,
get_current_active_superuser,
)
from app.core.config import settings
from app.core.security import get_password_hash, verify_password
from app.models import (
Item,
Message,
UpdatePassword,
User,
UserCreate,
UserCreateOpen,
UserOut,
UsersOut,
UserUpdate,
UserUpdateMe,
)
from app.utils import generate_new_account_email, send_email
router = APIRouter()
@router.get(
"/", dependencies=[Depends(get_current_active_superuser)], response_model=UsersOut
)
def read_users(session: SessionDep, skip: int = 0, limit: int = 100) -> Any:
"""
Retrieve users.
"""
statment = select(func.count()).select_from(User)
count = session.exec(statment).one()
statement = select(User).offset(skip).limit(limit)
users = session.exec(statement).all()
return UsersOut(data=users, count=count)
@router.post(
"/", dependencies=[Depends(get_current_active_superuser)], response_model=UserOut
)
def create_user(*, session: SessionDep, user_in: UserCreate) -> Any:
"""
Create new user.
"""
user = crud.get_user_by_email(session=session, email=user_in.email)
if user:
raise HTTPException(
status_code=400,
detail="The user with this email already exists in the system.",
)
user = crud.create_user(session=session, user_create=user_in)
if settings.emails_enabled and user_in.email:
email_data = generate_new_account_email(
email_to=user_in.email, username=user_in.email, password=user_in.password
)
send_email(
email_to=user_in.email,
subject=email_data.subject,
html_content=email_data.html_content,
)
return user
@router.patch("/me", response_model=UserOut)
def update_user_me(
*, session: SessionDep, user_in: UserUpdateMe, current_user: CurrentUser
) -> Any:
"""
Update own user.
"""
if user_in.email:
existing_user = crud.get_user_by_email(session=session, email=user_in.email)
if existing_user and existing_user.id != current_user.id:
raise HTTPException(
status_code=409, detail="User with this email already exists"
)
user_data = user_in.model_dump(exclude_unset=True)
current_user.sqlmodel_update(user_data)
session.add(current_user)
session.commit()
session.refresh(current_user)
return current_user
@router.patch("/me/password", response_model=Message)
def update_password_me(
*, session: SessionDep, body: UpdatePassword, current_user: CurrentUser
) -> Any:
"""
Update own password.
"""
if not verify_password(body.current_password, current_user.hashed_password):
raise HTTPException(status_code=400, detail="Incorrect password")
if body.current_password == body.new_password:
raise HTTPException(
status_code=400, detail="New password cannot be the same as the current one"
)
hashed_password = get_password_hash(body.new_password)
current_user.hashed_password = hashed_password
session.add(current_user)
session.commit()
return Message(message="Password updated successfully")
@router.get("/me", response_model=UserOut)
def read_user_me(session: SessionDep, current_user: CurrentUser) -> Any:
"""
Get current user.
"""
return current_user
@router.post("/open", response_model=UserOut)
def create_user_open(session: SessionDep, user_in: UserCreateOpen) -> Any:
"""
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)
if user:
raise HTTPException(
status_code=400,
detail="The user with this email already exists in the system",
)
user_create = UserCreate.from_orm(user_in)
user = crud.create_user(session=session, user_create=user_create)
return user
@router.get("/{user_id}", response_model=UserOut)
def read_user_by_id(
user_id: int, session: SessionDep, current_user: CurrentUser
) -> Any:
"""
Get a specific user by id.
"""
user = session.get(User, user_id)
if user == current_user:
return user
if not current_user.is_superuser:
raise HTTPException(
status_code=403,
detail="The user doesn't have enough privileges",
)
return user
@router.patch(
"/{user_id}",
dependencies=[Depends(get_current_active_superuser)],
response_model=UserOut,
)
def update_user(
*,
session: SessionDep,
user_id: int,
user_in: UserUpdate,
) -> Any:
"""
Update a user.
"""
db_user = session.get(User, user_id)
if not db_user:
raise HTTPException(
status_code=404,
detail="The user with this id does not exist in the system",
)
if user_in.email:
existing_user = crud.get_user_by_email(session=session, email=user_in.email)
if existing_user and existing_user.id != user_id:
raise HTTPException(
status_code=409, detail="User with this email already exists"
)
db_user = crud.update_user(session=session, db_user=db_user, user_in=user_in)
return db_user
@router.delete("/{user_id}")
def delete_user(
session: SessionDep, current_user: CurrentUser, user_id: int
) -> Message:
"""
Delete a user.
"""
user = session.get(User, user_id)
if not user:
raise HTTPException(status_code=404, detail="User not found")
elif user != current_user and not current_user.is_superuser:
raise HTTPException(
status_code=403, detail="The user doesn't have enough privileges"
)
elif user == current_user and current_user.is_superuser:
raise HTTPException(
status_code=403, detail="Super users are not allowed to delete themselves"
)
statement = delete(Item).where(col(Item.owner_id) == user_id)
session.exec(statement) # type: ignore
session.delete(user)
session.commit()
return Message(message="User deleted successfully")
+26
View File
@@ -0,0 +1,26 @@
from fastapi import APIRouter, Depends
from pydantic.networks import EmailStr
from app.api.deps import get_current_active_superuser
from app.models import Message
from app.utils import generate_test_email, send_email
router = APIRouter()
@router.post(
"/test-email/",
dependencies=[Depends(get_current_active_superuser)],
status_code=201,
)
def test_email(email_to: EmailStr) -> Message:
"""
Test emails.
"""
email_data = generate_test_email(email_to=email_to)
send_email(
email_to=email_to,
subject=email_data.subject,
html_content=email_data.html_content,
)
return Message(message="Test email sent")
@@ -1,9 +1,10 @@
import logging 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 tenacity import after_log, before_log, retry, stop_after_attempt, wait_fixed
from app.db.session import db_session from app.core.db import engine
from app.tests.api.api_v1.test_login import test_get_access_token
logging.basicConfig(level=logging.INFO) logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -18,20 +19,19 @@ wait_seconds = 1
before=before_log(logger, logging.INFO), before=before_log(logger, logging.INFO),
after=after_log(logger, logging.WARN), after=after_log(logger, logging.WARN),
) )
def init(): def init(db_engine: Engine) -> None:
try: try:
# Try to create session to check if DB is awake with Session(db_engine) as session:
db_session.execute("SELECT 1") # Try to create session to check if DB is awake
# Wait for API to be awake, run one simple tests to authenticate session.exec(select(1))
test_get_access_token()
except Exception as e: except Exception as e:
logger.error(e) logger.error(e)
raise e raise e
def main(): def main() -> None:
logger.info("Initializing service") logger.info("Initializing service")
init() init(engine)
logger.info("Service finished initializing") logger.info("Service finished initializing")
@@ -1,8 +1,10 @@
import logging 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 tenacity import after_log, before_log, retry, stop_after_attempt, wait_fixed
from app.db.session import db_session from app.core.db import engine
logging.basicConfig(level=logging.INFO) logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -17,18 +19,19 @@ wait_seconds = 1
before=before_log(logger, logging.INFO), before=before_log(logger, logging.INFO),
after=after_log(logger, logging.WARN), after=after_log(logger, logging.WARN),
) )
def init(): def init(db_engine: Engine) -> None:
try: try:
# Try to create session to check if DB is awake # Try to create session to check if DB is awake
db_session.execute("SELECT 1") with Session(db_engine) as session:
session.exec(select(1))
except Exception as e: except Exception as e:
logger.error(e) logger.error(e)
raise e raise e
def main(): def main() -> None:
logger.info("Initializing service") logger.info("Initializing service")
init() init(engine)
logger.info("Service finished initializing") logger.info("Service finished initializing")
+121
View File
@@ -0,0 +1,121 @@
import secrets
import warnings
from typing import Annotated, Any, Literal
from pydantic import (
AnyUrl,
BeforeValidator,
HttpUrl,
PostgresDsn,
computed_field,
model_validator,
)
from pydantic_core import MultiHostUrl
from pydantic_settings import BaseSettings, SettingsConfigDict
from typing_extensions import Self
def parse_cors(v: Any) -> list[str] | str:
if isinstance(v, str) and not v.startswith("["):
return [i.strip() for i in v.split(",")]
elif isinstance(v, list | str):
return v
raise ValueError(v)
class Settings(BaseSettings):
model_config = SettingsConfigDict(
env_file=".env", env_ignore_empty=True, extra="ignore"
)
API_V1_STR: str = "/api/v1"
SECRET_KEY: str = secrets.token_urlsafe(32)
# 60 minutes * 24 hours * 8 days = 8 days
ACCESS_TOKEN_EXPIRE_MINUTES: int = 60 * 24 * 8
DOMAIN: str = "localhost"
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[
list[AnyUrl] | str, BeforeValidator(parse_cors)
] = []
PROJECT_NAME: str
SENTRY_DSN: HttpUrl | None = None
POSTGRES_SERVER: str
POSTGRES_PORT: int = 5432
POSTGRES_USER: str
POSTGRES_PASSWORD: str
POSTGRES_DB: str = ""
@computed_field # type: ignore[misc]
@property
def SQLALCHEMY_DATABASE_URI(self) -> PostgresDsn:
return MultiHostUrl.build(
scheme="postgresql+psycopg",
username=self.POSTGRES_USER,
password=self.POSTGRES_PASSWORD,
host=self.POSTGRES_SERVER,
port=self.POSTGRES_PORT,
path=self.POSTGRES_DB,
)
SMTP_TLS: bool = True
SMTP_SSL: bool = False
SMTP_PORT: int = 587
SMTP_HOST: str | None = None
SMTP_USER: str | None = None
SMTP_PASSWORD: str | None = None
# TODO: update type to EmailStr when sqlmodel supports it
EMAILS_FROM_EMAIL: str | None = None
EMAILS_FROM_NAME: str | None = None
@model_validator(mode="after")
def _set_default_emails_from(self) -> Self:
if not self.EMAILS_FROM_NAME:
self.EMAILS_FROM_NAME = self.PROJECT_NAME
return self
EMAIL_RESET_TOKEN_EXPIRE_HOURS: int = 48
@computed_field # type: ignore[misc]
@property
def emails_enabled(self) -> bool:
return bool(self.SMTP_HOST and self.EMAILS_FROM_EMAIL)
# TODO: update type to EmailStr when sqlmodel supports it
EMAIL_TEST_USER: str = "test@example.com"
# TODO: update type to EmailStr when sqlmodel supports it
FIRST_SUPERUSER: str
FIRST_SUPERUSER_PASSWORD: str
USERS_OPEN_REGISTRATION: bool = False
def _check_default_secret(self, var_name: str, value: str | None) -> None:
if value == "changethis":
message = (
f'The value of {var_name} is "changethis", '
"for security, please change it, at least for deployments."
)
if self.ENVIRONMENT == "local":
warnings.warn(message, stacklevel=1)
else:
raise ValueError(message)
@model_validator(mode="after")
def _enforce_non_default_secrets(self) -> Self:
self._check_default_secret("SECRET_KEY", self.SECRET_KEY)
self._check_default_secret("POSTGRES_PASSWORD", self.POSTGRES_PASSWORD)
self._check_default_secret(
"FIRST_SUPERUSER_PASSWORD", self.FIRST_SUPERUSER_PASSWORD
)
return self
settings = Settings() # type: ignore
+34
View File
@@ -0,0 +1,34 @@
from sqlmodel import Session, create_engine, select
from app import crud
from app.core.config import settings
from app.models import User, UserCreate
engine = create_engine(str(settings.SQLALCHEMY_DATABASE_URI))
# make sure all SQLModel models are imported (app.models) before initializing DB
# otherwise, SQLModel might fail to initialize relationships properly
# for more details: https://github.com/tiangolo/full-stack-fastapi-template/issues/28
def init_db(session: Session) -> None:
# Tables should be created with Alembic migrations
# But if you don't want to use migrations, create
# the tables un-commenting the next lines
# from sqlmodel import SQLModel
# from app.core.engine import engine
# This works because the models are already imported and registered from app.models
# SQLModel.metadata.create_all(engine)
user = session.exec(
select(User).where(User.email == settings.FIRST_SUPERUSER)
).first()
if not user:
user_in = UserCreate(
email=settings.FIRST_SUPERUSER,
password=settings.FIRST_SUPERUSER_PASSWORD,
is_superuser=True,
)
user = crud.create_user(session=session, user_create=user_in)
+27
View File
@@ -0,0 +1,27 @@
from datetime import datetime, timedelta
from typing import Any
from jose import jwt
from passlib.context import CryptContext
from app.core.config import settings
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
ALGORITHM = "HS256"
def create_access_token(subject: str | Any, expires_delta: timedelta) -> str:
expire = datetime.utcnow() + expires_delta
to_encode = {"exp": expire, "sub": str(subject)}
encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt
def verify_password(plain_password: str, hashed_password: str) -> bool:
return pwd_context.verify(plain_password, hashed_password)
def get_password_hash(password: str) -> str:
return pwd_context.hash(password)
+53
View File
@@ -0,0 +1,53 @@
from typing import Any
from sqlmodel import Session, select
from app.core.security import get_password_hash, verify_password
from app.models import Item, ItemCreate, User, UserCreate, UserUpdate
def create_user(*, session: Session, user_create: UserCreate) -> User:
db_obj = User.model_validate(
user_create, update={"hashed_password": get_password_hash(user_create.password)}
)
session.add(db_obj)
session.commit()
session.refresh(db_obj)
return db_obj
def update_user(*, session: Session, db_user: User, user_in: UserUpdate) -> Any:
user_data = user_in.model_dump(exclude_unset=True)
extra_data = {}
if "password" in user_data:
password = user_data["password"]
hashed_password = get_password_hash(password)
extra_data["hashed_password"] = hashed_password
db_user.sqlmodel_update(user_data, update=extra_data)
session.add(db_user)
session.commit()
session.refresh(db_user)
return db_user
def get_user_by_email(*, session: Session, email: str) -> User | None:
statement = select(User).where(User.email == email)
session_user = session.exec(statement).first()
return session_user
def authenticate(*, session: Session, email: str, password: str) -> User | None:
db_user = get_user_by_email(session=session, email=email)
if not db_user:
return None
if not verify_password(password, db_user.hashed_password):
return None
return db_user
def create_item(*, session: Session, item_in: ItemCreate, owner_id: int) -> Item:
db_item = Item.model_validate(item_in, update={"owner_id": owner_id})
session.add(db_item)
session.commit()
session.refresh(db_item)
return db_item
@@ -0,0 +1,25 @@
<!doctype html><html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office"><head><title></title><!--[if !mso]><!-- --><meta http-equiv="X-UA-Compatible" content="IE=edge"><!--<![endif]--><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><style type="text/css">#outlook a { padding:0; }
.ReadMsgBody { width:100%; }
.ExternalClass { width:100%; }
.ExternalClass * { line-height:100%; }
body { margin:0;padding:0;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%; }
table, td { border-collapse:collapse;mso-table-lspace:0pt;mso-table-rspace:0pt; }
img { border:0;height:auto;line-height:100%; outline:none;text-decoration:none;-ms-interpolation-mode:bicubic; }
p { display:block;margin:13px 0; }</style><!--[if !mso]><!--><style type="text/css">@media only screen and (max-width:480px) {
@-ms-viewport { width:320px; }
@viewport { width:320px; }
}</style><!--<![endif]--><!--[if mso]>
<xml>
<o:OfficeDocumentSettings>
<o:AllowPNG/>
<o:PixelsPerInch>96</o:PixelsPerInch>
</o:OfficeDocumentSettings>
</xml>
<![endif]--><!--[if lte mso 11]>
<style type="text/css">
.outlook-group-fix { width:100% !important; }
</style>
<![endif]--><!--[if !mso]><!--><link href="https://fonts.googleapis.com/css?family=Ubuntu:300,400,500,700" rel="stylesheet" type="text/css"><style type="text/css">@import url(https://fonts.googleapis.com/css?family=Ubuntu:300,400,500,700);</style><!--<![endif]--><style type="text/css">@media only screen and (min-width:480px) {
.mj-column-per-100 { width:100% !important; max-width: 100%; }
}</style><style type="text/css"></style></head><body style="background-color:#fafbfc;"><div style="background-color:#fafbfc;"><!--[if mso | IE]><table align="center" border="0" cellpadding="0" cellspacing="0" class="" style="width:600px;" width="600" ><tr><td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;"><![endif]--><div style="background:#ffffff;background-color:#ffffff;Margin:0px auto;max-width:600px;"><table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="background:#ffffff;background-color:#ffffff;width:100%;"><tbody><tr><td style="direction:ltr;font-size:0px;padding:40px 20px;text-align:center;vertical-align:top;"><!--[if mso | IE]><table role="presentation" border="0" cellpadding="0" cellspacing="0"><tr><td class="" style="vertical-align:middle;width:560px;" ><![endif]--><div class="mj-column-per-100 outlook-group-fix" style="font-size:13px;text-align:left;direction:ltr;display:inline-block;vertical-align:middle;width:100%;"><table border="0" cellpadding="0" cellspacing="0" role="presentation" style="vertical-align:middle;" width="100%"><tr><td align="center" style="font-size:0px;padding:35px;word-break:break-word;"><div style="font-family:Ubuntu, Helvetica, Arial, sans-serif;font-size:20px;line-height:1;text-align:center;color:#333333;">{{ project_name }} - New Account</div></td></tr><tr><td align="center" style="font-size:0px;padding:10px 25px;padding-right:25px;padding-left:25px;word-break:break-word;"><div style="font-family:Arial, Helvetica, sans-serif;font-size:16px;line-height:1;text-align:center;color:#555555;"><span>Welcome to your new account!</span></div></td></tr><tr><td align="center" style="font-size:0px;padding:10px 25px;padding-right:25px;padding-left:25px;word-break:break-word;"><div style="font-family:Arial, Helvetica, sans-serif;font-size:16px;line-height:1;text-align:center;color:#555555;">Here are your account details:</div></td></tr><tr><td align="center" style="font-size:0px;padding:10px 25px;padding-right:25px;padding-left:25px;word-break:break-word;"><div style="font-family:Arial, Helvetica, sans-serif;font-size:16px;line-height:1;text-align:center;color:#555555;">Username: {{ username }}</div></td></tr><tr><td align="center" style="font-size:0px;padding:10px 25px;padding-right:25px;padding-left:25px;word-break:break-word;"><div style="font-family:Arial, Helvetica, sans-serif;font-size:16px;line-height:1;text-align:center;color:#555555;">Password: {{ password }}</div></td></tr><tr><td align="center" vertical-align="middle" style="font-size:0px;padding:15px 30px;word-break:break-word;"><table border="0" cellpadding="0" cellspacing="0" role="presentation" style="border-collapse:separate;line-height:100%;"><tr><td align="center" bgcolor="#009688" role="presentation" style="border:none;border-radius:8px;cursor:auto;padding:10px 25px;background:#009688;" valign="middle"><a href="{{ link }}" style="background:#009688;color:#ffffff;font-family:Ubuntu, Helvetica, Arial, sans-serif;font-size:18px;font-weight:normal;line-height:120%;Margin:0;text-decoration:none;text-transform:none;" target="_blank">Go to Dashboard</a></td></tr></table></td></tr><tr><td style="font-size:0px;padding:10px 25px;word-break:break-word;"><p style="border-top:solid 2px #cccccc;font-size:1;margin:0px auto;width:100%;"></p><!--[if mso | IE]><table align="center" border="0" cellpadding="0" cellspacing="0" style="border-top:solid 2px #cccccc;font-size:1;margin:0px auto;width:510px;" role="presentation" width="510px" ><tr><td style="height:0;line-height:0;"> &nbsp;
</td></tr></table><![endif]--></td></tr></table></div><!--[if mso | IE]></td></tr></table><![endif]--></td></tr></tbody></table></div><!--[if mso | IE]></td></tr></table><![endif]--></div></body></html>
@@ -0,0 +1,25 @@
<!doctype html><html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office"><head><title></title><!--[if !mso]><!-- --><meta http-equiv="X-UA-Compatible" content="IE=edge"><!--<![endif]--><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><style type="text/css">#outlook a { padding:0; }
.ReadMsgBody { width:100%; }
.ExternalClass { width:100%; }
.ExternalClass * { line-height:100%; }
body { margin:0;padding:0;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%; }
table, td { border-collapse:collapse;mso-table-lspace:0pt;mso-table-rspace:0pt; }
img { border:0;height:auto;line-height:100%; outline:none;text-decoration:none;-ms-interpolation-mode:bicubic; }
p { display:block;margin:13px 0; }</style><!--[if !mso]><!--><style type="text/css">@media only screen and (max-width:480px) {
@-ms-viewport { width:320px; }
@viewport { width:320px; }
}</style><!--<![endif]--><!--[if mso]>
<xml>
<o:OfficeDocumentSettings>
<o:AllowPNG/>
<o:PixelsPerInch>96</o:PixelsPerInch>
</o:OfficeDocumentSettings>
</xml>
<![endif]--><!--[if lte mso 11]>
<style type="text/css">
.outlook-group-fix { width:100% !important; }
</style>
<![endif]--><!--[if !mso]><!--><link href="https://fonts.googleapis.com/css?family=Ubuntu:300,400,500,700" rel="stylesheet" type="text/css"><style type="text/css">@import url(https://fonts.googleapis.com/css?family=Ubuntu:300,400,500,700);</style><!--<![endif]--><style type="text/css">@media only screen and (min-width:480px) {
.mj-column-per-100 { width:100% !important; max-width: 100%; }
}</style><style type="text/css"></style></head><body style="background-color:#fafbfc;"><div style="background-color:#fafbfc;"><!--[if mso | IE]><table align="center" border="0" cellpadding="0" cellspacing="0" class="" style="width:600px;" width="600" ><tr><td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;"><![endif]--><div style="background:#ffffff;background-color:#ffffff;Margin:0px auto;max-width:600px;"><table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="background:#ffffff;background-color:#ffffff;width:100%;"><tbody><tr><td style="direction:ltr;font-size:0px;padding:40px 20px;text-align:center;vertical-align:top;"><!--[if mso | IE]><table role="presentation" border="0" cellpadding="0" cellspacing="0"><tr><td class="" style="vertical-align:middle;width:560px;" ><![endif]--><div class="mj-column-per-100 outlook-group-fix" style="font-size:13px;text-align:left;direction:ltr;display:inline-block;vertical-align:middle;width:100%;"><table border="0" cellpadding="0" cellspacing="0" role="presentation" style="vertical-align:middle;" width="100%"><tr><td align="center" style="font-size:0px;padding:35px;word-break:break-word;"><div style="font-family:Arial, Helvetica, sans-serif;font-size:20px;line-height:1;text-align:center;color:#333333;">{{ project_name }} - Password Recovery</div></td></tr><tr><td align="center" style="font-size:0px;padding:10px 25px;padding-right:25px;padding-left:25px;word-break:break-word;"><div style="font-family:Arial, Helvetica, sans-serif;font-size:16px;line-height:1;text-align:center;color:#555555;"><span>Hello {{ username }}</span></div></td></tr><tr><td align="center" style="font-size:0px;padding:10px 25px;padding-right:25px;padding-left:25px;word-break:break-word;"><div style="font-family:Arial, Helvetica, sans-serif;font-size:16px;line-height:1;text-align:center;color:#555555;">We've received a request to reset your password. You can do it by clicking the button below:</div></td></tr><tr><td align="center" vertical-align="middle" style="font-size:0px;padding:15px 30px;word-break:break-word;"><table border="0" cellpadding="0" cellspacing="0" role="presentation" style="border-collapse:separate;line-height:100%;"><tr><td align="center" bgcolor="#009688" role="presentation" style="border:none;border-radius:8px;cursor:auto;padding:10px 25px;background:#009688;" valign="middle"><a href="{{ link }}" style="background:#009688;color:#ffffff;font-family:Ubuntu, Helvetica, Arial, sans-serif;font-size:18px;font-weight:normal;line-height:120%;Margin:0;text-decoration:none;text-transform:none;" target="_blank">Reset password</a></td></tr></table></td></tr><tr><td align="center" style="font-size:0px;padding:10px 25px;padding-right:25px;padding-left:25px;word-break:break-word;"><div style="font-family:Arial, Helvetica, sans-serif;font-size:16px;line-height:1;text-align:center;color:#555555;">Or copy and paste the following link into your browser:</div></td></tr><tr><td align="center" style="font-size:0px;padding:10px 25px;padding-right:25px;padding-left:25px;word-break:break-word;"><div style="font-family:Arial, Helvetica, sans-serif;font-size:16px;line-height:1;text-align:center;color:#555555;"><a href="{{ link }}">{{ link }}</a></div></td></tr><tr><td align="center" style="font-size:0px;padding:10px 25px;padding-right:25px;padding-left:25px;word-break:break-word;"><div style="font-family:Arial, Helvetica, sans-serif;font-size:16px;line-height:1;text-align:center;color:#555555;">This password will expire in {{ valid_hours }} hours.</div></td></tr><tr><td style="font-size:0px;padding:10px 25px;word-break:break-word;"><p style="border-top:solid 2px #cccccc;font-size:1;margin:0px auto;width:100%;"></p><!--[if mso | IE]><table align="center" border="0" cellpadding="0" cellspacing="0" style="border-top:solid 2px #cccccc;font-size:1;margin:0px auto;width:510px;" role="presentation" width="510px" ><tr><td style="height:0;line-height:0;"> &nbsp;
</td></tr></table><![endif]--></td></tr><tr><td align="center" style="font-size:0px;padding:10px 25px;padding-right:25px;padding-left:25px;word-break:break-word;"><div style="font-family:Arial, Helvetica, sans-serif;font-size:14px;line-height:1;text-align:center;color:#555555;">If you didn't request a password recovery you can disregard this email.</div></td></tr></table></div><!--[if mso | IE]></td></tr></table><![endif]--></td></tr></tbody></table></div><!--[if mso | IE]></td></tr></table><![endif]--></div></body></html>
@@ -0,0 +1,25 @@
<!doctype html><html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office"><head><title></title><!--[if !mso]><!-- --><meta http-equiv="X-UA-Compatible" content="IE=edge"><!--<![endif]--><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><style type="text/css">#outlook a { padding:0; }
.ReadMsgBody { width:100%; }
.ExternalClass { width:100%; }
.ExternalClass * { line-height:100%; }
body { margin:0;padding:0;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%; }
table, td { border-collapse:collapse;mso-table-lspace:0pt;mso-table-rspace:0pt; }
img { border:0;height:auto;line-height:100%; outline:none;text-decoration:none;-ms-interpolation-mode:bicubic; }
p { display:block;margin:13px 0; }</style><!--[if !mso]><!--><style type="text/css">@media only screen and (max-width:480px) {
@-ms-viewport { width:320px; }
@viewport { width:320px; }
}</style><!--<![endif]--><!--[if mso]>
<xml>
<o:OfficeDocumentSettings>
<o:AllowPNG/>
<o:PixelsPerInch>96</o:PixelsPerInch>
</o:OfficeDocumentSettings>
</xml>
<![endif]--><!--[if lte mso 11]>
<style type="text/css">
.outlook-group-fix { width:100% !important; }
</style>
<![endif]--><style type="text/css">@media only screen and (min-width:480px) {
.mj-column-per-100 { width:100% !important; max-width: 100%; }
}</style><style type="text/css"></style></head><body style="background-color:#fafbfc;"><div style="background-color:#fafbfc;"><!--[if mso | IE]><table align="center" border="0" cellpadding="0" cellspacing="0" class="" style="width:600px;" width="600" ><tr><td style="line-height:0px;font-size:0px;mso-line-height-rule:exactly;"><![endif]--><div style="background:#ffffff;background-color:#ffffff;Margin:0px auto;max-width:600px;"><table align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" style="background:#ffffff;background-color:#ffffff;width:100%;"><tbody><tr><td style="direction:ltr;font-size:0px;padding:40px 20px;text-align:center;vertical-align:top;"><!--[if mso | IE]><table role="presentation" border="0" cellpadding="0" cellspacing="0"><tr><td class="" style="vertical-align:middle;width:560px;" ><![endif]--><div class="mj-column-per-100 outlook-group-fix" style="font-size:13px;text-align:left;direction:ltr;display:inline-block;vertical-align:middle;width:100%;"><table border="0" cellpadding="0" cellspacing="0" role="presentation" style="vertical-align:middle;" width="100%"><tr><td align="center" style="font-size:0px;padding:35px;word-break:break-word;"><div style="font-family:Arial, Helvetica, sans-serif;font-size:20px;line-height:1;text-align:center;color:#333333;">{{ project_name }}</div></td></tr><tr><td align="center" style="font-size:0px;padding:10px 25px;padding-right:25px;padding-left:25px;word-break:break-word;"><div style="font-family:, sans-serif;font-size:16px;line-height:1;text-align:center;color:#555555;"><span>Test email for: {{ email }}</span></div></td></tr><tr><td style="font-size:0px;padding:10px 25px;word-break:break-word;"><p style="border-top:solid 2px #cccccc;font-size:1;margin:0px auto;width:100%;"></p><!--[if mso | IE]><table align="center" border="0" cellpadding="0" cellspacing="0" style="border-top:solid 2px #cccccc;font-size:1;margin:0px auto;width:510px;" role="presentation" width="510px" ><tr><td style="height:0;line-height:0;"> &nbsp;
</td></tr></table><![endif]--></td></tr></table></div><!--[if mso | IE]></td></tr></table><![endif]--></td></tr></tbody></table></div><!--[if mso | IE]></td></tr></table><![endif]--></div></body></html>
@@ -0,0 +1,15 @@
<mjml>
<mj-body background-color="#fafbfc">
<mj-section background-color="#fff" padding="40px 20px">
<mj-column vertical-align="middle" width="100%">
<mj-text align="center" padding="35px" font-size="20px" color="#333">{{ project_name }} - New Account</mj-text>
<mj-text align="center" font-size="16px" padding-left="25px" padding-right="25px" font-family="Arial, Helvetica, sans-serif" color="#555"><span>Welcome to your new account!</span></mj-text>
<mj-text align="center" font-size="16px" padding-left="25px" padding-right="25px" font-family="Arial, Helvetica, sans-serif" color="#555">Here are your account details:</mj-text>
<mj-text align="center" font-size="16px" padding-left="25px" padding-right="25px" font-family="Arial, Helvetica, sans-serif" color="#555">Username: {{ username }}</mj-text>
<mj-text align="center" font-size="16px" padding-left="25px" padding-right="25px" font-family="Arial, Helvetica, sans-serif" color="#555">Password: {{ password }}</mj-text>
<mj-button align="center" font-size="18px" background-color="#009688" border-radius="8px" color="#fff" href="{{ link }}" padding="15px 30px">Go to Dashboard</mj-button>
<mj-divider border-color="#ccc" border-width="2px"></mj-divider>
</mj-column>
</mj-section>
</mj-body>
</mjml>
@@ -0,0 +1,17 @@
<mjml>
<mj-body background-color="#fafbfc">
<mj-section background-color="#fff" padding="40px 20px">
<mj-column vertical-align="middle" width="100%">
<mj-text align="center" padding="35px" font-size="20px" font-family="Arial, Helvetica, sans-serif" color="#333">{{ project_name }} - Password Recovery</mj-text>
<mj-text align="center" font-size="16px" padding-left="25px" padding-right="25px" font-family="Arial, Helvetica, sans-serif" color="#555"><span>Hello {{ username }}</span></mj-text>
<mj-text align="center" font-size="16px" padding-left="25px" padding-right="25px" font-family="Arial, Helvetica, sans-serif" color="#555">We've received a request to reset your password. You can do it by clicking the button below:</mj-text>
<mj-button align="center" font-size="18px" background-color="#009688" border-radius="8px" color="#fff" href="{{ link }}" padding="15px 30px">Reset password</mj-button>
<mj-text align="center" font-size="16px" padding-left="25px" padding-right="25px" font-family="Arial, Helvetica, sans-serif" color="#555">Or copy and paste the following link into your browser:</mj-text>
<mj-text align="center" font-size="16px" padding-left="25px" padding-right="25px" font-family="Arial, Helvetica, sans-serif" color="#555"><a href="{{ link }}">{{ link }}</a></mj-text>
<mj-text align="center" font-size="16px" padding-left="25px" padding-right="25px" font-family="Arial, Helvetica, sans-serif" color="#555">This password will expire in {{ valid_hours }} hours.</mj-text>
<mj-divider border-color="#ccc" border-width="2px"></mj-divider>
<mj-text align="center" font-size="14px" padding-left="25px" padding-right="25px" font-family="Arial, Helvetica, sans-serif" color="#555">If you didn't request a password recovery you can disregard this email.</mj-text>
</mj-column>
</mj-section>
</mj-body>
</mjml>
@@ -0,0 +1,11 @@
<mjml>
<mj-body background-color="#fafbfc">
<mj-section background-color="#fff" padding="40px 20px">
<mj-column vertical-align="middle" width="100%">
<mj-text align="center" padding="35px" font-size="20px" font-family="Arial, Helvetica, sans-serif" color="#333">{{ project_name }}</mj-text>
<mj-text align="center" font-size="16px" padding-left="25px" padding-right="25px" font-family=", sans-serif" color="#555"><span>Test email for: {{ email }}</span></mj-text>
<mj-divider border-color="#ccc" border-width="2px"></mj-divider>
</mj-column>
</mj-section>
</mj-body>
</mjml>
@@ -1,17 +1,19 @@
import logging import logging
from app.db.init_db import init_db from sqlmodel import Session
from app.db.session import db_session
from app.core.db import engine, init_db
logging.basicConfig(level=logging.INFO) logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
def init(): def init() -> None:
init_db(db_session) with Session(engine) as session:
init_db(session)
def main(): def main() -> None:
logger.info("Creating initial data") logger.info("Creating initial data")
init() init()
logger.info("Initial data created") logger.info("Initial data created")
+31
View File
@@ -0,0 +1,31 @@
from fastapi import FastAPI
from fastapi.routing import APIRoute
from starlette.middleware.cors import CORSMiddleware
from app.api.main import api_router
from app.core.config import settings
def custom_generate_unique_id(route: APIRoute) -> str:
return f"{route.tags[0]}-{route.name}"
app = FastAPI(
title=settings.PROJECT_NAME,
openapi_url=f"{settings.API_V1_STR}/openapi.json",
generate_unique_id_function=custom_generate_unique_id,
)
# Set all CORS enabled origins
if settings.BACKEND_CORS_ORIGINS:
app.add_middleware(
CORSMiddleware,
allow_origins=[
str(origin).strip("/") for origin in settings.BACKEND_CORS_ORIGINS
],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.include_router(api_router, prefix=settings.API_V1_STR)
+113
View File
@@ -0,0 +1,113 @@
from sqlmodel import Field, Relationship, SQLModel
# Shared properties
# TODO replace email str with EmailStr when sqlmodel supports it
class UserBase(SQLModel):
email: str = Field(unique=True, index=True)
is_active: bool = True
is_superuser: bool = False
full_name: str | None = None
# Properties to receive via API on creation
class UserCreate(UserBase):
password: str
# TODO replace email str with EmailStr when sqlmodel supports it
class UserCreateOpen(SQLModel):
email: str
password: str
full_name: str | None = None
# Properties to receive via API on update, all are optional
# TODO replace email str with EmailStr when sqlmodel supports it
class UserUpdate(UserBase):
email: str | None = None # type: ignore
password: str | None = None
# TODO replace email str with EmailStr when sqlmodel supports it
class UserUpdateMe(SQLModel):
full_name: str | None = None
email: str | None = None
class UpdatePassword(SQLModel):
current_password: str
new_password: str
# Database model, database table inferred from class name
class User(UserBase, table=True):
id: int | None = Field(default=None, primary_key=True)
hashed_password: str
items: list["Item"] = Relationship(back_populates="owner")
# Properties to return via API, id is always required
class UserOut(UserBase):
id: int
class UsersOut(SQLModel):
data: list[UserOut]
count: int
# Shared properties
class ItemBase(SQLModel):
title: str
description: str | None = None
# Properties to receive on item creation
class ItemCreate(ItemBase):
title: str
# Properties to receive on item update
class ItemUpdate(ItemBase):
title: str | None = None # type: ignore
# Database model, database table inferred from class name
class Item(ItemBase, table=True):
id: int | None = Field(default=None, primary_key=True)
title: str
owner_id: int | None = Field(default=None, foreign_key="user.id", nullable=False)
owner: User | None = Relationship(back_populates="items")
# Properties to return via API, id is always required
class ItemOut(ItemBase):
id: int
owner_id: int
class ItemsOut(SQLModel):
data: list[ItemOut]
count: int
# Generic message
class Message(SQLModel):
message: str
# JSON payload containing access token
class Token(SQLModel):
access_token: str
token_type: str = "bearer"
# Contents of JWT token
class TokenPayload(SQLModel):
sub: int | None = None
class NewPassword(SQLModel):
token: str
new_password: str
+162
View File
@@ -0,0 +1,162 @@
from fastapi.testclient import TestClient
from sqlmodel import Session
from app.core.config import settings
from app.tests.utils.item import create_random_item
def test_create_item(
client: TestClient, superuser_token_headers: dict[str, str], db: Session
) -> None:
data = {"title": "Foo", "description": "Fighters"}
response = client.post(
f"{settings.API_V1_STR}/items/",
headers=superuser_token_headers,
json=data,
)
assert response.status_code == 200
content = response.json()
assert content["title"] == data["title"]
assert content["description"] == data["description"]
assert "id" in content
assert "owner_id" in content
def test_read_item(
client: TestClient, superuser_token_headers: dict[str, str], db: Session
) -> None:
item = create_random_item(db)
response = client.get(
f"{settings.API_V1_STR}/items/{item.id}",
headers=superuser_token_headers,
)
assert response.status_code == 200
content = response.json()
assert content["title"] == item.title
assert content["description"] == item.description
assert content["id"] == item.id
assert content["owner_id"] == item.owner_id
def test_read_item_not_found(
client: TestClient, superuser_token_headers: dict[str, str], db: Session
) -> None:
response = client.get(
f"{settings.API_V1_STR}/items/999",
headers=superuser_token_headers,
)
assert response.status_code == 404
content = response.json()
assert content["detail"] == "Item not found"
def test_read_item_not_enough_permissions(
client: TestClient, normal_user_token_headers: dict[str, str], db: Session
) -> None:
item = create_random_item(db)
response = client.get(
f"{settings.API_V1_STR}/items/{item.id}",
headers=normal_user_token_headers,
)
assert response.status_code == 400
content = response.json()
assert content["detail"] == "Not enough permissions"
def test_read_items(
client: TestClient, superuser_token_headers: dict[str, str], db: Session
) -> None:
create_random_item(db)
create_random_item(db)
response = client.get(
f"{settings.API_V1_STR}/items/",
headers=superuser_token_headers,
)
assert response.status_code == 200
content = response.json()
assert len(content["data"]) >= 2
def test_update_item(
client: TestClient, superuser_token_headers: dict[str, str], db: Session
) -> None:
item = create_random_item(db)
data = {"title": "Updated title", "description": "Updated description"}
response = client.put(
f"{settings.API_V1_STR}/items/{item.id}",
headers=superuser_token_headers,
json=data,
)
assert response.status_code == 200
content = response.json()
assert content["title"] == data["title"]
assert content["description"] == data["description"]
assert content["id"] == item.id
assert content["owner_id"] == item.owner_id
def test_update_item_not_found(
client: TestClient, superuser_token_headers: dict[str, str], db: Session
) -> None:
data = {"title": "Updated title", "description": "Updated description"}
response = client.put(
f"{settings.API_V1_STR}/items/999",
headers=superuser_token_headers,
json=data,
)
assert response.status_code == 404
content = response.json()
assert content["detail"] == "Item not found"
def test_update_item_not_enough_permissions(
client: TestClient, normal_user_token_headers: dict[str, str], db: Session
) -> None:
item = create_random_item(db)
data = {"title": "Updated title", "description": "Updated description"}
response = client.put(
f"{settings.API_V1_STR}/items/{item.id}",
headers=normal_user_token_headers,
json=data,
)
assert response.status_code == 400
content = response.json()
assert content["detail"] == "Not enough permissions"
def test_delete_item(
client: TestClient, superuser_token_headers: dict[str, str], db: Session
) -> None:
item = create_random_item(db)
response = client.delete(
f"{settings.API_V1_STR}/items/{item.id}",
headers=superuser_token_headers,
)
assert response.status_code == 200
content = response.json()
assert content["message"] == "Item deleted successfully"
def test_delete_item_not_found(
client: TestClient, superuser_token_headers: dict[str, str], db: Session
) -> None:
response = client.delete(
f"{settings.API_V1_STR}/items/999",
headers=superuser_token_headers,
)
assert response.status_code == 404
content = response.json()
assert content["detail"] == "Item not found"
def test_delete_item_not_enough_permissions(
client: TestClient, normal_user_token_headers: dict[str, str], db: Session
) -> None:
item = create_random_item(db)
response = client.delete(
f"{settings.API_V1_STR}/items/{item.id}",
headers=normal_user_token_headers,
)
assert response.status_code == 400
content = response.json()
assert content["detail"] == "Not enough permissions"
@@ -0,0 +1,94 @@
from fastapi.testclient import TestClient
from pytest_mock import MockerFixture
from app.core.config import settings
from app.utils import generate_password_reset_token
def test_get_access_token(client: TestClient) -> None:
login_data = {
"username": settings.FIRST_SUPERUSER,
"password": settings.FIRST_SUPERUSER_PASSWORD,
}
r = client.post(f"{settings.API_V1_STR}/login/access-token", data=login_data)
tokens = r.json()
assert r.status_code == 200
assert "access_token" in tokens
assert tokens["access_token"]
def test_get_access_token_incorrect_password(client: TestClient) -> None:
login_data = {
"username": settings.FIRST_SUPERUSER,
"password": "incorrect",
}
r = client.post(f"{settings.API_V1_STR}/login/access-token", data=login_data)
assert r.status_code == 400
def test_use_access_token(
client: TestClient, superuser_token_headers: dict[str, str]
) -> None:
r = client.post(
f"{settings.API_V1_STR}/login/test-token",
headers=superuser_token_headers,
)
result = r.json()
assert r.status_code == 200
assert "email" in result
def test_recovery_password(
client: TestClient, normal_user_token_headers: dict[str, str], mocker: MockerFixture
) -> None:
mocker.patch("app.utils.send_email", return_value=None)
mocker.patch("app.core.config.settings.SMTP_HOST", "smtp.example.com")
mocker.patch("app.core.config.settings.SMTP_USER", "admin@example.com")
email = "test@example.com"
r = client.post(
f"{settings.API_V1_STR}/password-recovery/{email}",
headers=normal_user_token_headers,
)
assert r.status_code == 200
assert r.json() == {"message": "Password recovery email sent"}
def test_recovery_password_user_not_exits(
client: TestClient, normal_user_token_headers: dict[str, str]
) -> None:
email = "jVgQr@example.com"
r = client.post(
f"{settings.API_V1_STR}/password-recovery/{email}",
headers=normal_user_token_headers,
)
assert r.status_code == 404
def test_reset_password(
client: TestClient, superuser_token_headers: dict[str, str]
) -> None:
token = generate_password_reset_token(email=settings.FIRST_SUPERUSER)
data = {"new_password": "changethis", "token": token}
r = client.post(
f"{settings.API_V1_STR}/reset-password/",
headers=superuser_token_headers,
json=data,
)
assert r.status_code == 200
assert r.json() == {"message": "Password updated successfully"}
def test_reset_password_invalid_token(
client: TestClient, superuser_token_headers: dict[str, str]
) -> None:
data = {"new_password": "changethis", "token": "invalid"}
r = client.post(
f"{settings.API_V1_STR}/reset-password/",
headers=superuser_token_headers,
json=data,
)
response = r.json()
assert "detail" in response
assert r.status_code == 400
assert response["detail"] == "Invalid token"
+455
View File
@@ -0,0 +1,455 @@
from fastapi.testclient import TestClient
from pytest_mock import MockerFixture
from sqlmodel import Session
from app import crud
from app.core.config import settings
from app.models import UserCreate
from app.tests.utils.utils import random_email, random_lower_string
def test_get_users_superuser_me(
client: TestClient, superuser_token_headers: dict[str, str]
) -> None:
r = client.get(f"{settings.API_V1_STR}/users/me", headers=superuser_token_headers)
current_user = r.json()
assert current_user
assert current_user["is_active"] is True
assert current_user["is_superuser"]
assert current_user["email"] == settings.FIRST_SUPERUSER
def test_get_users_normal_user_me(
client: TestClient, normal_user_token_headers: dict[str, str]
) -> None:
r = client.get(f"{settings.API_V1_STR}/users/me", headers=normal_user_token_headers)
current_user = r.json()
assert current_user
assert current_user["is_active"] is True
assert current_user["is_superuser"] is False
assert current_user["email"] == settings.EMAIL_TEST_USER
def test_create_user_new_email(
client: TestClient,
superuser_token_headers: dict[str, str],
db: Session,
mocker: MockerFixture,
) -> None:
mocker.patch("app.utils.send_email")
mocker.patch("app.core.config.settings.SMTP_HOST", "smtp.example.com")
mocker.patch("app.core.config.settings.SMTP_USER", "admin@example.com")
username = random_email()
password = random_lower_string()
data = {"email": username, "password": password}
r = client.post(
f"{settings.API_V1_STR}/users/",
headers=superuser_token_headers,
json=data,
)
assert 200 <= r.status_code < 300
created_user = r.json()
user = crud.get_user_by_email(session=db, email=username)
assert user
assert user.email == created_user["email"]
def test_get_existing_user(
client: TestClient, superuser_token_headers: dict[str, str], db: Session
) -> None:
username = random_email()
password = random_lower_string()
user_in = UserCreate(email=username, password=password)
user = crud.create_user(session=db, user_create=user_in)
user_id = user.id
r = client.get(
f"{settings.API_V1_STR}/users/{user_id}",
headers=superuser_token_headers,
)
assert 200 <= r.status_code < 300
api_user = r.json()
existing_user = crud.get_user_by_email(session=db, email=username)
assert existing_user
assert existing_user.email == api_user["email"]
def test_get_existing_user_current_user(client: TestClient, db: Session) -> None:
username = random_email()
password = random_lower_string()
user_in = UserCreate(email=username, password=password)
user = crud.create_user(session=db, user_create=user_in)
user_id = user.id
login_data = {
"username": username,
"password": password,
}
r = client.post(f"{settings.API_V1_STR}/login/access-token", data=login_data)
tokens = r.json()
a_token = tokens["access_token"]
headers = {"Authorization": f"Bearer {a_token}"}
r = client.get(
f"{settings.API_V1_STR}/users/{user_id}",
headers=headers,
)
assert 200 <= r.status_code < 300
api_user = r.json()
existing_user = crud.get_user_by_email(session=db, email=username)
assert existing_user
assert existing_user.email == api_user["email"]
def test_get_existing_user_permissions_error(
client: TestClient, normal_user_token_headers: dict[str, str], db: Session
) -> None:
r = client.get(
f"{settings.API_V1_STR}/users/999999",
headers=normal_user_token_headers,
)
assert r.status_code == 403
assert r.json() == {"detail": "The user doesn't have enough privileges"}
def test_create_user_existing_username(
client: TestClient, superuser_token_headers: dict[str, str], db: Session
) -> None:
username = random_email()
# username = email
password = random_lower_string()
user_in = UserCreate(email=username, password=password)
crud.create_user(session=db, user_create=user_in)
data = {"email": username, "password": password}
r = client.post(
f"{settings.API_V1_STR}/users/",
headers=superuser_token_headers,
json=data,
)
created_user = r.json()
assert r.status_code == 400
assert "_id" not in created_user
def test_create_user_by_normal_user(
client: TestClient, normal_user_token_headers: dict[str, str]
) -> None:
username = random_email()
password = random_lower_string()
data = {"email": username, "password": password}
r = client.post(
f"{settings.API_V1_STR}/users/",
headers=normal_user_token_headers,
json=data,
)
assert r.status_code == 400
def test_retrieve_users(
client: TestClient, superuser_token_headers: dict[str, str], db: Session
) -> None:
username = random_email()
password = random_lower_string()
user_in = UserCreate(email=username, password=password)
crud.create_user(session=db, user_create=user_in)
username2 = random_email()
password2 = random_lower_string()
user_in2 = UserCreate(email=username2, password=password2)
crud.create_user(session=db, user_create=user_in2)
r = client.get(f"{settings.API_V1_STR}/users/", headers=superuser_token_headers)
all_users = r.json()
assert len(all_users["data"]) > 1
assert "count" in all_users
for item in all_users["data"]:
assert "email" in item
def test_update_user_me(
client: TestClient, normal_user_token_headers: dict[str, str], db: Session
) -> None:
full_name = "Updated Name"
email = random_email()
data = {"full_name": full_name, "email": email}
r = client.patch(
f"{settings.API_V1_STR}/users/me",
headers=normal_user_token_headers,
json=data,
)
assert r.status_code == 200
updated_user = r.json()
assert updated_user["email"] == email
assert updated_user["full_name"] == full_name
def test_update_password_me(
client: TestClient, superuser_token_headers: dict[str, str], db: Session
) -> None:
new_password = random_lower_string()
data = {
"current_password": settings.FIRST_SUPERUSER_PASSWORD,
"new_password": new_password,
}
r = client.patch(
f"{settings.API_V1_STR}/users/me/password",
headers=superuser_token_headers,
json=data,
)
assert r.status_code == 200
updated_user = r.json()
assert updated_user["message"] == "Password updated successfully"
# Revert to the old password to keep consistency in test
old_data = {
"current_password": new_password,
"new_password": settings.FIRST_SUPERUSER_PASSWORD,
}
r = client.patch(
f"{settings.API_V1_STR}/users/me/password",
headers=superuser_token_headers,
json=old_data,
)
assert r.status_code == 200
def test_update_password_me_incorrect_password(
client: TestClient, superuser_token_headers: dict[str, str], db: Session
) -> None:
new_password = random_lower_string()
data = {"current_password": new_password, "new_password": new_password}
r = client.patch(
f"{settings.API_V1_STR}/users/me/password",
headers=superuser_token_headers,
json=data,
)
assert r.status_code == 400
updated_user = r.json()
assert updated_user["detail"] == "Incorrect password"
def test_update_user_me_email_exists(
client: TestClient, normal_user_token_headers: dict[str, str], db: Session
) -> None:
username = random_email()
password = random_lower_string()
user_in = UserCreate(email=username, password=password)
user = crud.create_user(session=db, user_create=user_in)
data = {"email": user.email}
r = client.patch(
f"{settings.API_V1_STR}/users/me",
headers=normal_user_token_headers,
json=data,
)
assert r.status_code == 409
assert r.json()["detail"] == "User with this email already exists"
def test_update_password_me_same_password_error(
client: TestClient, superuser_token_headers: dict[str, str], db: Session
) -> None:
data = {
"current_password": settings.FIRST_SUPERUSER_PASSWORD,
"new_password": settings.FIRST_SUPERUSER_PASSWORD,
}
r = client.patch(
f"{settings.API_V1_STR}/users/me/password",
headers=superuser_token_headers,
json=data,
)
assert r.status_code == 400
updated_user = r.json()
assert (
updated_user["detail"] == "New password cannot be the same as the current one"
)
def test_create_user_open(client: TestClient, mocker: MockerFixture) -> None:
mocker.patch("app.core.config.settings.USERS_OPEN_REGISTRATION", True)
username = random_email()
password = random_lower_string()
full_name = random_lower_string()
data = {"email": username, "password": password, "full_name": full_name}
r = client.post(
f"{settings.API_V1_STR}/users/open",
json=data,
)
assert r.status_code == 200
created_user = r.json()
assert created_user["email"] == username
assert created_user["full_name"] == full_name
def test_create_user_open_forbidden_error(
client: TestClient, mocker: MockerFixture
) -> None:
mocker.patch("app.core.config.settings.USERS_OPEN_REGISTRATION", False)
username = random_email()
password = random_lower_string()
full_name = random_lower_string()
data = {"email": username, "password": password, "full_name": full_name}
r = client.post(
f"{settings.API_V1_STR}/users/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(
client: TestClient, mocker: MockerFixture
) -> None:
mocker.patch("app.core.config.settings.USERS_OPEN_REGISTRATION", True)
password = random_lower_string()
full_name = random_lower_string()
data = {
"email": settings.FIRST_SUPERUSER,
"password": password,
"full_name": full_name,
}
r = client.post(
f"{settings.API_V1_STR}/users/open",
json=data,
)
assert r.status_code == 400
assert r.json()["detail"] == "The user with this email already exists in the system"
def test_update_user(
client: TestClient, superuser_token_headers: dict[str, str], db: Session
) -> None:
username = random_email()
password = random_lower_string()
user_in = UserCreate(email=username, password=password)
user = crud.create_user(session=db, user_create=user_in)
data = {"full_name": "Updated_full_name"}
r = client.patch(
f"{settings.API_V1_STR}/users/{user.id}",
headers=superuser_token_headers,
json=data,
)
assert r.status_code == 200
updated_user = r.json()
assert updated_user["full_name"] == "Updated_full_name"
def test_update_user_not_exists(
client: TestClient, superuser_token_headers: dict[str, str], db: Session
) -> None:
data = {"full_name": "Updated_full_name"}
r = client.patch(
f"{settings.API_V1_STR}/users/99999999",
headers=superuser_token_headers,
json=data,
)
assert r.status_code == 404
assert r.json()["detail"] == "The user with this id does not exist in the system"
def test_update_user_email_exists(
client: TestClient, superuser_token_headers: dict[str, str], db: Session
) -> None:
username = random_email()
password = random_lower_string()
user_in = UserCreate(email=username, password=password)
user = crud.create_user(session=db, user_create=user_in)
username2 = random_email()
password2 = random_lower_string()
user_in2 = UserCreate(email=username2, password=password2)
user2 = crud.create_user(session=db, user_create=user_in2)
data = {"email": user2.email}
r = client.patch(
f"{settings.API_V1_STR}/users/{user.id}",
headers=superuser_token_headers,
json=data,
)
assert r.status_code == 409
assert r.json()["detail"] == "User with this email already exists"
def test_delete_user_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"
def test_delete_user_current_user(client: TestClient, db: Session) -> None:
username = random_email()
password = random_lower_string()
user_in = UserCreate(email=username, password=password)
user = crud.create_user(session=db, user_create=user_in)
user_id = user.id
login_data = {
"username": username,
"password": password,
}
r = client.post(f"{settings.API_V1_STR}/login/access-token", data=login_data)
tokens = r.json()
a_token = tokens["access_token"]
headers = {"Authorization": f"Bearer {a_token}"}
r = client.delete(
f"{settings.API_V1_STR}/users/{user_id}",
headers=headers,
)
assert r.status_code == 200
deleted_user = r.json()
assert deleted_user["message"] == "User deleted successfully"
def test_delete_user_not_found(
client: TestClient, superuser_token_headers: dict[str, str], db: Session
) -> None:
r = client.delete(
f"{settings.API_V1_STR}/users/99999999",
headers=superuser_token_headers,
)
assert r.status_code == 404
assert r.json()["detail"] == "User not found"
def test_delete_user_current_super_user_error(
client: TestClient, superuser_token_headers: dict[str, str], db: Session
) -> None:
super_user = crud.get_user_by_email(session=db, email=settings.FIRST_SUPERUSER)
assert super_user
user_id = super_user.id
r = client.delete(
f"{settings.API_V1_STR}/users/{user_id}",
headers=superuser_token_headers,
)
assert r.status_code == 403
assert r.json()["detail"] == "Super users are not allowed to delete themselves"
def test_delete_user_without_privileges(
client: TestClient, normal_user_token_headers: dict[str, str], db: Session
) -> None:
username = random_email()
password = random_lower_string()
user_in = UserCreate(email=username, password=password)
user = crud.create_user(session=db, user_create=user_in)
r = client.delete(
f"{settings.API_V1_STR}/users/{user.id}",
headers=normal_user_token_headers,
)
assert r.status_code == 403
assert r.json()["detail"] == "The user doesn't have enough privileges"
+42
View File
@@ -0,0 +1,42 @@
from collections.abc import Generator
import pytest
from fastapi.testclient import TestClient
from sqlmodel import Session, delete
from app.core.config import settings
from app.core.db import engine, init_db
from app.main import app
from app.models import Item, User
from app.tests.utils.user import authentication_token_from_email
from app.tests.utils.utils import get_superuser_token_headers
@pytest.fixture(scope="session", autouse=True)
def db() -> Generator[Session, None, None]:
with Session(engine) as session:
init_db(session)
yield session
statement = delete(Item)
session.execute(statement)
statement = delete(User)
session.execute(statement)
session.commit()
@pytest.fixture(scope="module")
def client() -> Generator[TestClient, None, None]:
with TestClient(app) as c:
yield c
@pytest.fixture(scope="module")
def superuser_token_headers(client: TestClient) -> dict[str, str]:
return get_superuser_token_headers(client)
@pytest.fixture(scope="module")
def normal_user_token_headers(client: TestClient, db: Session) -> dict[str, str]:
return authentication_token_from_email(
client=client, email=settings.EMAIL_TEST_USER, db=db
)
+91
View File
@@ -0,0 +1,91 @@
from fastapi.encoders import jsonable_encoder
from sqlmodel import Session
from app import crud
from app.core.security import verify_password
from app.models import User, UserCreate, UserUpdate
from app.tests.utils.utils import random_email, random_lower_string
def test_create_user(db: Session) -> None:
email = random_email()
password = random_lower_string()
user_in = UserCreate(email=email, password=password)
user = crud.create_user(session=db, user_create=user_in)
assert user.email == email
assert hasattr(user, "hashed_password")
def test_authenticate_user(db: Session) -> None:
email = random_email()
password = random_lower_string()
user_in = UserCreate(email=email, password=password)
user = crud.create_user(session=db, user_create=user_in)
authenticated_user = crud.authenticate(session=db, email=email, password=password)
assert authenticated_user
assert user.email == authenticated_user.email
def test_not_authenticate_user(db: Session) -> None:
email = random_email()
password = random_lower_string()
user = crud.authenticate(session=db, email=email, password=password)
assert user is None
def test_check_if_user_is_active(db: Session) -> None:
email = random_email()
password = random_lower_string()
user_in = UserCreate(email=email, password=password)
user = crud.create_user(session=db, user_create=user_in)
assert user.is_active is True
def test_check_if_user_is_active_inactive(db: Session) -> None:
email = random_email()
password = random_lower_string()
user_in = UserCreate(email=email, password=password, disabled=True)
user = crud.create_user(session=db, user_create=user_in)
assert user.is_active
def test_check_if_user_is_superuser(db: Session) -> None:
email = random_email()
password = random_lower_string()
user_in = UserCreate(email=email, password=password, is_superuser=True)
user = crud.create_user(session=db, user_create=user_in)
assert user.is_superuser is True
def test_check_if_user_is_superuser_normal_user(db: Session) -> None:
username = random_email()
password = random_lower_string()
user_in = UserCreate(email=username, password=password)
user = crud.create_user(session=db, user_create=user_in)
assert user.is_superuser is False
def test_get_user(db: Session) -> None:
password = random_lower_string()
username = random_email()
user_in = UserCreate(email=username, password=password, is_superuser=True)
user = crud.create_user(session=db, user_create=user_in)
user_2 = db.get(User, user.id)
assert user_2
assert user.email == user_2.email
assert jsonable_encoder(user) == jsonable_encoder(user_2)
def test_update_user(db: Session) -> None:
password = random_lower_string()
email = random_email()
user_in = UserCreate(email=email, password=password, is_superuser=True)
user = crud.create_user(session=db, user_create=user_in)
new_password = random_lower_string()
user_in_update = UserUpdate(password=new_password, is_superuser=True)
if user.id is not None:
crud.update_user(session=db, db_user=user, user_in=user_in_update)
user_2 = db.get(User, user.id)
assert user_2
assert user.email == user_2.email
assert verify_password(new_password, user_2.hashed_password)
@@ -0,0 +1,33 @@
from unittest.mock import MagicMock
from pytest_mock import MockerFixture
from sqlmodel import select
from app.backend_pre_start import init, logger
def test_init_successful_connection(mocker: MockerFixture) -> None:
engine_mock = MagicMock()
session_mock = MagicMock()
exec_mock = MagicMock(return_value=True)
session_mock.configure_mock(**{"exec.return_value": exec_mock})
mocker.patch("sqlmodel.Session", return_value=session_mock)
mocker.patch.object(logger, "info")
mocker.patch.object(logger, "error")
mocker.patch.object(logger, "warn")
try:
init(engine_mock)
connection_successful = True
except Exception:
connection_successful = False
assert (
connection_successful
), "The database connection should be successful and not raise an exception."
assert session_mock.exec.called_once_with(
select(1)
), "The session should execute a select statement once."
@@ -0,0 +1,33 @@
from unittest.mock import MagicMock
from pytest_mock import MockerFixture
from sqlmodel import select
from app.tests_pre_start import init, logger
def test_init_successful_connection(mocker: MockerFixture) -> None:
engine_mock = MagicMock()
session_mock = MagicMock()
exec_mock = MagicMock(return_value=True)
session_mock.configure_mock(**{"exec.return_value": exec_mock})
mocker.patch("sqlmodel.Session", return_value=session_mock)
mocker.patch.object(logger, "info")
mocker.patch.object(logger, "error")
mocker.patch.object(logger, "warn")
try:
init(engine_mock)
connection_successful = True
except Exception:
connection_successful = False
assert (
connection_successful
), "The database connection should be successful and not raise an exception."
assert session_mock.exec.called_once_with(
select(1)
), "The session should execute a select statement once."
+16
View File
@@ -0,0 +1,16 @@
from sqlmodel import Session
from app import crud
from app.models import Item, ItemCreate
from app.tests.utils.user import create_random_user
from app.tests.utils.utils import random_lower_string
def create_random_item(db: Session) -> Item:
user = create_random_user(db)
owner_id = user.id
assert owner_id is not None
title = random_lower_string()
description = random_lower_string()
item_in = ItemCreate(title=title, description=description)
return crud.create_item(session=db, item_in=item_in, owner_id=owner_id)
+49
View File
@@ -0,0 +1,49 @@
from fastapi.testclient import TestClient
from sqlmodel import Session
from app import crud
from app.core.config import settings
from app.models import User, UserCreate, UserUpdate
from app.tests.utils.utils import random_email, random_lower_string
def user_authentication_headers(
*, client: TestClient, email: str, password: str
) -> dict[str, str]:
data = {"username": email, "password": password}
r = client.post(f"{settings.API_V1_STR}/login/access-token", data=data)
response = r.json()
auth_token = response["access_token"]
headers = {"Authorization": f"Bearer {auth_token}"}
return headers
def create_random_user(db: Session) -> User:
email = random_email()
password = random_lower_string()
user_in = UserCreate(email=email, password=password)
user = crud.create_user(session=db, user_create=user_in)
return user
def authentication_token_from_email(
*, client: TestClient, email: str, db: Session
) -> dict[str, str]:
"""
Return a valid token for the user with given email.
If the user doesn't exist it is created first.
"""
password = random_lower_string()
user = crud.get_user_by_email(session=db, email=email)
if not user:
user_in_create = UserCreate(email=email, password=password)
user = crud.create_user(session=db, user_create=user_in_create)
else:
user_in_update = UserUpdate(password=password)
if not user.id:
raise Exception("User id not set")
user = crud.update_user(session=db, db_user=user, user_in=user_in_update)
return user_authentication_headers(client=client, email=email, password=password)
+26
View File
@@ -0,0 +1,26 @@
import random
import string
from fastapi.testclient import TestClient
from app.core.config import settings
def random_lower_string() -> str:
return "".join(random.choices(string.ascii_lowercase, k=32))
def random_email() -> str:
return f"{random_lower_string()}@{random_lower_string()}.com"
def get_superuser_token_headers(client: TestClient) -> dict[str, str]:
login_data = {
"username": settings.FIRST_SUPERUSER,
"password": settings.FIRST_SUPERUSER_PASSWORD,
}
r = client.post(f"{settings.API_V1_STR}/login/access-token", data=login_data)
tokens = r.json()
a_token = tokens["access_token"]
headers = {"Authorization": f"Bearer {a_token}"}
return headers
@@ -1,8 +1,10 @@
import logging 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 tenacity import after_log, before_log, retry, stop_after_attempt, wait_fixed
from app.db.session import db_session from app.core.db import engine
logging.basicConfig(level=logging.INFO) logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -17,18 +19,19 @@ wait_seconds = 1
before=before_log(logger, logging.INFO), before=before_log(logger, logging.INFO),
after=after_log(logger, logging.WARN), after=after_log(logger, logging.WARN),
) )
def init(): def init(db_engine: Engine) -> None:
try: try:
# Try to create session to check if DB is awake # Try to create session to check if DB is awake
db_session.execute("SELECT 1") with Session(db_engine) as session:
session.exec(select(1))
except Exception as e: except Exception as e:
logger.error(e) logger.error(e)
raise e raise e
def main(): def main() -> None:
logger.info("Initializing service") logger.info("Initializing service")
init() init(engine)
logger.info("Service finished initializing") logger.info("Service finished initializing")
+116
View File
@@ -0,0 +1,116 @@
import logging
from dataclasses import dataclass
from datetime import datetime, timedelta
from pathlib import Path
from typing import Any
import emails # type: ignore
from jinja2 import Template
from jose import JWTError, jwt
from app.core.config import settings
@dataclass
class EmailData:
html_content: str
subject: str
def render_email_template(*, template_name: str, context: dict[str, Any]) -> str:
template_str = (
Path(__file__).parent / "email-templates" / "build" / template_name
).read_text()
html_content = Template(template_str).render(context)
return html_content
def send_email(
*,
email_to: str,
subject: str = "",
html_content: str = "",
) -> None:
assert settings.emails_enabled, "no provided configuration for email variables"
message = emails.Message(
subject=subject,
html=html_content,
mail_from=(settings.EMAILS_FROM_NAME, settings.EMAILS_FROM_EMAIL),
)
smtp_options = {"host": settings.SMTP_HOST, "port": settings.SMTP_PORT}
if settings.SMTP_TLS:
smtp_options["tls"] = True
elif settings.SMTP_SSL:
smtp_options["ssl"] = True
if settings.SMTP_USER:
smtp_options["user"] = settings.SMTP_USER
if settings.SMTP_PASSWORD:
smtp_options["password"] = settings.SMTP_PASSWORD
response = message.send(to=email_to, smtp=smtp_options)
logging.info(f"send email result: {response}")
def generate_test_email(email_to: str) -> EmailData:
project_name = settings.PROJECT_NAME
subject = f"{project_name} - Test email"
html_content = render_email_template(
template_name="test_email.html",
context={"project_name": settings.PROJECT_NAME, "email": email_to},
)
return EmailData(html_content=html_content, subject=subject)
def generate_reset_password_email(email_to: str, email: str, token: str) -> EmailData:
project_name = settings.PROJECT_NAME
subject = f"{project_name} - Password recovery for user {email}"
link = f"{settings.server_host}/reset-password?token={token}"
html_content = render_email_template(
template_name="reset_password.html",
context={
"project_name": settings.PROJECT_NAME,
"username": email,
"email": email_to,
"valid_hours": settings.EMAIL_RESET_TOKEN_EXPIRE_HOURS,
"link": link,
},
)
return EmailData(html_content=html_content, subject=subject)
def generate_new_account_email(
email_to: str, username: str, password: str
) -> EmailData:
project_name = settings.PROJECT_NAME
subject = f"{project_name} - New account for user {username}"
html_content = render_email_template(
template_name="new_account.html",
context={
"project_name": settings.PROJECT_NAME,
"username": username,
"password": password,
"email": email_to,
"link": settings.server_host,
},
)
return EmailData(html_content=html_content, subject=subject)
def generate_password_reset_token(email: str) -> str:
delta = timedelta(hours=settings.EMAIL_RESET_TOKEN_EXPIRE_HOURS)
now = datetime.utcnow()
expires = now + delta
exp = expires.timestamp()
encoded_jwt = jwt.encode(
{"exp": exp, "nbf": now, "sub": email},
settings.SECRET_KEY,
algorithm="HS256",
)
return encoded_jwt
def verify_password_reset_token(token: str) -> str | None:
try:
decoded_token = jwt.decode(token, settings.SECRET_KEY, algorithms=["HS256"])
return str(decoded_token["sub"])
except JWTError:
return None
+2257
View File
File diff suppressed because it is too large Load Diff
+75
View File
@@ -0,0 +1,75 @@
[tool.poetry]
name = "app"
version = "0.1.0"
description = ""
authors = ["Admin <admin@example.com>"]
[tool.poetry.dependencies]
python = "^3.10"
uvicorn = {extras = ["standard"], version = "^0.24.0.post1"}
fastapi = "^0.109.1"
python-multipart = "^0.0.7"
email-validator = "^2.1.0.post1"
passlib = {extras = ["bcrypt"], version = "^1.7.4"}
tenacity = "^8.2.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]
requires = ["poetry>=0.12"]
build-backend = "poetry.masonry.api"
[tool.mypy]
strict = true
exclude = ["venv", "alembic"]
[tool.ruff]
target-version = "py310"
[tool.ruff.lint]
select = [
"E", # pycodestyle errors
"W", # pycodestyle warnings
"F", # pyflakes
"I", # isort
"B", # flake8-bugbear
"C4", # flake8-comprehensions
"UP", # pyupgrade
]
ignore = [
"E501", # line too long, handled by black
"B008", # do not perform function calls in argument defaults
"W191", # indentation contains tabs
"B904", # Allow raising exceptions without from e, for HTTPException
]
[tool.ruff.lint.pyupgrade]
# Preserve types, even if a file imports `from __future__ import annotations`.
keep-runtime-typing = true
+6
View File
@@ -0,0 +1,6 @@
#!/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
+6
View File
@@ -0,0 +1,6 @@
#!/bin/sh -e
set -x
autoflake --remove-all-unused-imports --recursive --remove-unused-variables --in-place app --exclude=__init__.py
black app
isort --recursive --apply app
+8
View File
@@ -0,0 +1,8 @@
#!/usr/bin/env bash
set -e
set -x
mypy app
ruff app
ruff format app --check
+6
View File
@@ -0,0 +1,6 @@
#!/usr/bin/env bash
set -e
set -x
bash scripts/test.sh --cov-report=html "${@}"
+8
View File
@@ -0,0 +1,8 @@
#!/usr/bin/env bash
set -e
set -x
coverage run --source=app -m pytest
coverage report --show-missing
coverage html --title "${@-coverage}"
@@ -1,6 +1,7 @@
#! /usr/bin/env bash #! /usr/bin/env bash
set -e set -e
set -x
python /app/app/tests_pre_start.py python /app/app/tests_pre_start.py
pytest /app/app/tests/ bash ./scripts/test.sh "$@"
-45
View File
@@ -1,45 +0,0 @@
{
"project_name": "Base Project",
"project_slug": "{{ cookiecutter.project_name|lower|replace(' ', '-') }}",
"domain_main": "{{cookiecutter.project_slug}}.com",
"domain_staging": "stag.{{cookiecutter.domain_main}}",
"docker_swarm_stack_name_main": "{{cookiecutter.domain_main|replace('.', '-')}}",
"docker_swarm_stack_name_staging": "{{cookiecutter.domain_staging|replace('.', '-')}}",
"secret_key": "changethis",
"first_superuser": "admin@{{cookiecutter.domain_main}}",
"first_superuser_password": "changethis",
"backend_cors_origins": "http://localhost, http://localhost:4200, http://localhost:3000, http://localhost:8080, https://localhost, https://localhost:4200, https://localhost:3000, https://localhost:8080, http://dev.{{cookiecutter.domain_main}}, https://{{cookiecutter.domain_staging}}, https://{{cookiecutter.domain_main}}, http://local.dockertoolbox.tiangolo.com, http://localhost.tiangolo.com",
"smtp_port": "587",
"smtp_host": "",
"smtp_user": "",
"smtp_password": "",
"smtp_emails_from_email": "info@{{cookiecutter.domain_main}}",
"postgres_password": "changethis",
"pgadmin_default_user": "{{cookiecutter.first_superuser}}",
"pgadmin_default_user_password": "{{cookiecutter.first_superuser_password}}",
"traefik_constraint_tag": "{{cookiecutter.domain_main}}",
"traefik_constraint_tag_staging": "{{cookiecutter.domain_staging}}",
"traefik_public_network": "traefik-public",
"traefik_public_constraint_tag": "traefik-public",
"flower_auth": "admin:{{cookiecutter.first_superuser_password}}",
"sentry_dsn": "",
"docker_image_prefix": "",
"docker_image_backend": "{{cookiecutter.docker_image_prefix}}backend",
"docker_image_celeryworker": "{{cookiecutter.docker_image_prefix}}celeryworker",
"docker_image_frontend": "{{cookiecutter.docker_image_prefix}}frontend",
"_copy_without_render": [
"frontend/src/**/*.html",
"frontend/src/**/*.vue",
"frontend/node_modules/*",
"backend/app/app/email-templates/**"
]
}
+102
View File
@@ -0,0 +1,102 @@
project_name:
type: str
help: The name of the project, shown to API users (in .env)
default: FastAPI Project
stack_name:
type: str
help: The name of the stack used for Docker Compose labels (no spaces) (in .env)
default: fastapi-project
secret_key:
type: str
help: |
'The secret key for the project, used for security,
stored in .env, you can generate one with:
python -c "import secrets; print(secrets.token_urlsafe(32))"'
default: changethis
first_superuser:
type: str
help: The email of the first superuser (in .env)
default: admin@example.com
first_superuser_password:
type: str
help: The password of the first superuser (in .env)
default: changethis
smtp_host:
type: str
help: The SMTP server host to send emails, you can set it later in .env
default: ""
smtp_user:
type: str
help: The SMTP server user to send emails, you can set it later in .env
default: ""
smtp_password:
type: str
help: The SMTP server password to send emails, you can set it later in .env
default: ""
emails_from_email:
type: str
help: The email account to send emails from, you can set it later in .env
default: info@example.com
postgres_password:
type: str
help: |
'The password for the PostgreSQL database, stored in .env,
you can generate one with:
python -c "import secrets; print(secrets.token_urlsafe(32))"'
default: changethis
sentry_dsn:
type: str
help: The DSN for Sentry, if you are using it, you can set it later in .env
default: ""
_exclude:
# Global
- .vscode
- .mypy_cache
- poetry.lock
# Python
- __pycache__
- app.egg-info
- "*.pyc"
- .mypy_cache
- .coverage
- htmlcov
- poetry.lock
- .cache
- .venv
# Frontend
# Logs
- logs
- "*.log"
- npm-debug.log*
- yarn-debug.log*
- yarn-error.log*
- pnpm-debug.log*
- lerna-debug.log*
- node_modules
- dist
- dist-ssr
- "*.local"
# Editor directories and files
- .idea
- .DS_Store
- "*.suo"
- "*.ntvs*"
- "*.njsproj"
- "*.sln"
- "*.sw?"
_answers_file: .copier/.copier-answers.yml
_tasks:
- "python .copier/update_dotenv.py"
+291
View File
@@ -0,0 +1,291 @@
# FastAPI Project - Deployment
You can deploy the project using Docker Compose to a remote server.
This project expects you to have a Traefik proxy handling communication to the outside world and HTTPS certificates.
You can use CI/CD (continuous integration and continuous deployment) systems to deploy automatically, there are already configurations to do it with GitHub Actions.
But you have to configure a couple things first. 🤓
## Preparation
* Have a remote server ready and available.
* Configure the DNS records of your domain to point to the IP of the server you just created.
* Configure a wildcard subdomain for your domain, so that you can have multiple subdomains for different services, e.g. `*.fastapi-project.example.com`. This will be useful for accessing different components, like `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.
* Install and configure [Docker](https://docs.docker.com/engine/install/) on the remote server (Docker Engine, not Docker Desktop).
## Public Traefik
We need a Traefik proxy to handle incoming connections and HTTPS certificates.
You need to do these next steps only once.
### Traefik Docker Compose
* Create a remote directory to store your Traefik Docker Compose file:
```bash
mkdir -p /root/code/traefik-public/
```
Copy the Traefik Docker Compose file to your server. You could do it by running the command `rsync` in your local terminal:
```bash
rsync -a docker-compose.traefik.yml root@your-server.example.com:/root/code/traefik-public/
```
### Traefik Public Network
This Traefik will expect a Docker "public network" named `traefik-public` to communicate with your stack(s).
This way, there will be a single public Traefik proxy that handles the communication (HTTP and HTTPS) with the outside world, and then behind that, you could have one or more stacks with different domains, even if they are on the same single server.
To create a Docker "public network" named `traefik-public` run the following command in your remote server:
```bash
docker network create traefik-public
```
### Traefik Environment Variables
The Traefik Docker Compose file expects some environment variables to be set in your terminal before starting it. You can do it by running the following commands in your remote server.
* Create the username for HTTP Basic Auth, e.g.:
```bash
export USERNAME=admin
```
* Create an environment variable with the password for HTTP Basic Auth, e.g.:
```bash
export PASSWORD=changethis
```
* Use openssl to generate the "hashed" version of the password for HTTP Basic Auth and store it in an environment variable:
```bash
export HASHED_PASSWORD=$(openssl passwd -apr1 $PASSWORD)
```
To verify that the hashed password is correct, you can print it:
```bash
echo $HASHED_PASSWORD
```
* Create an environment variable with the domain name for your server, e.g.:
```bash
export DOMAIN=fastapi-project.example.com
```
* Create an environment variable with the email for Let's Encrypt, e.g.:
```bash
export EMAIL=admin@example.com
```
**Note**: you need to set a different email, an email `@example.com` won't work.
### Start the Traefik Docker Compose
Go to the directory where you copied the Traefik Docker Compose file in your remote server:
```bash
cd /root/code/traefik-public/
```
Now with the environment variables set and the `docker-compose.traefik.yml` in place, you can start the Traefik Docker Compose running the following command:
```bash
docker compose -f docker-compose.traefik.yml up -d
```
## Deploy the FastAPI Project
Now that you have Traefik in place you can deploy your FastAPI project with Docker Compose.
**Note**: You might want to jump ahead to the section about Continuous Deployment with GitHub Actions.
## Environment Variables
You need to set some environment variables first.
Set the `ENVIRONMENT`, by default `local` (for development), but when deploying to a server you would put something like `staging` or `production`:
```bash
export ENVIRONMENT=production
```
Set the `DOMAIN`, by default `localhost` (for development), but when deploying you would use your own domain, for example:
```bash
export DOMAIN=fastapi-project.example.com
```
You can set several variables, like:
* `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.
* `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.
* `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_USER`: The SMTP server user to send emails.
* `SMTP_PASSWORD`: The SMTP server password to send emails.
* `EMAILS_FROM_EMAIL`: The email account to send emails from.
* `POSTGRES_SERVER`: The hostname of the PostgreSQL server. You can leave the default of `db`, provided by the same Docker Compose. You normally wouldn't need to change this unless you are using a third-party provider.
* `POSTGRES_PORT`: The port of the PostgreSQL server. You can leave the default. You normally wouldn't need to change this unless you are using a third-party provider.
* `POSTGRES_PASSWORD`: The Postgres password.
* `POSTGRES_USER`: The Postgres user, you can leave the default.
* `POSTGRES_DB`: The database name to use for this application. You can leave the default of `app`.
* `SENTRY_DSN`: The DSN for Sentry, if you are using it.
### Generate secret keys
Some environment variables in the `.env` file have a default value of `changethis`.
You have to change them with a secret key, to generate secret keys you can run the following command:
```bash
python -c "import secrets; print(secrets.token_urlsafe(32))"
```
Copy the content and use that as password / secret key. And run that again to generate another secure key.
### Deploy with Docker Compose
With the environment variables in place, you can deploy with Docker Compose:
```bash
docker compose -f docker-compose.yml up -d
```
For production you wouldn't want to have the overrides in `docker-compose.override.yml`, that's why we explicitly specify `docker-compose.yml` as the file to use.
## Continuous Deployment (CD)
You can use GitHub Actions to deploy your project automatically. 😎
You can have multiple environment deployments.
There are already two environments configured, `staging` and `production`. 🚀
### Install GitHub Actions Runner
* On your remote server, if you are running as the `root` user, create a user for your GitHub Actions:
```bash
adduser github
```
* Add Docker permissions to the `github` user:
```bash
usermod -aG docker github
```
* Temporarily switch to the `github` user:
```bash
su - github
```
* Go to the `github` user's home directory:
```bash
cd
```
* [Install a GitHub Action self-hosted runner following the official guide](https://docs.github.com/en/actions/hosting-your-own-runners/managing-self-hosted-runners/adding-self-hosted-runners#adding-a-self-hosted-runner-to-a-repository).
* When asked about labels, add a label for the environment, e.g. `production`. You can also add labels later.
After installing, the guide would tell you to run a command to start the runner. Nevertheless, it would stop once you terminate that process or if your local connection to your server is lost.
To make sure it runs on startup and continues running, you can install it as a service. To do that, exit the `github` user and go back to the `root` user:
```bash
exit
```
After you do it, you would be on the `root` user again. And you will be on the previous directory, belonging to the `root` user.
* Go to the `actions-runner` directory inside of the `github` user's home directory:
```bash
cd /home/github/actions-runner
```
* Install the self-hosted runner as a service with the user `github`:
```bash
./svc.sh install github
```
* Start the service:
```bash
./svc.sh start
```
* Check the status of the service:
```bash
./svc.sh status
```
You can read more about it in the official guide: [Configuring the self-hosted runner application as a service](https://docs.github.com/en/actions/hosting-your-own-runners/managing-self-hosted-runners/configuring-the-self-hosted-runner-application-as-a-service).
### Set Secrets
On your repository, configure secrets for the environment variables you need, the same ones described above, including `SECRET_KEY`, etc. Follow the [official GitHub guide for setting repository secrets](https://docs.github.com/en/actions/security-guides/using-secrets-in-github-actions#creating-secrets-for-a-repository).
The current Github Actions workflows expect these secrets:
* `DOMAIN_PRODUCTION`
* `DOMAIN_STAGING`
* `EMAILS_FROM_EMAIL`
* `FIRST_SUPERUSER`
* `FIRST_SUPERUSER_PASSWORD`
* `POSTGRES_PASSWORD`
* `SECRET_KEY`
## GitHub Action Deployment Workflows
There are GitHub Action workflows in the `.github/workflows` directory already configured for deploying to the environments (GitHub Actions runners with the labels):
* `staging`: after pushing (or merging) to the branch `master`.
* `production`: after publishing a release.
If you need to add extra environments you could use those as a starting point.
## URLs
Replace `fastapi-project.example.com` with your domain.
### Main Traefik Dashboard
Traefik UI: `https://traefik.fastapi-project.example.com`
### Production
Frontend: `https://fastapi-project.example.com`
Backend API docs: `https://fastapi-project.example.com/docs`
Backend API base URL: `https://fastapi-project.example.com/api/`
Adminer: `https://adminer.fastapi-project.example.com`
### Staging
Frontend: `https://staging.fastapi-project.example.com`
Backend API docs: `https://staging.fastapi-project.example.com/docs`
Backend API base URL: `https://staging.fastapi-project.example.com/api/`
Adminer: `https://staging.adminer.fastapi-project.example.com`
-17
View File
@@ -1,17 +0,0 @@
#! /usr/bin/env bash
# Run this script from outside the project, to integrate a dev-fsfp project with changes and review modifications
# Exit in case of error
set -e
if [ $(uname -s) = "Linux" ]; then
echo "Remove __pycache__ files"
sudo find ./dev-fsfp/ -type d -name __pycache__ -exec rm -r {} \+
fi
rm -rf ./full-stack-fastapi-postgresql/\{\{cookiecutter.project_slug\}\}/*
rsync -a --exclude=node_modules ./dev-fsfp/* ./full-stack-fastapi-postgresql/\{\{cookiecutter.project_slug\}\}/
rsync -a ./dev-fsfp/{.env,.gitignore,.gitlab-ci.yml} ./full-stack-fastapi-postgresql/\{\{cookiecutter.project_slug\}\}/
-2
View File
@@ -1,2 +0,0 @@
default_context:
"project_name": "Dev FSFP"
-10
View File
@@ -1,10 +0,0 @@
#! /usr/bin/env bash
# Run this script from outside the project, to generate a dev-fsfp project
# Exit in case of error
set -e
rm -rf ./dev-fsfp
cookiecutter --config-file ./full-stack-fastapi-postgresql/dev-fsfp-config.yml --no-input -f ./full-stack-fastapi-postgresql
+128
View File
@@ -0,0 +1,128 @@
# FastAPI Project - Development
## Development in `localhost` with a custom domain
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`.
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.
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.
* **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.
To configure it in your stack, follow the section **Change the development "domain"** below, using the domain `dev.example.com`.
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`.
Check all the corresponding available URLs in the section at the end.
## Change the development "domain"
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.
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.
* Open the file located at `./.env`. It would have a line like:
```
DOMAIN=localhost
```
* Change it to the domain you are going to use, e.g.:
```
DOMAIN=localhost.tiangolo.com
```
That variable will be used by the Docker Compose files.
After that, you can restart your stack with:
```bash
docker compose up -d
```
and check all the corresponding available URLs in the section at the end.
## Docker Compose files and env vars
There is a main `docker-compose.yml` file with all the configurations that apply to the whole stack, it is used automatically by `docker compose`.
And there's also a `docker-compose.override.yml` with overrides for development, for example to mount the source code as a volume. It is used automatically by `docker compose` to apply overrides on top of `docker-compose.yml`.
These Docker Compose files use the `.env` file containing configurations to be injected as environment variables in the containers.
They also use some additional configurations taken from environment variables set in the scripts before calling the `docker compose` command.
## The .env file
The `.env` file is the one that contains all your configurations, generated keys and passwords, etc.
Depending on your workflow, you could want to exclude it from Git, for example if your project is public. In that case, you would have to make sure to set up a way for your CI tools to obtain it while building or deploying your project.
One way to do it could be to add each environment variable to your CI/CD system, and updating the `docker-compose.yml` file to read that specific env var instead of reading the `.env` file.
## URLs
The production or staging URLs would use these same paths, but with your own domain.
### Development URLs
Development URLs, for local development.
Frontend: http://localhost
Backend: http://localhost/api/
Automatic Interactive Docs (Swagger UI): https://localhost/docs
Automatic Alternative Docs (ReDoc): https://localhost/redoc
Adminer: http://localhost:8080
Traefik UI: http://localhost:8090
### Development in localhost with a custom domain URLs
Development URLs, for local development.
Frontend: http://localhost.tiangolo.com
Backend: http://localhost.tiangolo.com/api/
Automatic Interactive Docs (Swagger UI): https://localhost.tiangolo.com/docs
Automatic Alternative Docs (ReDoc): https://localhost.tiangolo.com/redoc
Adminer: http://localhost.tiangolo.com:8080
Traefik UI: http://localhost.tiangolo.com:8090
+75
View File
@@ -0,0 +1,75 @@
version: "3.3"
services:
proxy:
image: traefik:v2.3
volumes:
- /var/run/docker.sock:/var/run/docker.sock
ports:
- "80:80"
- "8090:8080"
# Duplicate the command from docker-compose.yml to add --api.insecure=true
command:
# Enable Docker in Traefik, so that it reads labels from Docker services
- --providers.docker
# Add a constraint to only use services with the label for this stack
- --providers.docker.constraints=Label(`traefik.constraint-label`, `traefik-public`)
# Do not expose all Docker services, only the ones explicitly exposed
- --providers.docker.exposedbydefault=false
# Create an entrypoint "http" listening on port 80
- --entrypoints.http.address=:80
# Create an entrypoint "https" listening on port 443
- --entrypoints.https.address=:443
# Enable the access log, with HTTP requests
- --accesslog
# Enable the Traefik log, for configurations and errors
- --log
# Enable debug logging for local development
- --log.level=DEBUG
# Enable the Dashboard and API
- --api
# Enable the Dashboard and API in insecure mode for local development
- --api.insecure=true
labels:
# Enable Traefik for this service, to make it available in the public network
- traefik.enable=true
- traefik.constraint-label=traefik-public
# Dummy https-redirect middleware that doesn't really redirect, only to
# allow running it locally
- traefik.http.middlewares.https-redirect.contenttype.autodetect=false
db:
restart: "no"
ports:
- "5432:5432"
adminer:
restart: "no"
ports:
- "8080:8080"
backend:
restart: "no"
ports:
- "8888:8888"
volumes:
- ./backend/:/app
build:
context: ./backend
args:
INSTALL_DEV: ${INSTALL_DEV-true}
# command: sleep infinity # Infinite loop to keep container alive doing nothing
command: /start-reload.sh
frontend:
restart: "no"
build:
context: ./frontend
args:
- VITE_API_URL=http://${DOMAIN?Variable not set}
- NODE_ENV=development
networks:
traefik-public:
# For local dev, don't expect an external Traefik network
external: false
+77
View File
@@ -0,0 +1,77 @@
services:
traefik:
image: traefik:v2.3
ports:
# Listen on port 80, default for HTTP, necessary to redirect to HTTPS
- 80:80
# Listen on port 443, default for HTTPS
- 443:443
restart: always
labels:
# Enable Traefik for this service, to make it available in the public network
- traefik.enable=true
# Use the traefik-public network (declared below)
- traefik.docker.network=traefik-public
# Define the port inside of the Docker service to use
- traefik.http.services.traefik-dashboard.loadbalancer.server.port=8080
# Make Traefik use this domain (from an environment variable) in HTTP
- traefik.http.routers.traefik-dashboard-http.entrypoints=http
- traefik.http.routers.traefik-dashboard-http.rule=Host(`traefik.${DOMAIN?Variable not set}`)
# traefik-https the actual router using HTTPS
- traefik.http.routers.traefik-dashboard-https.entrypoints=https
- traefik.http.routers.traefik-dashboard-https.rule=Host(`traefik.${DOMAIN?Variable not set}`)
- traefik.http.routers.traefik-dashboard-https.tls=true
# Use the "le" (Let's Encrypt) resolver created below
- traefik.http.routers.traefik-dashboard-https.tls.certresolver=le
# Use the special Traefik service api@internal with the web UI/Dashboard
- traefik.http.routers.traefik-dashboard-https.service=api@internal
# https-redirect middleware to redirect HTTP to HTTPS
- traefik.http.middlewares.https-redirect.redirectscheme.scheme=https
- traefik.http.middlewares.https-redirect.redirectscheme.permanent=true
# traefik-http set up only to use the middleware to redirect to https
- traefik.http.routers.traefik-dashboard-http.middlewares=https-redirect
# admin-auth middleware with HTTP Basic auth
# Using the environment variables USERNAME and HASHED_PASSWORD
- traefik.http.middlewares.admin-auth.basicauth.users=${USERNAME?Variable not set}:${HASHED_PASSWORD?Variable not set}
# Enable HTTP Basic auth, using the middleware created above
- traefik.http.routers.traefik-dashboard-https.middlewares=admin-auth
volumes:
# Add Docker as a mounted volume, so that Traefik can read the labels of other services
- /var/run/docker.sock:/var/run/docker.sock:ro
# Mount the volume to store the certificates
- traefik-public-certificates:/certificates
command:
# Enable Docker in Traefik, so that it reads labels from Docker services
- --providers.docker
# Do not expose all Docker services, only the ones explicitly exposed
- --providers.docker.exposedbydefault=false
# Create an entrypoint "http" listening on port 80
- --entrypoints.http.address=:80
# Create an entrypoint "https" listening on port 443
- --entrypoints.https.address=:443
# Create the certificate resolver "le" for Let's Encrypt, uses the environment variable EMAIL
- --certificatesresolvers.le.acme.email=${EMAIL?Variable not set}
# Store the Let's Encrypt certificates in the mounted volume
- --certificatesresolvers.le.acme.storage=/certificates/acme.json
# Use the TLS Challenge for Let's Encrypt
- --certificatesresolvers.le.acme.tlschallenge=true
# Enable the access log, with HTTP requests
- --accesslog
# Enable the Traefik log, for configurations and errors
- --log
# Enable the Dashboard and API
- --api
networks:
# Use the public network created to be shared between Traefik and
# any other service that needs to be publicly available with HTTPS
- traefik-public
volumes:
# Create a volume to store the certificates, even if the container is recreated
traefik-public-certificates:
networks:
# Use the previously created public network "traefik-public", shared with other
# services that need to be publicly available via this Traefik
traefik-public:
external: true
+133
View File
@@ -0,0 +1,133 @@
version: "3.3"
services:
db:
image: postgres:12
restart: always
volumes:
- app-db-data:/var/lib/postgresql/data/pgdata
env_file:
- .env
environment:
- PGDATA=/var/lib/postgresql/data/pgdata
- POSTGRES_PASSWORD=${POSTGRES_PASSWORD?Variable not set}
- POSTGRES_USER=${POSTGRES_USER?Variable not set}
- POSTGRES_DB=${POSTGRES_DB?Variable not set}
adminer:
image: adminer
restart: always
networks:
- traefik-public
- default
depends_on:
- db
environment:
- ADMINER_DESIGN=pepa-linha-dark
labels:
- traefik.enable=true
- traefik.docker.network=traefik-public
- traefik.constraint-label=traefik-public
- traefik.http.routers.${STACK_NAME?Variable not set}-adminer-http.rule=Host(`adminer.${DOMAIN?Variable not set}`)
- traefik.http.routers.${STACK_NAME?Variable not set}-adminer-http.entrypoints=http
- traefik.http.routers.${STACK_NAME?Variable not set}-adminer-http.middlewares=https-redirect
- traefik.http.routers.${STACK_NAME?Variable not set}-adminer-https.rule=Host(`adminer.${DOMAIN?Variable not set}`)
- traefik.http.routers.${STACK_NAME?Variable not set}-adminer-https.entrypoints=https
- traefik.http.routers.${STACK_NAME?Variable not set}-adminer-https.tls=true
- traefik.http.routers.${STACK_NAME?Variable not set}-adminer-https.tls.certresolver=le
- traefik.http.services.${STACK_NAME?Variable not set}-adminer.loadbalancer.server.port=8080
backend:
image: '${DOCKER_IMAGE_BACKEND?Variable not set}:${TAG-latest}'
restart: always
networks:
- traefik-public
- default
depends_on:
- db
env_file:
- .env
environment:
- DOMAIN=${DOMAIN}
- 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}
- USERS_OPEN_REGISTRATION=${USERS_OPEN_REGISTRATION}
- 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}
build:
context: ./backend
args:
INSTALL_DEV: ${INSTALL_DEV-false}
labels:
- traefik.enable=true
- traefik.docker.network=traefik-public
- traefik.constraint-label=traefik-public
- traefik.http.services.${STACK_NAME?Variable not set}-backend.loadbalancer.server.port=80
- 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.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.entrypoints=https
- traefik.http.routers.${STACK_NAME?Variable not set}-backend-https.tls=true
- traefik.http.routers.${STACK_NAME?Variable not set}-backend-https.tls.certresolver=le
- traefik.http.routers.${STACK_NAME?Variable not set}-backend-http.middlewares=https-redirect,${STACK_NAME?Variable not set}-www-redirect
- traefik.http.routers.${STACK_NAME?Variable not set}-backend-https.middlewares=${STACK_NAME?Variable not set}-www-redirect
frontend:
image: '${DOCKER_IMAGE_FRONTEND?Variable not set}:${TAG-latest}'
restart: always
networks:
- traefik-public
- default
build:
context: ./frontend
args:
- VITE_API_URL=https://${DOMAIN?Variable not set}
- NODE_ENV=production
labels:
- traefik.enable=true
- traefik.docker.network=traefik-public
- traefik.constraint-label=traefik-public
- traefik.http.services.${STACK_NAME?Variable not set}-frontend.loadbalancer.server.port=80
- traefik.http.routers.${STACK_NAME?Variable not set}-frontend-http.rule=Host(`${DOMAIN?Variable not set}`, `www.${DOMAIN?Variable not set}`)
- traefik.http.routers.${STACK_NAME?Variable not set}-frontend-http.entrypoints=http
- traefik.http.routers.${STACK_NAME?Variable not set}-frontend-https.rule=Host(`${DOMAIN?Variable not set}`, `www.${DOMAIN?Variable not set}`)
- traefik.http.routers.${STACK_NAME?Variable not set}-frontend-https.entrypoints=https
- traefik.http.routers.${STACK_NAME?Variable not set}-frontend-https.tls=true
- traefik.http.routers.${STACK_NAME?Variable not set}-frontend-https.tls.certresolver=le
# Handle domain with and without "www" to redirect to only one
# To disable www redirection remove the next line
- 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:
app-db-data:
networks:
traefik-public:
# Allow setting it to false for testing
external: true
@@ -1 +1,2 @@
node_modules node_modules
dist
+1
View File
@@ -0,0 +1 @@
VITE_API_URL=http://localhost
+18
View File
@@ -0,0 +1,18 @@
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 },
],
},
}
@@ -1,21 +1,25 @@
.DS_Store # Logs
node_modules logs
/dist *.log
# local env files
.env.local
.env.*.local
# Log files
npm-debug.log* npm-debug.log*
yarn-debug.log* yarn-debug.log*
yarn-error.log* yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
openapi.json
# Editor directories and files # Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea .idea
.vscode .DS_Store
*.suo *.suo
*.ntvs* *.ntvs*
*.njsproj *.njsproj
*.sln *.sln
*.sw* *.sw?
+1
View File
@@ -0,0 +1 @@
18.x.x
+1
View File
@@ -0,0 +1 @@
src/client/
+8
View File
@@ -0,0 +1,8 @@
{
"bracketSpacing": true,
"semi": false,
"singleQuote": true,
"trailingComma": "all",
"printWidth": 80,
"tabWidth": 2
}
@@ -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 tiangolo/node-frontend:10 as build-stage FROM node:20 as build-stage
WORKDIR /app WORKDIR /app
@@ -9,20 +9,15 @@ RUN npm install
COPY ./ /app/ COPY ./ /app/
ARG FRONTEND_ENV=production ARG VITE_API_URL=${VITE_API_URL}
ENV VUE_APP_ENV=${FRONTEND_ENV}
# Comment out the next line to disable tests
RUN npm run test:unit
RUN npm run build RUN npm run build
# Stage 1, based on Nginx, to have only the compiled app, ready for production with Nginx # Stage 1, based on Nginx, to have only the compiled app, ready for production with Nginx
FROM nginx:1.15 FROM nginx:1
COPY --from=build-stage /app/dist/ /usr/share/nginx/html COPY --from=build-stage /app/dist/ /usr/share/nginx/html
COPY --from=build-stage /nginx.conf /etc/nginx/conf.d/default.conf COPY ./nginx.conf /etc/nginx/conf.d/default.conf
COPY ./nginx-backend-not-found.conf /etc/nginx/extra-conf.d/backend-not-found.conf COPY ./nginx-backend-not-found.conf /etc/nginx/extra-conf.d/backend-not-found.conf
+117
View File
@@ -0,0 +1,117 @@
# FastAPI Project - Frontend
The frontend is built with [Vite](https://vitejs.dev/), [React](https://reactjs.org/), [TypeScript](https://www.typescriptlang.org/), [TanStack Query](https://tanstack.com/query), [TanStack Router](https://tanstack.com/router) and [Chakra UI](https://chakra-ui.com/).
## Frontend development
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).
* After installing either nvm or fnm, proceed to the `frontend` directory:
```bash
cd frontend
```
* If the Node.js version specified in the `.nvmrc` file isn't installed on your system, you can install it using the appropriate command:
```bash
# If using fnm
fnm install
# If using nvm
nvm install
```
* Once the installation is complete, switch to the installed version:
```bash
# If using fnm
fnm use
# If using nvm
nvm use
```
* Within the `frontend` directory, install the necessary NPM packages:
```bash
npm install
```
* And start the live server with the following `npm` script:
```bash
npm run dev
```
* Then open your browser at http://localhost:5173/.
Notice that this live server is not running inside Docker, it's for local development, and that is the recommended workflow. Once you are happy with your frontend, you can build the frontend Docker image and start it, to test it in a production-like environment. But building the image at every change will not be as productive as running the local development server with live reload.
Check the file `package.json` to see other available options.
### Removing the frontend
If you are developing an API-only app and want to remove the frontend, you can do it easily:
* Remove the `./frontend` directory.
* In the `docker-compose.yml` file, remove the whole service / section `frontend`.
* In the `docker-compose.override.yml` file, remove the whole service / section `frontend`.
Done, you have a frontend-less (api-only) app. 🤓
---
If you want, you can also remove the `FRONTEND` environment variables from:
* `.env`
* `./scripts/*.sh`
But it would be only to clean them up, leaving them won't really have any effect either way.
## Generate Client
* Start the Docker Compose stack.
* Download the OpenAPI JSON file from `http://localhost/api/v1/openapi.json` and copy it to a new file `openapi.json` at the root of the `frontend` directory.
* To 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:
```bash
npm run generate-client
```
* Commit the changes.
Notice that everytime the backend changes (changing the OpenAPI schema), you should follow these steps again to update the frontend client.
## Using a Remote API
If you want to use a remote API, you can set the environment variable `VITE_API_URL` to the URL of the remote API. For example, you can set it in the `frontend/.env` file:
```env
VITE_API_URL=https://my-remote-api.example.com
```
Then, when you run the frontend, it will use that URL as the base URL for the API.
## Code Structure
The frontend code is structured as follows:
* `frontend/src` - The main frontend code.
* `frontend/src/assets` - Static assets.
* `frontend/src/client` - The generated OpenAPI client.
* `frontend/src/components` - The different components of the frontend.
* `frontend/src/hooks` - Custom hooks.
* `frontend/src/routes` - The different routes of the frontend which include the pages.
* `theme.tsx` - The Chakra UI custom theme.
+14
View File
@@ -0,0 +1,14 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Full Stack FastAPI Project</title>
<link rel="icon" type="image/x-icon" href="./src/assets/images/favicon.png" />
</head>
<body>
<div id="root"></div>
<script type="module" src="./src/main.tsx"></script>
</body>
</html>
+29
View File
@@ -0,0 +1,29 @@
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;
});
});

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