Compare commits

..

229 Commits

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-03-17 17:40:12 +01:00
github-actions c2220b8e68 📝 Update release notes 2024-03-17 16:29:03 +00:00
Alejandra 94a2037f8a 🎨 Format with Biome (#1097) 2024-03-17 16:28:45 +00:00
github-actions d4ee4db2f0 📝 Update release notes 2024-03-17 16:23:56 +00:00
Alejandra 4fbbdf4e94 🔥 Remove ESLint and Prettier from pre-commit config (#1096) 2024-03-17 16:23:36 +00:00
github-actions 6e7b8fd1df 📝 Update release notes 2024-03-17 16:13:41 +00:00
Alejandra 7856fd811b 🎨 Update quote style in biome formatter (#1095) 2024-03-17 16:13:25 +00:00
github-actions 477c5abf14 📝 Update release notes 2024-03-17 16:06:09 +00:00
Santiago Gandolfo 43435d50dd ♻️ Replace ESLint and Prettier with Biome to format and lint frontend (#719)
Co-authored-by: User <alejsdev@gmail.com>
Co-authored-by: Alejandra <90076947+alejsdev@users.noreply.github.com>
2024-03-17 16:05:47 +00:00
github-actions 75fc26192c 📝 Update release notes 2024-03-17 13:43:50 +00:00
Sebastián Ramírez 6aa2296dea 🐛 Fix 403 when the frontend has a directory without an index.html (#1094) 2024-03-17 13:43:31 +00:00
github-actions fa7d42eddd 📝 Update release notes 2024-03-16 13:02:54 +00:00
Δ̷̨̧̡̭̺̙̞͖̖͕̰̥̙̯͙̞̯̗̔͌͐̿͊̌́̄̑̿̓̉̈̀͘͠λ̶͔͓̘̘̳͇̻̍̏͌̅̓̓͂̍̾̔͜λ̶̛̯̖̯̲̱͎̙͎̎̐͆͂̽̓̇́͌́̀̏̎̅͋̏̊͘λ̶̨̨̰̟̯̫̲̲̫̯̭̤̳̼̫͉̹̞́̐̒Δ̷̡̛̥̖͇͚͍͍̄̏̂͛̅̌͗̂̽̅̀͆̿̔̚͜ a32cb74edd 🔥 Delete leftover celery file (#727) 2024-03-16 14:02:34 +01:00
github-actions 18ea605849 📝 Update release notes 2024-03-15 00:05:45 +00:00
Alejandra a2a1900105 🎨 Replace buttons styling for variants for consistency (#722) 2024-03-15 01:05:28 +01:00
github-actions 3fbdf21a05 📝 Update release notes 2024-03-14 11:27:23 +00:00
Alejandra f5764acd56 🛠️ Improve modify-openapi-operationids.js (#720) 2024-03-14 12:27:03 +01:00
github-actions 557b44f0e8 📝 Update release notes 2024-03-13 23:57:40 +00:00
Esteban Maya 85b7d6bc63 ♻️ Replace pytest-mock with unittest.mock and remove pytest-cov (#717) 2024-03-14 00:57:19 +01:00
github-actions a7deb9b39c 📝 Update release notes 2024-03-13 22:09:39 +00:00
Alejandra 85c1b06400 📝 Update README.md (#716) 2024-03-13 23:09:21 +01:00
github-actions 4fda65bec3 📝 Update release notes 2024-03-13 21:59:47 +00:00
Alejandra 21232c0f9f 🛠️ Minor changes in frontend (#715) 2024-03-13 21:59:28 +00:00
github-actions 10ef99cb68 📝 Update release notes 2024-03-13 20:44:12 +00:00
Alejandra b08aec7d98 ⚙️ Update pre-commit config with Prettier and ESLint (#714) 2024-03-13 21:43:54 +01:00
github-actions 2e96f05138 📝 Update release notes 2024-03-13 18:07:58 +00:00
Dudi Levy bbddf944e2 ♻ Update Docker image to prevent errors in M1 Macs (#710) 2024-03-13 19:07:40 +01:00
github-actions 80e6c81977 📝 Update release notes 2024-03-13 18:06:48 +00:00
Salomon Popp e13d120fd1 ✏ Fix typo in variable names in backend/app/api/routes/items.py and backend/app/api/routes/users.py (#711)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2024-03-13 18:06:22 +00:00
github-actions afc55bdf91 📝 Update release notes 2024-03-13 17:55:54 +00:00
emmanuel 24662000e7 ✏ Update header titles for consistency (#708) 2024-03-13 18:55:33 +01:00
github-actions 63e54cb9a5 📝 Update release notes 2024-03-13 11:55:17 +00:00
Alejandra ba042eca1f 📝 Update README.md, dark mode screenshot position (#706) 2024-03-13 12:54:57 +01:00
156 changed files with 6009 additions and 6457 deletions
-1
View File
@@ -13,7 +13,6 @@ BACKEND_CORS_ORIGINS="http://localhost,http://localhost:5173,https://localhost,h
SECRET_KEY=changethis SECRET_KEY=changethis
FIRST_SUPERUSER=admin@example.com FIRST_SUPERUSER=admin@example.com
FIRST_SUPERUSER_PASSWORD=changethis FIRST_SUPERUSER_PASSWORD=changethis
USERS_OPEN_REGISTRATION=False
# Emails # Emails
SMTP_HOST= SMTP_HOST=
+118
View File
@@ -0,0 +1,118 @@
labels: [question]
body:
- type: markdown
attributes:
value: |
Thanks for your interest in this project! 🚀
Please follow these instructions, fill every question, and do every step. 🙏
I'm asking this because answering questions and solving problems in GitHub is what consumes most of the time.
I end up not being able to add new features, fix bugs, review pull requests, etc. as fast as I wish because I have to spend too much time handling questions.
All that, on top of all the incredible help provided by a bunch of community members, that give a lot of their time to come here and help others.
That's a lot of work, but if more users came to help others like them just a little bit more, it would be much less effort for them (and you and me 😅).
By asking questions in a structured way (following this) it will be much easier to help you.
And there's a high chance that you will find the solution along the way and you won't even have to submit it and wait for an answer. 😎
As there are too many questions, I'll have to discard and close the incomplete ones. That will allow me (and others) to focus on helping people like you that follow the whole process and help us help you. 🤓
- type: checkboxes
id: checks
attributes:
label: First Check
description: Please confirm and check all the following options.
options:
- label: I added a very descriptive title here.
required: true
- label: I used the GitHub search to find a similar question and didn't find it.
required: true
- label: I searched in the documentation/README.
required: true
- label: I already searched in Google "How to do X" and didn't find any information.
required: true
- label: I already read and followed all the tutorial in the docs/README and didn't find an answer.
required: true
- type: checkboxes
id: help
attributes:
label: Commit to Help
description: |
After submitting this, I commit to one of:
* Read open questions until I find 2 where I can help someone and add a comment to help there.
* I already hit the "watch" button in this repository to receive notifications and I commit to help at least 2 people that ask questions in the future.
options:
- label: I commit to help with one of those options 👆
required: true
- type: textarea
id: example
attributes:
label: Example Code
description: |
Please add a self-contained, [minimal, reproducible, example](https://stackoverflow.com/help/minimal-reproducible-example) with your use case.
If I (or someone) can copy it, run it, and see it right away, there's a much higher chance I (or someone) will be able to help you.
placeholder: |
Write your example code here.
render: Text
validations:
required: true
- type: textarea
id: description
attributes:
label: Description
description: |
What is the problem, question, or error?
Write a short description telling me what you are doing, what you expect to happen, and what is currently happening.
placeholder: |
* Open the browser and call the endpoint `/`.
* It returns a JSON with `{"message": "Hello World"}`.
* But I expected it to return `{"message": "Hello Morty"}`.
validations:
required: true
- type: dropdown
id: os
attributes:
label: Operating System
description: What operating system are you on?
multiple: true
options:
- Linux
- Windows
- macOS
- Other
validations:
required: true
- type: textarea
id: os-details
attributes:
label: Operating System Details
description: You can add more details about your operating system here, in particular if you chose "Other".
validations:
required: true
- type: input
id: python-version
attributes:
label: Python Version
description: |
What Python version are you using?
You can find the Python version with:
```bash
python --version
```
validations:
required: true
- type: textarea
id: context
attributes:
label: Additional Context
description: Add any additional context information or screenshots you think are useful.
+10
View File
@@ -0,0 +1,10 @@
blank_issues_enabled: false
contact_links:
- name: Security Contact
about: Please report security vulnerabilities to security@tiangolo.com
- name: Question or Problem
about: Ask a question or ask about a problem in GitHub Discussions.
url: https://github.com/fastapi/full-stack-fastapi-template/discussions/categories/questions
- name: Feature Request
about: To suggest an idea or ask about a feature, please start with a question saying what you would like to achieve. There might be a way to do it already.
url: https://github.com/fastapi/full-stack-fastapi-template/discussions/categories/questions
+22
View File
@@ -0,0 +1,22 @@
name: Privileged
description: You are @tiangolo or he asked you directly to create an issue here. If not, check the other options. 👇
body:
- type: markdown
attributes:
value: |
Thanks for your interest in this project! 🚀
If you are not @tiangolo or he didn't ask you directly to create an issue here, please start the conversation in a [Question in GitHub Discussions](https://github.com/tiangolo/full-stack-fastapi-template/discussions/categories/questions) instead.
- type: checkboxes
id: privileged
attributes:
label: Privileged issue
description: Confirm that you are allowed to create an issue here.
options:
- label: I'm @tiangolo or he asked me directly to create an issue here.
required: true
- type: textarea
id: content
attributes:
label: Issue Content
description: Add the content of the issue here.
+5 -2
View File
@@ -7,12 +7,15 @@ on:
jobs: jobs:
deploy: deploy:
# Do not deploy in the main repository, only in user projects
if: github.repository_owner != 'fastapi'
runs-on: runs-on:
- self-hosted - self-hosted
- production - production
env: env:
ENVIRONMENT: production ENVIRONMENT: production
DOMAIN: ${{ secrets.DOMAIN_PRODUCTION }} DOMAIN: ${{ secrets.DOMAIN_PRODUCTION }}
STACK_NAME: ${{ secrets.STACK_NAME_PRODUCTION }}
SECRET_KEY: ${{ secrets.SECRET_KEY }} SECRET_KEY: ${{ secrets.SECRET_KEY }}
FIRST_SUPERUSER: ${{ secrets.FIRST_SUPERUSER }} FIRST_SUPERUSER: ${{ secrets.FIRST_SUPERUSER }}
FIRST_SUPERUSER_PASSWORD: ${{ secrets.FIRST_SUPERUSER_PASSWORD }} FIRST_SUPERUSER_PASSWORD: ${{ secrets.FIRST_SUPERUSER_PASSWORD }}
@@ -25,5 +28,5 @@ jobs:
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v4
- run: docker compose -f docker-compose.yml build - run: docker compose -f docker-compose.yml --project-name ${{ secrets.STACK_NAME_PRODUCTION }} build
- run: docker compose -f docker-compose.yml up -d - run: docker compose -f docker-compose.yml --project-name ${{ secrets.STACK_NAME_PRODUCTION }} up -d
+5 -2
View File
@@ -7,12 +7,15 @@ on:
jobs: jobs:
deploy: deploy:
# Do not deploy in the main repository, only in user projects
if: github.repository_owner != 'fastapi'
runs-on: runs-on:
- self-hosted - self-hosted
- staging - staging
env: env:
ENVIRONMENT: staging ENVIRONMENT: staging
DOMAIN: ${{ secrets.DOMAIN_STAGING }} DOMAIN: ${{ secrets.DOMAIN_STAGING }}
STACK_NAME: ${{ secrets.STACK_NAME_STAGING }}
SECRET_KEY: ${{ secrets.SECRET_KEY }} SECRET_KEY: ${{ secrets.SECRET_KEY }}
FIRST_SUPERUSER: ${{ secrets.FIRST_SUPERUSER }} FIRST_SUPERUSER: ${{ secrets.FIRST_SUPERUSER }}
FIRST_SUPERUSER_PASSWORD: ${{ secrets.FIRST_SUPERUSER_PASSWORD }} FIRST_SUPERUSER_PASSWORD: ${{ secrets.FIRST_SUPERUSER_PASSWORD }}
@@ -25,5 +28,5 @@ jobs:
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v4
- run: docker compose -f docker-compose.yml build - run: docker compose -f docker-compose.yml --project-name ${{ secrets.STACK_NAME_STAGING }} build
- run: docker compose -f docker-compose.yml up -d - run: docker compose -f docker-compose.yml --project-name ${{ secrets.STACK_NAME_STAGING }} up -d
+3
View File
@@ -11,6 +11,9 @@ on:
types: types:
- labeled - labeled
permissions:
issues: write
jobs: jobs:
issue-manager: issue-manager:
runs-on: ubuntu-latest runs-on: ubuntu-latest
+3 -1
View File
@@ -19,6 +19,8 @@ on:
jobs: jobs:
latest-changes: latest-changes:
runs-on: ubuntu-latest runs-on: ubuntu-latest
permissions:
pull-requests: read
steps: steps:
- name: Dump GitHub context - name: Dump GitHub context
env: env:
@@ -27,7 +29,7 @@ jobs:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
with: with:
# To allow latest-changes to commit to the main branch # To allow latest-changes to commit to the main branch
token: ${{ secrets.FULL_STACK_FASTAPI_POSTGRESQL_LATEST_CHANGES }} token: ${{ secrets.LATEST_CHANGES }}
- uses: docker://tiangolo/latest-changes:0.3.0 - uses: docker://tiangolo/latest-changes:0.3.0
# - uses: tiangolo/latest-changes@main # - uses: tiangolo/latest-changes@main
with: with:
+66
View File
@@ -0,0 +1,66 @@
name: Playwright Tests
on:
push:
branches:
- master
pull_request:
types:
- opened
- synchronize
workflow_dispatch:
inputs:
debug_enabled:
description: 'Run the build with tmate debugging enabled (https://github.com/marketplace/actions/debugging-with-tmate)'
required: false
default: 'false'
jobs:
test:
timeout-minutes: 60
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: lts/*
- uses: actions/setup-python@v5
with:
python-version: '3.10'
- name: Setup tmate session
uses: mxschmitt/action-tmate@v3
if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.debug_enabled == 'true' }}
with:
limit-access-to-actor: true
- name: Install dependencies
run: npm ci
working-directory: frontend
- name: Install Playwright Browsers
run: npx playwright install --with-deps
working-directory: frontend
- run: docker compose build
- run: docker compose down -v --remove-orphans
- run: docker compose up -d
- name: Run Playwright tests
run: npx playwright test
working-directory: frontend
- run: docker compose down -v --remove-orphans
- uses: actions/upload-artifact@v4
if: always()
with:
name: playwright-report
path: frontend/playwright-report/
retention-days: 30
# https://github.com/marketplace/actions/alls-green#why
e2e-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) }}
+9 -7
View File
@@ -5,13 +5,13 @@ on:
workflows: [Test] workflows: [Test]
types: [completed] types: [completed]
permissions:
statuses: write
jobs: jobs:
smokeshow: smokeshow:
if: ${{ github.event.workflow_run.conclusion == 'success' }} if: ${{ github.event.workflow_run.conclusion == 'success' }}
runs-on: ubuntu-latest runs-on: ubuntu-latest
permissions:
actions: read
statuses: write
steps: steps:
- uses: actions/setup-python@v5 - uses: actions/setup-python@v5
@@ -20,12 +20,14 @@ jobs:
- run: pip install smokeshow - run: pip install smokeshow
- uses: dawidd6/action-download-artifact@v3.1.2 - uses: actions/download-artifact@v4
with: with:
workflow: test.yml name: coverage-html
commit: ${{ github.event.workflow_run.head_sha }} path: backend/htmlcov
github-token: ${{ secrets.GITHUB_TOKEN }}
run-id: ${{ github.event.workflow_run.id }}
- run: smokeshow upload coverage-html - run: smokeshow upload backend/htmlcov
env: env:
SMOKESHOW_GITHUB_STATUS_DESCRIPTION: Coverage {coverage-percentage} SMOKESHOW_GITHUB_STATUS_DESCRIPTION: Coverage {coverage-percentage}
SMOKESHOW_GITHUB_COVERAGE_THRESHOLD: 90 SMOKESHOW_GITHUB_COVERAGE_THRESHOLD: 90
+5
View File
@@ -1 +1,6 @@
.vscode .vscode
node_modules/
/test-results/
/playwright-report/
/blob-report/
/playwright/.cache/
+3
View File
@@ -10,7 +10,9 @@ repos:
args: args:
- --unsafe - --unsafe
- id: end-of-file-fixer - id: end-of-file-fixer
exclude: ^frontend/src/client/.*
- id: trailing-whitespace - id: trailing-whitespace
exclude: ^frontend/src/client/.*
- repo: https://github.com/charliermarsh/ruff-pre-commit - repo: https://github.com/charliermarsh/ruff-pre-commit
rev: v0.2.2 rev: v0.2.2
hooks: hooks:
@@ -18,6 +20,7 @@ repos:
args: args:
- --fix - --fix
- id: ruff-format - id: ruff-format
ci: ci:
autofix_commit_msg: 🎨 [pre-commit.ci] Auto format from pre-commit.com hooks autofix_commit_msg: 🎨 [pre-commit.ci] Auto format from pre-commit.com hooks
autoupdate_commit_msg: ⬆ [pre-commit.ci] pre-commit autoupdate autoupdate_commit_msg: ⬆ [pre-commit.ci] pre-commit autoupdate
+94 -23
View File
@@ -1,11 +1,7 @@
# Full Stack FastAPI Template # Full Stack FastAPI Template
<a href="https://github.com/tiangolo/full-stack-fastapi-template/actions?query=workflow%3ATest" target="_blank"><img src="https://github.com/tiangolo/full-stack-fastapi-template/workflows/Test/badge.svg" alt="Test"></a> <a href="https://github.com/fastapi/full-stack-fastapi-template/actions?query=workflow%3ATest" target="_blank"><img src="https://github.com/fastapi/full-stack-fastapi-template/workflows/Test/badge.svg" alt="Test"></a>
<a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/tiangolo/full-stack-fastapi-template" target="_blank"><img src="https://coverage-badge.samuelcolvin.workers.dev/tiangolo/full-stack-fastapi-template.svg" alt="Coverage"></a> <a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/fastapi/full-stack-fastapi-template" target="_blank"><img src="https://coverage-badge.samuelcolvin.workers.dev/fastapi/full-stack-fastapi-template.svg" alt="Coverage"></a>
### Dashboard - Dark Mode
[![API docs](img/dashboard-dark.png)](https://github.com/tiangolo/full-stack-fastapi-postgresql)
## Technology Stack and Features ## Technology Stack and Features
@@ -17,10 +13,11 @@
- 💃 Using TypeScript, hooks, Vite, and other parts of a modern frontend stack. - 💃 Using TypeScript, hooks, Vite, and other parts of a modern frontend stack.
- 🎨 [Chakra UI](https://chakra-ui.com) for the frontend components. - 🎨 [Chakra UI](https://chakra-ui.com) for the frontend components.
- 🤖 An automatically generated frontend client. - 🤖 An automatically generated frontend client.
- 🧪 [Playwright](https://playwright.dev) for End-to-End testing.
- 🦇 Dark mode support. - 🦇 Dark mode support.
- 🐋 [Docker Compose](https://www.docker.com) for development and production. - 🐋 [Docker Compose](https://www.docker.com) for development and production.
- 🔒 Secure password hashing by default. - 🔒 Secure password hashing by default.
- 🔑 JWT token authentication. - 🔑 JWT (JSON Web Token) authentication.
- 📫 Email based password recovery. - 📫 Email based password recovery.
- ✅ Tests with [Pytest](https://pytest.org). - ✅ Tests with [Pytest](https://pytest.org).
- 📞 [Traefik](https://traefik.io) as a reverse proxy / load balancer. - 📞 [Traefik](https://traefik.io) as a reverse proxy / load balancer.
@@ -29,36 +26,106 @@
### Dashboard Login ### Dashboard Login
[![API docs](img/login.png)](https://github.com/tiangolo/full-stack-fastapi-template) [![API docs](img/login.png)](https://github.com/fastapi/full-stack-fastapi-template)
### Dashboard - Admin ### Dashboard - Admin
[![API docs](img/dashboard.png)](https://github.com/tiangolo/full-stack-fastapi-template) [![API docs](img/dashboard.png)](https://github.com/fastapi/full-stack-fastapi-template)
### Dashboard - Create User ### Dashboard - Create User
[![API docs](img/dashboard-create.png)](https://github.com/tiangolo/full-stack-fastapi-template) [![API docs](img/dashboard-create.png)](https://github.com/fastapi/full-stack-fastapi-template)
### Dashboard - Items ### Dashboard - Items
[![API docs](img/dashboard-items.png)](https://github.com/tiangolo/full-stack-fastapi-template) [![API docs](img/dashboard-items.png)](https://github.com/fastapi/full-stack-fastapi-template)
### Dashboard - User Settings ### Dashboard - User Settings
[![API docs](img/dashboard-user-settings.png)](https://github.com/tiangolo/full-stack-fastapi-template) [![API docs](img/dashboard-user-settings.png)](https://github.com/fastapi/full-stack-fastapi-template)
### Interactive API documentation ### Dashboard - Dark Mode
[![API docs](img/docs.png)](https://github.com/tiangolo/full-stack-fastapi-template) [![API docs](img/dashboard-dark.png)](https://github.com/fastapi/full-stack-fastapi-template)
### Interactive API Documentation
[![API docs](img/docs.png)](https://github.com/fastapi/full-stack-fastapi-template)
## How to use it ## How To Use It
You can **just fork or clone** this repository and use it as is. You can **just fork or clone** this repository and use it as is.
✨ It just works. ✨ ✨ It just works. ✨
### How to Use a Private Repository
If you want to have a private repository, GitHub won't allow you to simply fork it as it doesn't allow changing the visibility of forks.
But you can do the following:
- Create a new GitHub repo, for example `my-full-stack`.
- Clone this repository manually, set the name with the name of the project you want to use, for example `my-full-stack`:
```bash
git clone git@github.com:fastapi/full-stack-fastapi-template.git my-full-stack
```
- Enter into the new directory:
```bash
cd my-full-stack
```
- Set the new origin to your new repository, copy it from the GitHub interface, for example:
```bash
git remote set-url origin git@github.com:octocat/my-full-stack.git
```
- Add this repo as another "remote" to allow you to get updates later:
```bash
git remote add upstream git@github.com:fastapi/full-stack-fastapi-template.git
```
- Push the code to your new repository:
```bash
git push -u origin master
```
### Update From the Original Template
After cloning the repository, and after doing changes, you might want to get the latest changes from this original template.
- Make sure you added the original repository as a remote, you can check it with:
```bash
git remote -v
origin git@github.com:octocat/my-full-stack.git (fetch)
origin git@github.com:octocat/my-full-stack.git (push)
upstream git@github.com:fastapi/full-stack-fastapi-template.git (fetch)
upstream git@github.com:fastapi/full-stack-fastapi-template.git (push)
```
- Pull the latest changes without merging:
```bash
git pull --no-commit upstream master
```
This will download the latest changes from this template without committing them, that way you can check everything is right before committing.
- If there are conflicts, solve them in your editor.
- Once you are done, commit the changes:
```bash
git merge --continue
```
### Configure ### Configure
You can then update configs in the `.env` files to customize your configurations. You can then update configs in the `.env` files to customize your configurations.
@@ -69,7 +136,11 @@ Before deploying it, make sure you change at least the values for:
- `FIRST_SUPERUSER_PASSWORD` - `FIRST_SUPERUSER_PASSWORD`
- `POSTGRES_PASSWORD` - `POSTGRES_PASSWORD`
### Generate secret keys You can (and should) pass these as environment variables from secrets.
Read the [deployment.md](./deployment.md) docs for more details.
### Generate Secret Keys
Some environment variables in the `.env` file have a default value of `changethis`. Some environment variables in the `.env` file have a default value of `changethis`.
@@ -81,7 +152,7 @@ python -c "import secrets; print(secrets.token_urlsafe(32))"
Copy the content and use that as password / secret key. And run that again to generate another secure key. Copy the content and use that as password / secret key. And run that again to generate another secure key.
## How to use it - alternative with Copier ## How To Use It - Alternative With Copier
This repository also supports generating a new project using [Copier](https://copier.readthedocs.io). This repository also supports generating a new project using [Copier](https://copier.readthedocs.io).
@@ -103,25 +174,25 @@ pipx install copier
**Note**: If you have `pipx`, installing copier is optional, you could run it directly. **Note**: If you have `pipx`, installing copier is optional, you could run it directly.
### Generate a Project with Copier ### Generate a Project With Copier
Decide a name for your new project's directory, you will use it below. For example, `my-awesome-project`. Decide a name for your new project's directory, you will use it below. For example, `my-awesome-project`.
Go to the directory that will be the parent of your project, and run the command with your project's name: Go to the directory that will be the parent of your project, and run the command with your project's name:
```bash ```bash
copier copy https://github.com/tiangolo/full-stack-fastapi-template my-awesome-project --trust copier copy https://github.com/fastapi/full-stack-fastapi-template my-awesome-project --trust
``` ```
If you have `pipx` and you didn't install `copier`, you can run it directly: If you have `pipx` and you didn't install `copier`, you can run it directly:
```bash ```bash
pipx run copier copy https://github.com/tiangolo/full-stack-fastapi-template my-awesome-project --trust pipx run copier copy https://github.com/fastapi/full-stack-fastapi-template my-awesome-project --trust
``` ```
**Note** the `--trust` option is necessary to be able to execute a [post-creation script](https://github.com/tiangolo/full-stack-fastapi-template/blob/master/.copier/update_dotenv.py) that updates your `.env` files. **Note** the `--trust` option is necessary to be able to execute a [post-creation script](https://github.com/fastapi/full-stack-fastapi-template/blob/master/.copier/update_dotenv.py) that updates your `.env` files.
### Input variables ### Input Variables
Copier will ask you for some data, you might want to have at hand before generating the project. Copier will ask you for some data, you might want to have at hand before generating the project.
@@ -130,7 +201,7 @@ But don't worry, you can just update any of that in the `.env` files afterwards.
The input variables, with their default values (some auto generated) are: The input variables, with their default values (some auto generated) are:
- `project_name`: (default: `"FastAPI Project"`) The name of the project, shown to API users (in .env). - `project_name`: (default: `"FastAPI Project"`) The name of the project, shown to API users (in .env).
- `stack_name`: (default: `"fastapi-project"`) The name of the stack used for Docker Compose labels (no spaces) (in .env). - `stack_name`: (default: `"fastapi-project"`) The name of the stack used for Docker Compose labels and project name (no spaces, no periods) (in .env).
- `secret_key`: (default: `"changethis"`) The secret key for the project, used for security, stored in .env, you can generate one with the method above. - `secret_key`: (default: `"changethis"`) The secret key for the project, used for security, stored in .env, you can generate one with the method above.
- `first_superuser`: (default: `"admin@example.com"`) The email of the first superuser (in .env). - `first_superuser`: (default: `"admin@example.com"`) The email of the first superuser (in .env).
- `first_superuser_password`: (default: `"changethis"`) The password of the first superuser (in .env). - `first_superuser_password`: (default: `"changethis"`) The password of the first superuser (in .env).
+29
View File
@@ -0,0 +1,29 @@
# Security Policy
Security is very important for this project and its community. 🔒
Learn more about it below. 👇
## Versions
The latest version or release is supported.
You are encouraged to write tests for your application and update your versions frequently after ensuring that your tests are passing. This way you will benefit from the latest features, bug fixes, and **security fixes**.
## Reporting a Vulnerability
If you think you found a vulnerability, and even if you are not sure about it, please report it right away by sending an email to: security@tiangolo.com. Please try to be as explicit as possible, describing all the steps and example code to reproduce the security issue.
I (the author, [@tiangolo](https://twitter.com/tiangolo)) will review it thoroughly and get back to you.
## Public Discussions
Please restrain from publicly discussing a potential security vulnerability. 🙊
It's better to discuss privately and try to find a solution first, to limit the potential impact as much as possible.
---
Thanks for your help!
The community and I thank you for that. 🙇
+1 -1
View File
@@ -183,7 +183,7 @@ $ alembic revision --autogenerate -m "Add column last_name to User model"
$ alembic upgrade head $ alembic upgrade head
``` ```
If you don't want to use migrations at all, uncomment the lines in the file at `./backend/app/db/init_db.py` that end in: If you don't want to use migrations at all, uncomment the lines in the file at `./backend/app/core/db.py` that end in:
```python ```python
SQLModel.metadata.create_all(engine) SQLModel.metadata.create_all(engine)
+2 -6
View File
@@ -19,6 +19,7 @@ fileConfig(config.config_file_name)
# target_metadata = None # target_metadata = None
from app.models import SQLModel # noqa from app.models import SQLModel # noqa
from app.core.config import settings # noqa
target_metadata = SQLModel.metadata target_metadata = SQLModel.metadata
@@ -29,12 +30,7 @@ target_metadata = SQLModel.metadata
def get_url(): def get_url():
user = os.getenv("POSTGRES_USER", "postgres") return str(settings.SQLALCHEMY_DATABASE_URI)
password = os.getenv("POSTGRES_PASSWORD", "")
server = os.getenv("POSTGRES_SERVER", "db")
port = os.getenv("POSTGRES_PORT", "5432")
db = os.getenv("POSTGRES_DB", "app")
return f"postgresql+psycopg://{user}:{password}@{server}:{port}/{db}"
def run_migrations_offline(): def run_migrations_offline():
@@ -0,0 +1,37 @@
"""Add cascade delete relationships
Revision ID: 1a31ce608336
Revises: d98dd8ec85a3
Create Date: 2024-07-31 22:24:34.447891
"""
from alembic import op
import sqlalchemy as sa
import sqlmodel.sql.sqltypes
# revision identifiers, used by Alembic.
revision = '1a31ce608336'
down_revision = 'd98dd8ec85a3'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.alter_column('item', 'owner_id',
existing_type=sa.UUID(),
nullable=False)
op.drop_constraint('item_owner_id_fkey', 'item', type_='foreignkey')
op.create_foreign_key(None, 'item', 'user', ['owner_id'], ['id'], ondelete='CASCADE')
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_constraint(None, 'item', type_='foreignkey')
op.create_foreign_key('item_owner_id_fkey', 'item', 'user', ['owner_id'], ['id'])
op.alter_column('item', 'owner_id',
existing_type=sa.UUID(),
nullable=True)
# ### end Alembic commands ###
@@ -0,0 +1,69 @@
"""Add max length for string(varchar) fields in User and Items models
Revision ID: 9c0a54914c78
Revises: e2412789c190
Create Date: 2024-06-17 14:42:44.639457
"""
from alembic import op
import sqlalchemy as sa
import sqlmodel.sql.sqltypes
# revision identifiers, used by Alembic.
revision = '9c0a54914c78'
down_revision = 'e2412789c190'
branch_labels = None
depends_on = None
def upgrade():
# Adjust the length of the email field in the User table
op.alter_column('user', 'email',
existing_type=sa.String(),
type_=sa.String(length=255),
existing_nullable=False)
# Adjust the length of the full_name field in the User table
op.alter_column('user', 'full_name',
existing_type=sa.String(),
type_=sa.String(length=255),
existing_nullable=True)
# Adjust the length of the title field in the Item table
op.alter_column('item', 'title',
existing_type=sa.String(),
type_=sa.String(length=255),
existing_nullable=False)
# Adjust the length of the description field in the Item table
op.alter_column('item', 'description',
existing_type=sa.String(),
type_=sa.String(length=255),
existing_nullable=True)
def downgrade():
# Revert the length of the email field in the User table
op.alter_column('user', 'email',
existing_type=sa.String(length=255),
type_=sa.String(),
existing_nullable=False)
# Revert the length of the full_name field in the User table
op.alter_column('user', 'full_name',
existing_type=sa.String(length=255),
type_=sa.String(),
existing_nullable=True)
# Revert the length of the title field in the Item table
op.alter_column('item', 'title',
existing_type=sa.String(length=255),
type_=sa.String(),
existing_nullable=False)
# Revert the length of the description field in the Item table
op.alter_column('item', 'description',
existing_type=sa.String(length=255),
type_=sa.String(),
existing_nullable=True)
@@ -0,0 +1,90 @@
"""Edit replace id integers in all models to use UUID instead
Revision ID: d98dd8ec85a3
Revises: 9c0a54914c78
Create Date: 2024-07-19 04:08:04.000976
"""
from alembic import op
import sqlalchemy as sa
import sqlmodel.sql.sqltypes
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = 'd98dd8ec85a3'
down_revision = '9c0a54914c78'
branch_labels = None
depends_on = None
def upgrade():
# Ensure uuid-ossp extension is available
op.execute('CREATE EXTENSION IF NOT EXISTS "uuid-ossp"')
# Create a new UUID column with a default UUID value
op.add_column('user', sa.Column('new_id', postgresql.UUID(as_uuid=True), default=sa.text('uuid_generate_v4()')))
op.add_column('item', sa.Column('new_id', postgresql.UUID(as_uuid=True), default=sa.text('uuid_generate_v4()')))
op.add_column('item', sa.Column('new_owner_id', postgresql.UUID(as_uuid=True), nullable=True))
# Populate the new columns with UUIDs
op.execute('UPDATE "user" SET new_id = uuid_generate_v4()')
op.execute('UPDATE item SET new_id = uuid_generate_v4()')
op.execute('UPDATE item SET new_owner_id = (SELECT new_id FROM "user" WHERE "user".id = item.owner_id)')
# Set the new_id as not nullable
op.alter_column('user', 'new_id', nullable=False)
op.alter_column('item', 'new_id', nullable=False)
# Drop old columns and rename new columns
op.drop_constraint('item_owner_id_fkey', 'item', type_='foreignkey')
op.drop_column('item', 'owner_id')
op.alter_column('item', 'new_owner_id', new_column_name='owner_id')
op.drop_column('user', 'id')
op.alter_column('user', 'new_id', new_column_name='id')
op.drop_column('item', 'id')
op.alter_column('item', 'new_id', new_column_name='id')
# Create primary key constraint
op.create_primary_key('user_pkey', 'user', ['id'])
op.create_primary_key('item_pkey', 'item', ['id'])
# Recreate foreign key constraint
op.create_foreign_key('item_owner_id_fkey', 'item', 'user', ['owner_id'], ['id'])
def downgrade():
# Reverse the upgrade process
op.add_column('user', sa.Column('old_id', sa.Integer, autoincrement=True))
op.add_column('item', sa.Column('old_id', sa.Integer, autoincrement=True))
op.add_column('item', sa.Column('old_owner_id', sa.Integer, nullable=True))
# Populate the old columns with default values
# Generate sequences for the integer IDs if not exist
op.execute('CREATE SEQUENCE IF NOT EXISTS user_id_seq AS INTEGER OWNED BY "user".old_id')
op.execute('CREATE SEQUENCE IF NOT EXISTS item_id_seq AS INTEGER OWNED BY item.old_id')
op.execute('SELECT setval(\'user_id_seq\', COALESCE((SELECT MAX(old_id) + 1 FROM "user"), 1), false)')
op.execute('SELECT setval(\'item_id_seq\', COALESCE((SELECT MAX(old_id) + 1 FROM item), 1), false)')
op.execute('UPDATE "user" SET old_id = nextval(\'user_id_seq\')')
op.execute('UPDATE item SET old_id = nextval(\'item_id_seq\'), old_owner_id = (SELECT old_id FROM "user" WHERE "user".id = item.owner_id)')
# Drop new columns and rename old columns back
op.drop_constraint('item_owner_id_fkey', 'item', type_='foreignkey')
op.drop_column('item', 'owner_id')
op.alter_column('item', 'old_owner_id', new_column_name='owner_id')
op.drop_column('user', 'id')
op.alter_column('user', 'old_id', new_column_name='id')
op.drop_column('item', 'id')
op.alter_column('item', 'old_id', new_column_name='id')
# Create primary key constraint
op.create_primary_key('user_pkey', 'user', ['id'])
op.create_primary_key('item_pkey', 'item', ['id'])
# Recreate foreign key constraint
op.create_foreign_key('item_owner_id_fkey', 'item', 'user', ['owner_id'], ['id'])
+4 -3
View File
@@ -1,9 +1,10 @@
from collections.abc import Generator from collections.abc import Generator
from typing import Annotated from typing import Annotated
import jwt
from fastapi import Depends, HTTPException, status from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer from fastapi.security import OAuth2PasswordBearer
from jose import JWTError, jwt from jwt.exceptions import InvalidTokenError
from pydantic import ValidationError from pydantic import ValidationError
from sqlmodel import Session from sqlmodel import Session
@@ -32,7 +33,7 @@ def get_current_user(session: SessionDep, token: TokenDep) -> User:
token, settings.SECRET_KEY, algorithms=[security.ALGORITHM] token, settings.SECRET_KEY, algorithms=[security.ALGORITHM]
) )
token_data = TokenPayload(**payload) token_data = TokenPayload(**payload)
except (JWTError, ValidationError): except (InvalidTokenError, ValidationError):
raise HTTPException( raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN, status_code=status.HTTP_403_FORBIDDEN,
detail="Could not validate credentials", detail="Could not validate credentials",
@@ -51,6 +52,6 @@ CurrentUser = Annotated[User, Depends(get_current_user)]
def get_current_active_superuser(current_user: CurrentUser) -> User: def get_current_active_superuser(current_user: CurrentUser) -> User:
if not current_user.is_superuser: if not current_user.is_superuser:
raise HTTPException( raise HTTPException(
status_code=400, detail="The user doesn't have enough privileges" status_code=403, detail="The user doesn't have enough privileges"
) )
return current_user return current_user
+20 -13
View File
@@ -1,15 +1,16 @@
import uuid
from typing import Any from typing import Any
from fastapi import APIRouter, HTTPException from fastapi import APIRouter, HTTPException
from sqlmodel import func, select from sqlmodel import func, select
from app.api.deps import CurrentUser, SessionDep from app.api.deps import CurrentUser, SessionDep
from app.models import Item, ItemCreate, ItemOut, ItemsOut, ItemUpdate, Message from app.models import Item, ItemCreate, ItemPublic, ItemsPublic, ItemUpdate, Message
router = APIRouter() router = APIRouter()
@router.get("/", response_model=ItemsOut) @router.get("/", response_model=ItemsPublic)
def read_items( def read_items(
session: SessionDep, current_user: CurrentUser, skip: int = 0, limit: int = 100 session: SessionDep, current_user: CurrentUser, skip: int = 0, limit: int = 100
) -> Any: ) -> Any:
@@ -18,17 +19,17 @@ def read_items(
""" """
if current_user.is_superuser: if current_user.is_superuser:
statment = select(func.count()).select_from(Item) count_statement = select(func.count()).select_from(Item)
count = session.exec(statment).one() count = session.exec(count_statement).one()
statement = select(Item).offset(skip).limit(limit) statement = select(Item).offset(skip).limit(limit)
items = session.exec(statement).all() items = session.exec(statement).all()
else: else:
statment = ( count_statement = (
select(func.count()) select(func.count())
.select_from(Item) .select_from(Item)
.where(Item.owner_id == current_user.id) .where(Item.owner_id == current_user.id)
) )
count = session.exec(statment).one() count = session.exec(count_statement).one()
statement = ( statement = (
select(Item) select(Item)
.where(Item.owner_id == current_user.id) .where(Item.owner_id == current_user.id)
@@ -37,11 +38,11 @@ def read_items(
) )
items = session.exec(statement).all() items = session.exec(statement).all()
return ItemsOut(data=items, count=count) return ItemsPublic(data=items, count=count)
@router.get("/{id}", response_model=ItemOut) @router.get("/{id}", response_model=ItemPublic)
def read_item(session: SessionDep, current_user: CurrentUser, id: int) -> Any: def read_item(session: SessionDep, current_user: CurrentUser, id: uuid.UUID) -> Any:
""" """
Get item by ID. Get item by ID.
""" """
@@ -53,7 +54,7 @@ def read_item(session: SessionDep, current_user: CurrentUser, id: int) -> Any:
return item return item
@router.post("/", response_model=ItemOut) @router.post("/", response_model=ItemPublic)
def create_item( def create_item(
*, session: SessionDep, current_user: CurrentUser, item_in: ItemCreate *, session: SessionDep, current_user: CurrentUser, item_in: ItemCreate
) -> Any: ) -> Any:
@@ -67,9 +68,13 @@ def create_item(
return item return item
@router.put("/{id}", response_model=ItemOut) @router.put("/{id}", response_model=ItemPublic)
def update_item( def update_item(
*, session: SessionDep, current_user: CurrentUser, id: int, item_in: ItemUpdate *,
session: SessionDep,
current_user: CurrentUser,
id: uuid.UUID,
item_in: ItemUpdate,
) -> Any: ) -> Any:
""" """
Update an item. Update an item.
@@ -88,7 +93,9 @@ def update_item(
@router.delete("/{id}") @router.delete("/{id}")
def delete_item(session: SessionDep, current_user: CurrentUser, id: int) -> Message: def delete_item(
session: SessionDep, current_user: CurrentUser, id: uuid.UUID
) -> Message:
""" """
Delete an item. Delete an item.
""" """
+2 -2
View File
@@ -10,7 +10,7 @@ from app.api.deps import CurrentUser, SessionDep, get_current_active_superuser
from app.core import security from app.core import security
from app.core.config import settings from app.core.config import settings
from app.core.security import get_password_hash from app.core.security import get_password_hash
from app.models import Message, NewPassword, Token, UserOut from app.models import Message, NewPassword, Token, UserPublic
from app.utils import ( from app.utils import (
generate_password_reset_token, generate_password_reset_token,
generate_reset_password_email, generate_reset_password_email,
@@ -43,7 +43,7 @@ def login_access_token(
) )
@router.post("/login/test-token", response_model=UserOut) @router.post("/login/test-token", response_model=UserPublic)
def test_token(current_user: CurrentUser) -> Any: def test_token(current_user: CurrentUser) -> Any:
""" """
Test access token Test access token
+40 -31
View File
@@ -1,3 +1,4 @@
import uuid
from typing import Any from typing import Any
from fastapi import APIRouter, Depends, HTTPException from fastapi import APIRouter, Depends, HTTPException
@@ -17,9 +18,9 @@ from app.models import (
UpdatePassword, UpdatePassword,
User, User,
UserCreate, UserCreate,
UserCreateOpen, UserPublic,
UserOut, UserRegister,
UsersOut, UsersPublic,
UserUpdate, UserUpdate,
UserUpdateMe, UserUpdateMe,
) )
@@ -29,24 +30,26 @@ router = APIRouter()
@router.get( @router.get(
"/", dependencies=[Depends(get_current_active_superuser)], response_model=UsersOut "/",
dependencies=[Depends(get_current_active_superuser)],
response_model=UsersPublic,
) )
def read_users(session: SessionDep, skip: int = 0, limit: int = 100) -> Any: def read_users(session: SessionDep, skip: int = 0, limit: int = 100) -> Any:
""" """
Retrieve users. Retrieve users.
""" """
statment = select(func.count()).select_from(User) count_statement = select(func.count()).select_from(User)
count = session.exec(statment).one() count = session.exec(count_statement).one()
statement = select(User).offset(skip).limit(limit) statement = select(User).offset(skip).limit(limit)
users = session.exec(statement).all() users = session.exec(statement).all()
return UsersOut(data=users, count=count) return UsersPublic(data=users, count=count)
@router.post( @router.post(
"/", dependencies=[Depends(get_current_active_superuser)], response_model=UserOut "/", dependencies=[Depends(get_current_active_superuser)], response_model=UserPublic
) )
def create_user(*, session: SessionDep, user_in: UserCreate) -> Any: def create_user(*, session: SessionDep, user_in: UserCreate) -> Any:
""" """
@@ -72,7 +75,7 @@ def create_user(*, session: SessionDep, user_in: UserCreate) -> Any:
return user return user
@router.patch("/me", response_model=UserOut) @router.patch("/me", response_model=UserPublic)
def update_user_me( def update_user_me(
*, session: SessionDep, user_in: UserUpdateMe, current_user: CurrentUser *, session: SessionDep, user_in: UserUpdateMe, current_user: CurrentUser
) -> Any: ) -> Any:
@@ -114,38 +117,49 @@ def update_password_me(
return Message(message="Password updated successfully") return Message(message="Password updated successfully")
@router.get("/me", response_model=UserOut) @router.get("/me", response_model=UserPublic)
def read_user_me(session: SessionDep, current_user: CurrentUser) -> Any: def read_user_me(current_user: CurrentUser) -> Any:
""" """
Get current user. Get current user.
""" """
return current_user return current_user
@router.post("/open", response_model=UserOut) @router.delete("/me", response_model=Message)
def create_user_open(session: SessionDep, user_in: UserCreateOpen) -> Any: def delete_user_me(session: SessionDep, current_user: CurrentUser) -> Any:
"""
Delete own user.
"""
if current_user.is_superuser:
raise HTTPException(
status_code=403, detail="Super users are not allowed to delete themselves"
)
statement = delete(Item).where(col(Item.owner_id) == current_user.id)
session.exec(statement) # type: ignore
session.delete(current_user)
session.commit()
return Message(message="User deleted successfully")
@router.post("/signup", response_model=UserPublic)
def register_user(session: SessionDep, user_in: UserRegister) -> Any:
""" """
Create new user without the need to be logged in. Create new user without the need to be logged in.
""" """
if not settings.USERS_OPEN_REGISTRATION:
raise HTTPException(
status_code=403,
detail="Open user registration is forbidden on this server",
)
user = crud.get_user_by_email(session=session, email=user_in.email) user = crud.get_user_by_email(session=session, email=user_in.email)
if user: if user:
raise HTTPException( raise HTTPException(
status_code=400, status_code=400,
detail="The user with this email already exists in the system", detail="The user with this email already exists in the system",
) )
user_create = UserCreate.from_orm(user_in) user_create = UserCreate.model_validate(user_in)
user = crud.create_user(session=session, user_create=user_create) user = crud.create_user(session=session, user_create=user_create)
return user return user
@router.get("/{user_id}", response_model=UserOut) @router.get("/{user_id}", response_model=UserPublic)
def read_user_by_id( def read_user_by_id(
user_id: int, session: SessionDep, current_user: CurrentUser user_id: uuid.UUID, session: SessionDep, current_user: CurrentUser
) -> Any: ) -> Any:
""" """
Get a specific user by id. Get a specific user by id.
@@ -164,12 +178,12 @@ def read_user_by_id(
@router.patch( @router.patch(
"/{user_id}", "/{user_id}",
dependencies=[Depends(get_current_active_superuser)], dependencies=[Depends(get_current_active_superuser)],
response_model=UserOut, response_model=UserPublic,
) )
def update_user( def update_user(
*, *,
session: SessionDep, session: SessionDep,
user_id: int, user_id: uuid.UUID,
user_in: UserUpdate, user_in: UserUpdate,
) -> Any: ) -> Any:
""" """
@@ -193,9 +207,9 @@ def update_user(
return db_user return db_user
@router.delete("/{user_id}") @router.delete("/{user_id}", dependencies=[Depends(get_current_active_superuser)])
def delete_user( def delete_user(
session: SessionDep, current_user: CurrentUser, user_id: int session: SessionDep, current_user: CurrentUser, user_id: uuid.UUID
) -> Message: ) -> Message:
""" """
Delete a user. Delete a user.
@@ -203,15 +217,10 @@ def delete_user(
user = session.get(User, user_id) user = session.get(User, user_id)
if not user: if not user:
raise HTTPException(status_code=404, detail="User not found") raise HTTPException(status_code=404, detail="User not found")
elif user != current_user and not current_user.is_superuser: if user == current_user:
raise HTTPException(
status_code=403, detail="The user doesn't have enough privileges"
)
elif user == current_user and current_user.is_superuser:
raise HTTPException( raise HTTPException(
status_code=403, detail="Super users are not allowed to delete themselves" status_code=403, detail="Super users are not allowed to delete themselves"
) )
statement = delete(Item).where(col(Item.owner_id) == user_id) statement = delete(Item).where(col(Item.owner_id) == user_id)
session.exec(statement) # type: ignore session.exec(statement) # type: ignore
session.delete(user) session.delete(user)
-39
View File
@@ -1,39 +0,0 @@
import logging
from sqlalchemy import Engine
from sqlmodel import Session, select
from tenacity import after_log, before_log, retry, stop_after_attempt, wait_fixed
from app.core.db import engine
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
max_tries = 60 * 5 # 5 minutes
wait_seconds = 1
@retry(
stop=stop_after_attempt(max_tries),
wait=wait_fixed(wait_seconds),
before=before_log(logger, logging.INFO),
after=after_log(logger, logging.WARN),
)
def init(db_engine: Engine) -> None:
try:
# Try to create session to check if DB is awake
with Session(db_engine) as session:
session.exec(select(1))
except Exception as e:
logger.error(e)
raise e
def main() -> None:
logger.info("Initializing service")
init(engine)
logger.info("Service finished initializing")
if __name__ == "__main__":
main()
+4 -5
View File
@@ -34,7 +34,7 @@ class Settings(BaseSettings):
DOMAIN: str = "localhost" DOMAIN: str = "localhost"
ENVIRONMENT: Literal["local", "staging", "production"] = "local" ENVIRONMENT: Literal["local", "staging", "production"] = "local"
@computed_field # type: ignore[misc] @computed_field # type: ignore[prop-decorator]
@property @property
def server_host(self) -> str: def server_host(self) -> str:
# Use HTTPS for anything other than local development # Use HTTPS for anything other than local development
@@ -51,10 +51,10 @@ class Settings(BaseSettings):
POSTGRES_SERVER: str POSTGRES_SERVER: str
POSTGRES_PORT: int = 5432 POSTGRES_PORT: int = 5432
POSTGRES_USER: str POSTGRES_USER: str
POSTGRES_PASSWORD: str POSTGRES_PASSWORD: str = ""
POSTGRES_DB: str = "" POSTGRES_DB: str = ""
@computed_field # type: ignore[misc] @computed_field # type: ignore[prop-decorator]
@property @property
def SQLALCHEMY_DATABASE_URI(self) -> PostgresDsn: def SQLALCHEMY_DATABASE_URI(self) -> PostgresDsn:
return MultiHostUrl.build( return MultiHostUrl.build(
@@ -84,7 +84,7 @@ class Settings(BaseSettings):
EMAIL_RESET_TOKEN_EXPIRE_HOURS: int = 48 EMAIL_RESET_TOKEN_EXPIRE_HOURS: int = 48
@computed_field # type: ignore[misc] @computed_field # type: ignore[prop-decorator]
@property @property
def emails_enabled(self) -> bool: def emails_enabled(self) -> bool:
return bool(self.SMTP_HOST and self.EMAILS_FROM_EMAIL) return bool(self.SMTP_HOST and self.EMAILS_FROM_EMAIL)
@@ -94,7 +94,6 @@ class Settings(BaseSettings):
# TODO: update type to EmailStr when sqlmodel supports it # TODO: update type to EmailStr when sqlmodel supports it
FIRST_SUPERUSER: str FIRST_SUPERUSER: str
FIRST_SUPERUSER_PASSWORD: str FIRST_SUPERUSER_PASSWORD: str
USERS_OPEN_REGISTRATION: bool = False
def _check_default_secret(self, var_name: str, value: str | None) -> None: def _check_default_secret(self, var_name: str, value: str | None) -> None:
if value == "changethis": if value == "changethis":
+1 -1
View File
@@ -9,7 +9,7 @@ engine = create_engine(str(settings.SQLALCHEMY_DATABASE_URI))
# make sure all SQLModel models are imported (app.models) before initializing DB # make sure all SQLModel models are imported (app.models) before initializing DB
# otherwise, SQLModel might fail to initialize relationships properly # otherwise, SQLModel might fail to initialize relationships properly
# for more details: https://github.com/tiangolo/full-stack-fastapi-template/issues/28 # for more details: https://github.com/fastapi/full-stack-fastapi-template/issues/28
def init_db(session: Session) -> None: def init_db(session: Session) -> None:
+3 -3
View File
@@ -1,7 +1,7 @@
from datetime import datetime, timedelta from datetime import datetime, timedelta, timezone
from typing import Any from typing import Any
from jose import jwt import jwt
from passlib.context import CryptContext from passlib.context import CryptContext
from app.core.config import settings from app.core.config import settings
@@ -13,7 +13,7 @@ ALGORITHM = "HS256"
def create_access_token(subject: str | Any, expires_delta: timedelta) -> str: def create_access_token(subject: str | Any, expires_delta: timedelta) -> str:
expire = datetime.utcnow() + expires_delta expire = datetime.now(timezone.utc) + expires_delta
to_encode = {"exp": expire, "sub": str(subject)} to_encode = {"exp": expire, "sub": str(subject)}
encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=ALGORITHM) encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt return encoded_jwt
+2 -1
View File
@@ -1,3 +1,4 @@
import uuid
from typing import Any from typing import Any
from sqlmodel import Session, select from sqlmodel import Session, select
@@ -45,7 +46,7 @@ def authenticate(*, session: Session, email: str, password: str) -> User | None:
return db_user return db_user
def create_item(*, session: Session, item_in: ItemCreate, owner_id: int) -> Item: def create_item(*, session: Session, item_in: ItemCreate, owner_id: uuid.UUID) -> Item:
db_item = Item.model_validate(item_in, update={"owner_id": owner_id}) db_item = Item.model_validate(item_in, update={"owner_id": owner_id})
session.add(db_item) session.add(db_item)
session.commit() session.commit()
+4
View File
@@ -1,3 +1,4 @@
import sentry_sdk
from fastapi import FastAPI from fastapi import FastAPI
from fastapi.routing import APIRoute from fastapi.routing import APIRoute
from starlette.middleware.cors import CORSMiddleware from starlette.middleware.cors import CORSMiddleware
@@ -10,6 +11,9 @@ def custom_generate_unique_id(route: APIRoute) -> str:
return f"{route.tags[0]}-{route.name}" return f"{route.tags[0]}-{route.name}"
if settings.SENTRY_DSN and settings.ENVIRONMENT != "local":
sentry_sdk.init(dsn=str(settings.SENTRY_DSN), enable_tracing=True)
app = FastAPI( app = FastAPI(
title=settings.PROJECT_NAME, title=settings.PROJECT_NAME,
openapi_url=f"{settings.API_V1_STR}/openapi.json", openapi_url=f"{settings.API_V1_STR}/openapi.json",
+38 -37
View File
@@ -1,94 +1,95 @@
import uuid
from pydantic import EmailStr
from sqlmodel import Field, Relationship, SQLModel from sqlmodel import Field, Relationship, SQLModel
# Shared properties # Shared properties
# TODO replace email str with EmailStr when sqlmodel supports it
class UserBase(SQLModel): class UserBase(SQLModel):
email: str = Field(unique=True, index=True) email: EmailStr = Field(unique=True, index=True, max_length=255)
is_active: bool = True is_active: bool = True
is_superuser: bool = False is_superuser: bool = False
full_name: str | None = None full_name: str | None = Field(default=None, max_length=255)
# Properties to receive via API on creation # Properties to receive via API on creation
class UserCreate(UserBase): class UserCreate(UserBase):
password: str password: str = Field(min_length=8, max_length=40)
# TODO replace email str with EmailStr when sqlmodel supports it class UserRegister(SQLModel):
class UserCreateOpen(SQLModel): email: EmailStr = Field(max_length=255)
email: str password: str = Field(min_length=8, max_length=40)
password: str full_name: str | None = Field(default=None, max_length=255)
full_name: str | None = None
# Properties to receive via API on update, all are optional # Properties to receive via API on update, all are optional
# TODO replace email str with EmailStr when sqlmodel supports it
class UserUpdate(UserBase): class UserUpdate(UserBase):
email: str | None = None # type: ignore email: EmailStr | None = Field(default=None, max_length=255) # type: ignore
password: str | None = None password: str | None = Field(default=None, min_length=8, max_length=40)
# TODO replace email str with EmailStr when sqlmodel supports it
class UserUpdateMe(SQLModel): class UserUpdateMe(SQLModel):
full_name: str | None = None full_name: str | None = Field(default=None, max_length=255)
email: str | None = None email: EmailStr | None = Field(default=None, max_length=255)
class UpdatePassword(SQLModel): class UpdatePassword(SQLModel):
current_password: str current_password: str = Field(min_length=8, max_length=40)
new_password: str new_password: str = Field(min_length=8, max_length=40)
# Database model, database table inferred from class name # Database model, database table inferred from class name
class User(UserBase, table=True): class User(UserBase, table=True):
id: int | None = Field(default=None, primary_key=True) id: uuid.UUID = Field(default_factory=uuid.uuid4, primary_key=True)
hashed_password: str hashed_password: str
items: list["Item"] = Relationship(back_populates="owner") items: list["Item"] = Relationship(back_populates="owner", cascade_delete=True)
# Properties to return via API, id is always required # Properties to return via API, id is always required
class UserOut(UserBase): class UserPublic(UserBase):
id: int id: uuid.UUID
class UsersOut(SQLModel): class UsersPublic(SQLModel):
data: list[UserOut] data: list[UserPublic]
count: int count: int
# Shared properties # Shared properties
class ItemBase(SQLModel): class ItemBase(SQLModel):
title: str title: str = Field(min_length=1, max_length=255)
description: str | None = None description: str | None = Field(default=None, max_length=255)
# Properties to receive on item creation # Properties to receive on item creation
class ItemCreate(ItemBase): class ItemCreate(ItemBase):
title: str title: str = Field(min_length=1, max_length=255)
# Properties to receive on item update # Properties to receive on item update
class ItemUpdate(ItemBase): class ItemUpdate(ItemBase):
title: str | None = None # type: ignore title: str | None = Field(default=None, min_length=1, max_length=255) # type: ignore
# Database model, database table inferred from class name # Database model, database table inferred from class name
class Item(ItemBase, table=True): class Item(ItemBase, table=True):
id: int | None = Field(default=None, primary_key=True) id: uuid.UUID = Field(default_factory=uuid.uuid4, primary_key=True)
title: str title: str = Field(max_length=255)
owner_id: int | None = Field(default=None, foreign_key="user.id", nullable=False) owner_id: uuid.UUID = Field(
foreign_key="user.id", nullable=False, ondelete="CASCADE"
)
owner: User | None = Relationship(back_populates="items") owner: User | None = Relationship(back_populates="items")
# Properties to return via API, id is always required # Properties to return via API, id is always required
class ItemOut(ItemBase): class ItemPublic(ItemBase):
id: int id: uuid.UUID
owner_id: int owner_id: uuid.UUID
class ItemsOut(SQLModel): class ItemsPublic(SQLModel):
data: list[ItemOut] data: list[ItemPublic]
count: int count: int
@@ -105,9 +106,9 @@ class Token(SQLModel):
# Contents of JWT token # Contents of JWT token
class TokenPayload(SQLModel): class TokenPayload(SQLModel):
sub: int | None = None sub: str | None = None
class NewPassword(SQLModel): class NewPassword(SQLModel):
token: str token: str
new_password: str new_password: str = Field(min_length=8, max_length=40)
+13 -11
View File
@@ -1,3 +1,5 @@
import uuid
from fastapi.testclient import TestClient from fastapi.testclient import TestClient
from sqlmodel import Session from sqlmodel import Session
@@ -6,7 +8,7 @@ from app.tests.utils.item import create_random_item
def test_create_item( def test_create_item(
client: TestClient, superuser_token_headers: dict[str, str], db: Session client: TestClient, superuser_token_headers: dict[str, str]
) -> None: ) -> None:
data = {"title": "Foo", "description": "Fighters"} data = {"title": "Foo", "description": "Fighters"}
response = client.post( response = client.post(
@@ -34,15 +36,15 @@ def test_read_item(
content = response.json() content = response.json()
assert content["title"] == item.title assert content["title"] == item.title
assert content["description"] == item.description assert content["description"] == item.description
assert content["id"] == item.id assert content["id"] == str(item.id)
assert content["owner_id"] == item.owner_id assert content["owner_id"] == str(item.owner_id)
def test_read_item_not_found( def test_read_item_not_found(
client: TestClient, superuser_token_headers: dict[str, str], db: Session client: TestClient, superuser_token_headers: dict[str, str]
) -> None: ) -> None:
response = client.get( response = client.get(
f"{settings.API_V1_STR}/items/999", f"{settings.API_V1_STR}/items/{uuid.uuid4()}",
headers=superuser_token_headers, headers=superuser_token_headers,
) )
assert response.status_code == 404 assert response.status_code == 404
@@ -91,16 +93,16 @@ def test_update_item(
content = response.json() content = response.json()
assert content["title"] == data["title"] assert content["title"] == data["title"]
assert content["description"] == data["description"] assert content["description"] == data["description"]
assert content["id"] == item.id assert content["id"] == str(item.id)
assert content["owner_id"] == item.owner_id assert content["owner_id"] == str(item.owner_id)
def test_update_item_not_found( def test_update_item_not_found(
client: TestClient, superuser_token_headers: dict[str, str], db: Session client: TestClient, superuser_token_headers: dict[str, str]
) -> None: ) -> None:
data = {"title": "Updated title", "description": "Updated description"} data = {"title": "Updated title", "description": "Updated description"}
response = client.put( response = client.put(
f"{settings.API_V1_STR}/items/999", f"{settings.API_V1_STR}/items/{uuid.uuid4()}",
headers=superuser_token_headers, headers=superuser_token_headers,
json=data, json=data,
) )
@@ -138,10 +140,10 @@ def test_delete_item(
def test_delete_item_not_found( def test_delete_item_not_found(
client: TestClient, superuser_token_headers: dict[str, str], db: Session client: TestClient, superuser_token_headers: dict[str, str]
) -> None: ) -> None:
response = client.delete( response = client.delete(
f"{settings.API_V1_STR}/items/999", f"{settings.API_V1_STR}/items/{uuid.uuid4()}",
headers=superuser_token_headers, headers=superuser_token_headers,
) )
assert response.status_code == 404 assert response.status_code == 404
+16 -6
View File
@@ -1,7 +1,11 @@
from unittest.mock import patch
from fastapi.testclient import TestClient from fastapi.testclient import TestClient
from pytest_mock import MockerFixture from sqlmodel import Session, select
from app.core.config import settings from app.core.config import settings
from app.core.security import verify_password
from app.models import User
from app.utils import generate_password_reset_token from app.utils import generate_password_reset_token
@@ -39,11 +43,12 @@ def test_use_access_token(
def test_recovery_password( def test_recovery_password(
client: TestClient, normal_user_token_headers: dict[str, str], mocker: MockerFixture client: TestClient, normal_user_token_headers: dict[str, str]
) -> None: ) -> None:
mocker.patch("app.utils.send_email", return_value=None) with (
mocker.patch("app.core.config.settings.SMTP_HOST", "smtp.example.com") patch("app.core.config.settings.SMTP_HOST", "smtp.example.com"),
mocker.patch("app.core.config.settings.SMTP_USER", "admin@example.com") patch("app.core.config.settings.SMTP_USER", "admin@example.com"),
):
email = "test@example.com" email = "test@example.com"
r = client.post( r = client.post(
f"{settings.API_V1_STR}/password-recovery/{email}", f"{settings.API_V1_STR}/password-recovery/{email}",
@@ -65,7 +70,7 @@ def test_recovery_password_user_not_exits(
def test_reset_password( def test_reset_password(
client: TestClient, superuser_token_headers: dict[str, str] client: TestClient, superuser_token_headers: dict[str, str], db: Session
) -> None: ) -> None:
token = generate_password_reset_token(email=settings.FIRST_SUPERUSER) token = generate_password_reset_token(email=settings.FIRST_SUPERUSER)
data = {"new_password": "changethis", "token": token} data = {"new_password": "changethis", "token": token}
@@ -77,6 +82,11 @@ def test_reset_password(
assert r.status_code == 200 assert r.status_code == 200
assert r.json() == {"message": "Password updated successfully"} assert r.json() == {"message": "Password updated successfully"}
user_query = select(User).where(User.email == settings.FIRST_SUPERUSER)
user = db.exec(user_query).first()
assert user
assert verify_password(data["new_password"], user.hashed_password)
def test_reset_password_invalid_token( def test_reset_password_invalid_token(
client: TestClient, superuser_token_headers: dict[str, str] client: TestClient, superuser_token_headers: dict[str, str]
+92 -61
View File
@@ -1,10 +1,13 @@
import uuid
from unittest.mock import patch
from fastapi.testclient import TestClient from fastapi.testclient import TestClient
from pytest_mock import MockerFixture from sqlmodel import Session, select
from sqlmodel import Session
from app import crud from app import crud
from app.core.config import settings from app.core.config import settings
from app.models import UserCreate from app.core.security import verify_password
from app.models import User, UserCreate
from app.tests.utils.utils import random_email, random_lower_string from app.tests.utils.utils import random_email, random_lower_string
@@ -31,14 +34,13 @@ def test_get_users_normal_user_me(
def test_create_user_new_email( def test_create_user_new_email(
client: TestClient, client: TestClient, superuser_token_headers: dict[str, str], db: Session
superuser_token_headers: dict[str, str],
db: Session,
mocker: MockerFixture,
) -> None: ) -> None:
mocker.patch("app.utils.send_email") with (
mocker.patch("app.core.config.settings.SMTP_HOST", "smtp.example.com") patch("app.utils.send_email", return_value=None),
mocker.patch("app.core.config.settings.SMTP_USER", "admin@example.com") patch("app.core.config.settings.SMTP_HOST", "smtp.example.com"),
patch("app.core.config.settings.SMTP_USER", "admin@example.com"),
):
username = random_email() username = random_email()
password = random_lower_string() password = random_lower_string()
data = {"email": username, "password": password} data = {"email": username, "password": password}
@@ -101,10 +103,10 @@ def test_get_existing_user_current_user(client: TestClient, db: Session) -> None
def test_get_existing_user_permissions_error( def test_get_existing_user_permissions_error(
client: TestClient, normal_user_token_headers: dict[str, str], db: Session client: TestClient, normal_user_token_headers: dict[str, str]
) -> None: ) -> None:
r = client.get( r = client.get(
f"{settings.API_V1_STR}/users/999999", f"{settings.API_V1_STR}/users/{uuid.uuid4()}",
headers=normal_user_token_headers, headers=normal_user_token_headers,
) )
assert r.status_code == 403 assert r.status_code == 403
@@ -141,7 +143,7 @@ def test_create_user_by_normal_user(
headers=normal_user_token_headers, headers=normal_user_token_headers,
json=data, json=data,
) )
assert r.status_code == 400 assert r.status_code == 403
def test_retrieve_users( def test_retrieve_users(
@@ -182,6 +184,12 @@ def test_update_user_me(
assert updated_user["email"] == email assert updated_user["email"] == email
assert updated_user["full_name"] == full_name assert updated_user["full_name"] == full_name
user_query = select(User).where(User.email == email)
user_db = db.exec(user_query).first()
assert user_db
assert user_db.email == email
assert user_db.full_name == full_name
def test_update_password_me( def test_update_password_me(
client: TestClient, superuser_token_headers: dict[str, str], db: Session client: TestClient, superuser_token_headers: dict[str, str], db: Session
@@ -200,6 +208,12 @@ def test_update_password_me(
updated_user = r.json() updated_user = r.json()
assert updated_user["message"] == "Password updated successfully" assert updated_user["message"] == "Password updated successfully"
user_query = select(User).where(User.email == settings.FIRST_SUPERUSER)
user_db = db.exec(user_query).first()
assert user_db
assert user_db.email == settings.FIRST_SUPERUSER
assert verify_password(new_password, user_db.hashed_password)
# Revert to the old password to keep consistency in test # Revert to the old password to keep consistency in test
old_data = { old_data = {
"current_password": new_password, "current_password": new_password,
@@ -210,11 +224,14 @@ def test_update_password_me(
headers=superuser_token_headers, headers=superuser_token_headers,
json=old_data, json=old_data,
) )
db.refresh(user_db)
assert r.status_code == 200 assert r.status_code == 200
assert verify_password(settings.FIRST_SUPERUSER_PASSWORD, user_db.hashed_password)
def test_update_password_me_incorrect_password( def test_update_password_me_incorrect_password(
client: TestClient, superuser_token_headers: dict[str, str], db: Session client: TestClient, superuser_token_headers: dict[str, str]
) -> None: ) -> None:
new_password = random_lower_string() new_password = random_lower_string()
data = {"current_password": new_password, "new_password": new_password} data = {"current_password": new_password, "new_password": new_password}
@@ -247,7 +264,7 @@ def test_update_user_me_email_exists(
def test_update_password_me_same_password_error( def test_update_password_me_same_password_error(
client: TestClient, superuser_token_headers: dict[str, str], db: Session client: TestClient, superuser_token_headers: dict[str, str]
) -> None: ) -> None:
data = { data = {
"current_password": settings.FIRST_SUPERUSER_PASSWORD, "current_password": settings.FIRST_SUPERUSER_PASSWORD,
@@ -265,14 +282,13 @@ def test_update_password_me_same_password_error(
) )
def test_create_user_open(client: TestClient, mocker: MockerFixture) -> None: def test_register_user(client: TestClient, db: Session) -> None:
mocker.patch("app.core.config.settings.USERS_OPEN_REGISTRATION", True)
username = random_email() username = random_email()
password = random_lower_string() password = random_lower_string()
full_name = random_lower_string() full_name = random_lower_string()
data = {"email": username, "password": password, "full_name": full_name} data = {"email": username, "password": password, "full_name": full_name}
r = client.post( r = client.post(
f"{settings.API_V1_STR}/users/open", f"{settings.API_V1_STR}/users/signup",
json=data, json=data,
) )
assert r.status_code == 200 assert r.status_code == 200
@@ -280,27 +296,15 @@ def test_create_user_open(client: TestClient, mocker: MockerFixture) -> None:
assert created_user["email"] == username assert created_user["email"] == username
assert created_user["full_name"] == full_name assert created_user["full_name"] == full_name
user_query = select(User).where(User.email == username)
def test_create_user_open_forbidden_error( user_db = db.exec(user_query).first()
client: TestClient, mocker: MockerFixture assert user_db
) -> None: assert user_db.email == username
mocker.patch("app.core.config.settings.USERS_OPEN_REGISTRATION", False) assert user_db.full_name == full_name
username = random_email() assert verify_password(password, user_db.hashed_password)
password = random_lower_string()
full_name = random_lower_string()
data = {"email": username, "password": password, "full_name": full_name}
r = client.post(
f"{settings.API_V1_STR}/users/open",
json=data,
)
assert r.status_code == 403
assert r.json()["detail"] == "Open user registration is forbidden on this server"
def test_create_user_open_already_exists_error( def test_register_user_already_exists_error(client: TestClient) -> None:
client: TestClient, mocker: MockerFixture
) -> None:
mocker.patch("app.core.config.settings.USERS_OPEN_REGISTRATION", True)
password = random_lower_string() password = random_lower_string()
full_name = random_lower_string() full_name = random_lower_string()
data = { data = {
@@ -309,7 +313,7 @@ def test_create_user_open_already_exists_error(
"full_name": full_name, "full_name": full_name,
} }
r = client.post( r = client.post(
f"{settings.API_V1_STR}/users/open", f"{settings.API_V1_STR}/users/signup",
json=data, json=data,
) )
assert r.status_code == 400 assert r.status_code == 400
@@ -332,15 +336,22 @@ def test_update_user(
) )
assert r.status_code == 200 assert r.status_code == 200
updated_user = r.json() updated_user = r.json()
assert updated_user["full_name"] == "Updated_full_name" assert updated_user["full_name"] == "Updated_full_name"
user_query = select(User).where(User.email == username)
user_db = db.exec(user_query).first()
db.refresh(user_db)
assert user_db
assert user_db.full_name == "Updated_full_name"
def test_update_user_not_exists( def test_update_user_not_exists(
client: TestClient, superuser_token_headers: dict[str, str], db: Session client: TestClient, superuser_token_headers: dict[str, str]
) -> None: ) -> None:
data = {"full_name": "Updated_full_name"} data = {"full_name": "Updated_full_name"}
r = client.patch( r = client.patch(
f"{settings.API_V1_STR}/users/99999999", f"{settings.API_V1_STR}/users/{uuid.uuid4()}",
headers=superuser_token_headers, headers=superuser_token_headers,
json=data, json=data,
) )
@@ -371,24 +382,7 @@ def test_update_user_email_exists(
assert r.json()["detail"] == "User with this email already exists" assert r.json()["detail"] == "User with this email already exists"
def test_delete_user_super_user( def test_delete_user_me(client: TestClient, db: Session) -> None:
client: TestClient, superuser_token_headers: dict[str, str], db: Session
) -> None:
username = random_email()
password = random_lower_string()
user_in = UserCreate(email=username, password=password)
user = crud.create_user(session=db, user_create=user_in)
user_id = user.id
r = client.delete(
f"{settings.API_V1_STR}/users/{user_id}",
headers=superuser_token_headers,
)
assert r.status_code == 200
deleted_user = r.json()
assert deleted_user["message"] == "User deleted successfully"
def test_delete_user_current_user(client: TestClient, db: Session) -> None:
username = random_email() username = random_email()
password = random_lower_string() password = random_lower_string()
user_in = UserCreate(email=username, password=password) user_in = UserCreate(email=username, password=password)
@@ -405,19 +399,56 @@ def test_delete_user_current_user(client: TestClient, db: Session) -> None:
headers = {"Authorization": f"Bearer {a_token}"} headers = {"Authorization": f"Bearer {a_token}"}
r = client.delete( r = client.delete(
f"{settings.API_V1_STR}/users/{user_id}", f"{settings.API_V1_STR}/users/me",
headers=headers, headers=headers,
) )
assert r.status_code == 200 assert r.status_code == 200
deleted_user = r.json() deleted_user = r.json()
assert deleted_user["message"] == "User deleted successfully" assert deleted_user["message"] == "User deleted successfully"
result = db.exec(select(User).where(User.id == user_id)).first()
assert result is None
user_query = select(User).where(User.id == user_id)
user_db = db.execute(user_query).first()
assert user_db is None
def test_delete_user_me_as_superuser(
client: TestClient, superuser_token_headers: dict[str, str]
) -> None:
r = client.delete(
f"{settings.API_V1_STR}/users/me",
headers=superuser_token_headers,
)
assert r.status_code == 403
response = r.json()
assert response["detail"] == "Super users are not allowed to delete themselves"
def test_delete_user_super_user(
client: TestClient, superuser_token_headers: dict[str, str], db: Session
) -> None:
username = random_email()
password = random_lower_string()
user_in = UserCreate(email=username, password=password)
user = crud.create_user(session=db, user_create=user_in)
user_id = user.id
r = client.delete(
f"{settings.API_V1_STR}/users/{user_id}",
headers=superuser_token_headers,
)
assert r.status_code == 200
deleted_user = r.json()
assert deleted_user["message"] == "User deleted successfully"
result = db.exec(select(User).where(User.id == user_id)).first()
assert result is None
def test_delete_user_not_found( def test_delete_user_not_found(
client: TestClient, superuser_token_headers: dict[str, str], db: Session client: TestClient, superuser_token_headers: dict[str, str]
) -> None: ) -> None:
r = client.delete( r = client.delete(
f"{settings.API_V1_STR}/users/99999999", f"{settings.API_V1_STR}/users/{uuid.uuid4()}",
headers=superuser_token_headers, headers=superuser_token_headers,
) )
assert r.status_code == 404 assert r.status_code == 404
@@ -1,23 +1,23 @@
from unittest.mock import MagicMock from unittest.mock import MagicMock, patch
from pytest_mock import MockerFixture
from sqlmodel import select from sqlmodel import select
from app.backend_pre_start import init, logger from app.backend_pre_start import init, logger
def test_init_successful_connection(mocker: MockerFixture) -> None: def test_init_successful_connection() -> None:
engine_mock = MagicMock() engine_mock = MagicMock()
session_mock = MagicMock() session_mock = MagicMock()
exec_mock = MagicMock(return_value=True) exec_mock = MagicMock(return_value=True)
session_mock.configure_mock(**{"exec.return_value": exec_mock}) session_mock.configure_mock(**{"exec.return_value": exec_mock})
mocker.patch("sqlmodel.Session", return_value=session_mock)
mocker.patch.object(logger, "info")
mocker.patch.object(logger, "error")
mocker.patch.object(logger, "warn")
with (
patch("sqlmodel.Session", return_value=session_mock),
patch.object(logger, "info"),
patch.object(logger, "error"),
patch.object(logger, "warn"),
):
try: try:
init(engine_mock) init(engine_mock)
connection_successful = True connection_successful = True
@@ -1,23 +1,23 @@
from unittest.mock import MagicMock from unittest.mock import MagicMock, patch
from pytest_mock import MockerFixture
from sqlmodel import select from sqlmodel import select
from app.tests_pre_start import init, logger from app.tests_pre_start import init, logger
def test_init_successful_connection(mocker: MockerFixture) -> None: def test_init_successful_connection() -> None:
engine_mock = MagicMock() engine_mock = MagicMock()
session_mock = MagicMock() session_mock = MagicMock()
exec_mock = MagicMock(return_value=True) exec_mock = MagicMock(return_value=True)
session_mock.configure_mock(**{"exec.return_value": exec_mock}) session_mock.configure_mock(**{"exec.return_value": exec_mock})
mocker.patch("sqlmodel.Session", return_value=session_mock)
mocker.patch.object(logger, "info")
mocker.patch.object(logger, "error")
mocker.patch.object(logger, "warn")
with (
patch("sqlmodel.Session", return_value=session_mock),
patch.object(logger, "info"),
patch.object(logger, "error"),
patch.object(logger, "warn"),
):
try: try:
init(engine_mock) init(engine_mock)
connection_successful = True connection_successful = True
+5 -4
View File
@@ -1,12 +1,13 @@
import logging import logging
from dataclasses import dataclass from dataclasses import dataclass
from datetime import datetime, timedelta from datetime import datetime, timedelta, timezone
from pathlib import Path from pathlib import Path
from typing import Any from typing import Any
import emails # type: ignore import emails # type: ignore
import jwt
from jinja2 import Template from jinja2 import Template
from jose import JWTError, jwt from jwt.exceptions import InvalidTokenError
from app.core.config import settings from app.core.config import settings
@@ -97,7 +98,7 @@ def generate_new_account_email(
def generate_password_reset_token(email: str) -> str: def generate_password_reset_token(email: str) -> str:
delta = timedelta(hours=settings.EMAIL_RESET_TOKEN_EXPIRE_HOURS) delta = timedelta(hours=settings.EMAIL_RESET_TOKEN_EXPIRE_HOURS)
now = datetime.utcnow() now = datetime.now(timezone.utc)
expires = now + delta expires = now + delta
exp = expires.timestamp() exp = expires.timestamp()
encoded_jwt = jwt.encode( encoded_jwt = jwt.encode(
@@ -112,5 +113,5 @@ def verify_password_reset_token(token: str) -> str | None:
try: try:
decoded_token = jwt.decode(token, settings.SECRET_KEY, algorithms=["HS256"]) decoded_token = jwt.decode(token, settings.SECRET_KEY, algorithms=["HS256"])
return str(decoded_token["sub"]) return str(decoded_token["sub"])
except JWTError: except InvalidTokenError:
return None return None
+661 -834
View File
File diff suppressed because it is too large Load Diff
+8 -13
View File
@@ -15,43 +15,37 @@ tenacity = "^8.2.3"
pydantic = ">2.0" pydantic = ">2.0"
emails = "^0.6" emails = "^0.6"
gunicorn = "^21.2.0" gunicorn = "^22.0.0"
jinja2 = "^3.1.2" jinja2 = "^3.1.4"
alembic = "^1.12.1" alembic = "^1.12.1"
python-jose = {extras = ["cryptography"], version = "^3.3.0"}
httpx = "^0.25.1" httpx = "^0.25.1"
psycopg = {extras = ["binary"], version = "^3.1.13"} psycopg = {extras = ["binary"], version = "^3.1.13"}
sqlmodel = "^0.0.16" sqlmodel = "^0.0.21"
# Pin bcrypt until passlib supports the latest # Pin bcrypt until passlib supports the latest
bcrypt = "4.0.1" bcrypt = "4.0.1"
pydantic-settings = "^2.2.1" pydantic-settings = "^2.2.1"
sentry-sdk = {extras = ["fastapi"], version = "^1.40.6"} sentry-sdk = {extras = ["fastapi"], version = "^1.40.6"}
pyjwt = "^2.8.0"
[tool.poetry.group.dev.dependencies] [tool.poetry.group.dev.dependencies]
pytest = "^7.4.3" pytest = "^7.4.3"
pytest-cov = "^4.1.0"
mypy = "^1.8.0" mypy = "^1.8.0"
ruff = "^0.2.2" ruff = "^0.2.2"
pre-commit = "^3.6.2" pre-commit = "^3.6.2"
pytest-mock = "^3.12.0"
types-python-jose = "^3.3.4.20240106"
types-passlib = "^1.7.7.20240106" types-passlib = "^1.7.7.20240106"
coverage = "^7.4.3"
[tool.isort]
multi_line_output = 3
include_trailing_comma = true
force_grid_wrap = 0
line_length = 88
[build-system] [build-system]
requires = ["poetry>=0.12"] requires = ["poetry>=0.12"]
build-backend = "poetry.masonry.api" build-backend = "poetry.masonry.api"
[tool.mypy] [tool.mypy]
strict = true strict = true
exclude = ["venv", "alembic"] exclude = ["venv", ".venv", "alembic"]
[tool.ruff] [tool.ruff]
target-version = "py310" target-version = "py310"
exclude = ["alembic"]
[tool.ruff.lint] [tool.ruff.lint]
select = [ select = [
@@ -62,6 +56,7 @@ select = [
"B", # flake8-bugbear "B", # flake8-bugbear
"C4", # flake8-comprehensions "C4", # flake8-comprehensions
"UP", # pyupgrade "UP", # pyupgrade
"ARG001", # unused arguments in functions
] ]
ignore = [ ignore = [
"E501", # line too long, handled by black "E501", # line too long, handled by black
-6
View File
@@ -1,6 +0,0 @@
#!/bin/sh -e
set -x
# Sort imports one per line, so autoflake can remove unused imports
isort --recursive --force-single-line-imports --apply app
sh ./scripts/format.sh
+2 -3
View File
@@ -1,6 +1,5 @@
#!/bin/sh -e #!/bin/sh -e
set -x set -x
autoflake --remove-all-unused-imports --recursive --remove-unused-variables --in-place app --exclude=__init__.py ruff check app scripts --fix
black app ruff format app scripts
isort --recursive --apply app
+1 -1
View File
@@ -4,5 +4,5 @@ set -e
set -x set -x
mypy app mypy app
ruff app ruff check app
ruff format app --check ruff format app --check
-6
View File
@@ -1,6 +0,0 @@
#!/usr/bin/env bash
set -e
set -x
bash scripts/test.sh --cov-report=html "${@}"
+14 -2
View File
@@ -127,11 +127,12 @@ export DOMAIN=fastapi-project.example.com
You can set several variables, like: You can set several variables, like:
* `PROJECT_NAME`: The name of the project, used in the API for the docs and emails.
* `STACK_NAME`: The name of the stack used for Docker Compose labels and project name, this should be different for `staging`, `production`, etc. You could use the same domain replacing dots with dashes, e.g. `fastapi-project-example-com` and `staging-fastapi-project-example-com`.
* `BACKEND_CORS_ORIGINS`: A list of allowed CORS origins separated by commas. * `BACKEND_CORS_ORIGINS`: A list of allowed CORS origins separated by commas.
* `SECRET_KEY`: The secret key for the FastAPI project, used to sign tokens. * `SECRET_KEY`: The secret key for the FastAPI project, used to sign tokens.
* `FIRST_SUPERUSER`: The email of the first superuser, this superuser will be the one that can create new users. * `FIRST_SUPERUSER`: The email of the first superuser, this superuser will be the one that can create new users.
* `FIRST_SUPERUSER_PASSWORD`: The password of the first superuser. * `FIRST_SUPERUSER_PASSWORD`: The password of the first superuser.
* `USERS_OPEN_REGISTRATION`: Whether to allow open registration of new users.
* `SMTP_HOST`: The SMTP server host to send emails, this would come from your email provider (E.g. Mailgun, Sparkpost, Sendgrid, etc). * `SMTP_HOST`: The SMTP server host to send emails, this would come from your email provider (E.g. Mailgun, Sparkpost, Sendgrid, etc).
* `SMTP_USER`: The SMTP server user to send emails. * `SMTP_USER`: The SMTP server user to send emails.
* `SMTP_PASSWORD`: The SMTP server password to send emails. * `SMTP_PASSWORD`: The SMTP server password to send emails.
@@ -143,6 +144,13 @@ You can set several variables, like:
* `POSTGRES_DB`: The database name to use for this application. You can leave the default of `app`. * `POSTGRES_DB`: The database name to use for this application. You can leave the default of `app`.
* `SENTRY_DSN`: The DSN for Sentry, if you are using it. * `SENTRY_DSN`: The DSN for Sentry, if you are using it.
## GitHub Actions Environment Variables
There are some environment variables only used by GitHub Actions that you can configure:
* `LATEST_CHANGES`: Used by the GitHub Action [latest-changes](https://github.com/tiangolo/latest-changes) to automatically add release notes based on the PRs merged. It's a personal access token, read the docs for details.
* `SMOKESHOW_AUTH_KEY`: Used to handle and publish the code coverage using [Smokeshow](https://github.com/samuelcolvin/smokeshow), follow their instructions to create a (free) Smokeshow key.
### Generate secret keys ### Generate secret keys
Some environment variables in the `.env` file have a default value of `changethis`. Some environment variables in the `.env` file have a default value of `changethis`.
@@ -247,11 +255,15 @@ The current Github Actions workflows expect these secrets:
* `DOMAIN_PRODUCTION` * `DOMAIN_PRODUCTION`
* `DOMAIN_STAGING` * `DOMAIN_STAGING`
* `STACK_NAME_PRODUCTION`
* `STACK_NAME_STAGING`
* `EMAILS_FROM_EMAIL` * `EMAILS_FROM_EMAIL`
* `FIRST_SUPERUSER` * `FIRST_SUPERUSER`
* `FIRST_SUPERUSER_PASSWORD` * `FIRST_SUPERUSER_PASSWORD`
* `POSTGRES_PASSWORD` * `POSTGRES_PASSWORD`
* `SECRET_KEY` * `SECRET_KEY`
* `LATEST_CHANGES`
* `SMOKESHOW_AUTH_KEY`
## GitHub Action Deployment Workflows ## GitHub Action Deployment Workflows
@@ -288,4 +300,4 @@ Backend API docs: `https://staging.fastapi-project.example.com/docs`
Backend API base URL: `https://staging.fastapi-project.example.com/api/` Backend API base URL: `https://staging.fastapi-project.example.com/api/`
Adminer: `https://staging.adminer.fastapi-project.example.com` Adminer: `https://adminer.staging.fastapi-project.example.com`
+51 -4
View File
@@ -23,6 +23,7 @@ In that case, you will need to use a fake local domain (`dev.example.com`) and m
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. 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: * 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 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`. * **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`.
@@ -91,6 +92,52 @@ Depending on your workflow, you could want to exclude it from Git, for example i
One way to do it could be to add each environment variable to your CI/CD system, and updating the `docker-compose.yml` file to read that specific env var instead of reading the `.env` file. One way to do it could be to add each environment variable to your CI/CD system, and updating the `docker-compose.yml` file to read that specific env var instead of reading the `.env` file.
### Pre-commits and code linting
we are using a tool called [pre-commit](https://pre-commit.com/) for code linting and formatting.
When you install it, it runs right before making a commit in git. This way it ensures that the code is consistent and formatted even before it is committed.
You can find a file `.pre-commit-config.yaml` with configurations at the root of the project.
#### Install pre-commit to run automatically
`pre-commit` is already part of the dependencies of the project, but you could also install it globally if you prefer to, following [the official pre-commit docs](https://pre-commit.com/).
After having the `pre-commit` tool installed and available, you need to "install" it in the local repository, so that it runs automatically before each commit.
Using Poetry, you could do it with:
```bash
❯ poetry run pre-commit install
pre-commit installed at .git/hooks/pre-commit
```
Now whenever you try to commit, e.g. with:
```bash
git commit
```
...pre-commit will run and check and format the code you are about to commit, and will ask you to add that code (stage it) with git again before committing.
Then you can `git add` the modified/fixed files again and now you can commit.
#### Running pre-commit hooks manually
you can also run `pre-commit` manually on all the files, you can do it using Poetry with:
```bash
❯ poetry run pre-commit run --all-files
check for added large files..............................................Passed
check toml...............................................................Passed
check yaml...............................................................Passed
ruff.....................................................................Passed
ruff-format..............................................................Passed
eslint...................................................................Passed
prettier.................................................................Passed
```
## URLs ## URLs
The production or staging URLs would use these same paths, but with your own domain. The production or staging URLs would use these same paths, but with your own domain.
@@ -103,9 +150,9 @@ Frontend: http://localhost
Backend: http://localhost/api/ Backend: http://localhost/api/
Automatic Interactive Docs (Swagger UI): https://localhost/docs Automatic Interactive Docs (Swagger UI): http://localhost/docs
Automatic Alternative Docs (ReDoc): https://localhost/redoc Automatic Alternative Docs (ReDoc): http://localhost/redoc
Adminer: http://localhost:8080 Adminer: http://localhost:8080
@@ -119,9 +166,9 @@ Frontend: http://localhost.tiangolo.com
Backend: http://localhost.tiangolo.com/api/ Backend: http://localhost.tiangolo.com/api/
Automatic Interactive Docs (Swagger UI): https://localhost.tiangolo.com/docs Automatic Interactive Docs (Swagger UI): http://localhost.tiangolo.com/docs
Automatic Alternative Docs (ReDoc): https://localhost.tiangolo.com/redoc Automatic Alternative Docs (ReDoc): http://localhost.tiangolo.com/redoc
Adminer: http://localhost.tiangolo.com:8080 Adminer: http://localhost.tiangolo.com:8080
+15 -2
View File
@@ -1,8 +1,7 @@
version: "3.3"
services: services:
proxy: proxy:
image: traefik:v2.3 image: traefik:3.0
volumes: volumes:
- /var/run/docker.sock:/var/run/docker.sock - /var/run/docker.sock:/var/run/docker.sock
ports: ports:
@@ -37,6 +36,9 @@ services:
# Dummy https-redirect middleware that doesn't really redirect, only to # Dummy https-redirect middleware that doesn't really redirect, only to
# allow running it locally # allow running it locally
- traefik.http.middlewares.https-redirect.contenttype.autodetect=false - traefik.http.middlewares.https-redirect.contenttype.autodetect=false
networks:
- traefik-public
- default
db: db:
restart: "no" restart: "no"
@@ -60,6 +62,17 @@ services:
INSTALL_DEV: ${INSTALL_DEV-true} INSTALL_DEV: ${INSTALL_DEV-true}
# command: sleep infinity # Infinite loop to keep container alive doing nothing # command: sleep infinity # Infinite loop to keep container alive doing nothing
command: /start-reload.sh command: /start-reload.sh
environment:
SMTP_HOST: "mailcatcher"
SMTP_PORT: "1025"
SMTP_TLS: "false"
EMAILS_FROM_EMAIL: "noreply@example.com"
mailcatcher:
image: schickling/mailcatcher
ports:
- "1080:1080"
- "1025:1025"
frontend: frontend:
restart: "no" restart: "no"
+1 -1
View File
@@ -1,6 +1,6 @@
services: services:
traefik: traefik:
image: traefik:v2.3 image: traefik:3.0
ports: ports:
# Listen on port 80, default for HTTP, necessary to redirect to HTTPS # Listen on port 80, default for HTTP, necessary to redirect to HTTPS
- 80:80 - 80:80
+12 -15
View File
@@ -1,4 +1,3 @@
version: "3.3"
services: services:
db: db:
image: postgres:12 image: postgres:12
@@ -53,7 +52,6 @@ services:
- SECRET_KEY=${SECRET_KEY?Variable not set} - SECRET_KEY=${SECRET_KEY?Variable not set}
- FIRST_SUPERUSER=${FIRST_SUPERUSER?Variable not set} - FIRST_SUPERUSER=${FIRST_SUPERUSER?Variable not set}
- FIRST_SUPERUSER_PASSWORD=${FIRST_SUPERUSER_PASSWORD?Variable not set} - FIRST_SUPERUSER_PASSWORD=${FIRST_SUPERUSER_PASSWORD?Variable not set}
- USERS_OPEN_REGISTRATION=${USERS_OPEN_REGISTRATION}
- SMTP_HOST=${SMTP_HOST} - SMTP_HOST=${SMTP_HOST}
- SMTP_USER=${SMTP_USER} - SMTP_USER=${SMTP_USER}
- SMTP_PASSWORD=${SMTP_PASSWORD} - SMTP_PASSWORD=${SMTP_PASSWORD}
@@ -69,6 +67,7 @@ services:
context: ./backend context: ./backend
args: args:
INSTALL_DEV: ${INSTALL_DEV-false} INSTALL_DEV: ${INSTALL_DEV-false}
platform: linux/amd64 # Patch for M1 Mac
labels: labels:
- traefik.enable=true - traefik.enable=true
- traefik.docker.network=traefik-public - traefik.docker.network=traefik-public
@@ -76,14 +75,20 @@ services:
- traefik.http.services.${STACK_NAME?Variable not set}-backend.loadbalancer.server.port=80 - traefik.http.services.${STACK_NAME?Variable not set}-backend.loadbalancer.server.port=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.rule=(Host(`${DOMAIN?Variable not set}`) || Host(`www.${DOMAIN?Variable not set}`)) && (PathPrefix(`/api`) || PathPrefix(`/docs`) || PathPrefix(`/redoc`))
- traefik.http.routers.${STACK_NAME?Variable not set}-backend-http.entrypoints=http - traefik.http.routers.${STACK_NAME?Variable not set}-backend-http.entrypoints=http
- traefik.http.routers.${STACK_NAME?Variable not set}-backend-https.rule=Host(`${DOMAIN?Variable not set}`, `www.${DOMAIN?Variable not set}`) && PathPrefix(`/api`, `/docs`, `/redoc`) - traefik.http.routers.${STACK_NAME?Variable not set}-backend-https.rule=(Host(`${DOMAIN?Variable not set}`) || Host(`www.${DOMAIN?Variable not set}`)) && (PathPrefix(`/api`) || PathPrefix(`/docs`) || PathPrefix(`/redoc`))
- traefik.http.routers.${STACK_NAME?Variable not set}-backend-https.entrypoints=https - traefik.http.routers.${STACK_NAME?Variable not set}-backend-https.entrypoints=https
- traefik.http.routers.${STACK_NAME?Variable not set}-backend-https.tls=true - traefik.http.routers.${STACK_NAME?Variable not set}-backend-https.tls=true
- traefik.http.routers.${STACK_NAME?Variable not set}-backend-https.tls.certresolver=le - traefik.http.routers.${STACK_NAME?Variable not set}-backend-https.tls.certresolver=le
# Define Traefik Middleware to handle domain with and without "www" to redirect to only one
- 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
- traefik.http.middlewares.${STACK_NAME?Variable not set}-www-redirect.redirectregex.replacement=http$${1}://${DOMAIN?Variable not set}/$${3}
# Enable www redirection for HTTP and HTTPS
- 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-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 - traefik.http.routers.${STACK_NAME?Variable not set}-backend-https.middlewares=${STACK_NAME?Variable not set}-www-redirect
@@ -105,24 +110,16 @@ services:
- traefik.http.services.${STACK_NAME?Variable not set}-frontend.loadbalancer.server.port=80 - traefik.http.services.${STACK_NAME?Variable not set}-frontend.loadbalancer.server.port=80
- traefik.http.routers.${STACK_NAME?Variable not set}-frontend-http.rule=Host(`${DOMAIN?Variable not set}`, `www.${DOMAIN?Variable not set}`) - traefik.http.routers.${STACK_NAME?Variable not set}-frontend-http.rule=Host(`${DOMAIN?Variable not set}`) || Host(`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-http.entrypoints=http
- traefik.http.routers.${STACK_NAME?Variable not set}-frontend-https.rule=Host(`${DOMAIN?Variable not set}`, `www.${DOMAIN?Variable not set}`) - traefik.http.routers.${STACK_NAME?Variable not set}-frontend-https.rule=Host(`${DOMAIN?Variable not set}`) || Host(`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.entrypoints=https
- traefik.http.routers.${STACK_NAME?Variable not set}-frontend-https.tls=true - traefik.http.routers.${STACK_NAME?Variable not set}-frontend-https.tls=true
- traefik.http.routers.${STACK_NAME?Variable not set}-frontend-https.tls.certresolver=le - traefik.http.routers.${STACK_NAME?Variable not set}-frontend-https.tls.certresolver=le
# Handle domain with and without "www" to redirect to only one # Enable www redirection for HTTP and HTTPS
# 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 - 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 - traefik.http.routers.${STACK_NAME?Variable not set}-frontend-http.middlewares=https-redirect,${STACK_NAME?Variable not set}-www-redirect
volumes: volumes:
app-db-data: app-db-data:
-18
View File
@@ -1,18 +0,0 @@
module.exports = {
root: true,
env: { browser: true, es2020: true },
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:react-hooks/recommended',
],
ignorePatterns: ['dist', '.eslintrc.cjs'],
parser: '@typescript-eslint/parser',
plugins: ['react-refresh'],
rules: {
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true },
],
},
}
+4
View File
@@ -23,3 +23,7 @@ openapi.json
*.njsproj *.njsproj
*.sln *.sln
*.sw? *.sw?
/test-results/
/playwright-report/
/blob-report/
/playwright/.cache/
+1 -1
View File
@@ -1 +1 @@
18.x.x 20
-1
View File
@@ -1 +0,0 @@
src/client/
-8
View File
@@ -1,8 +0,0 @@
{
"bracketSpacing": true,
"semi": false,
"singleQuote": true,
"trailingComma": "all",
"printWidth": 80,
"tabWidth": 2
}
+1 -1
View File
@@ -1,5 +1,5 @@
# Stage 0, "build-stage", based on Node.js, to build and compile the frontend # Stage 0, "build-stage", based on Node.js, to build and compile the frontend
FROM node:20 as build-stage FROM node:20 AS build-stage
WORKDIR /app WORKDIR /app
+30
View File
@@ -115,3 +115,33 @@ The frontend code is structured as follows:
* `frontend/src/hooks` - Custom hooks. * `frontend/src/hooks` - Custom hooks.
* `frontend/src/routes` - The different routes of the frontend which include the pages. * `frontend/src/routes` - The different routes of the frontend which include the pages.
* `theme.tsx` - The Chakra UI custom theme. * `theme.tsx` - The Chakra UI custom theme.
## End-to-End Testing with Playwright
The frontend includes initial end-to-end tests using Playwright. To run the tests, you need to have the Docker Compose stack running. Start the stack with the following command:
```bash
docker compose up -d
```
Then, you can run the tests with the following command:
```bash
npx playwright test
```
You can also run your tests in UI mode to see the browser and interact with it running:
```bash
npx playwright test --ui
```
To stop and remove the Docker Compose stack and clean the data created in tests, use the following command:
```bash
docker compose down -v
```
To update the tests, navigate to the tests directory and modify the existing test files or add new ones as needed.
For more information on writing and running Playwright tests, refer to the official [Playwright documentation](https://playwright.dev/docs/intro).
+37
View File
@@ -0,0 +1,37 @@
{
"$schema": "https://biomejs.dev/schemas/1.6.1/schema.json",
"organizeImports": {
"enabled": true
},
"files": {
"ignore": [
"node_modules",
"src/client/",
"src/routeTree.gen.ts",
"playwright.config.ts",
"playwright-report"
]
},
"linter": {
"enabled": true,
"rules": {
"recommended": true,
"suspicious": {
"noExplicitAny": "off",
"noArrayIndexKey": "off"
},
"style": {
"noNonNullAssertion": "off"
}
}
},
"formatter": {
"indentStyle": "space"
},
"javascript": {
"formatter": {
"quoteStyle": "double",
"semicolons": "asNeeded"
}
}
}
+1 -1
View File
@@ -5,7 +5,7 @@
<link rel="icon" type="image/svg+xml" href="/vite.svg" /> <link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Full Stack FastAPI Project</title> <title>Full Stack FastAPI Project</title>
<link rel="icon" type="image/x-icon" href="./src/assets/images/favicon.png" /> <link rel="icon" type="image/x-icon" href="/assets/images/favicon.png" />
</head> </head>
<body> <body>
<div id="root"></div> <div id="root"></div>
+30 -23
View File
@@ -1,29 +1,36 @@
import * as fs from "fs"; import * as fs from "node:fs"
const filePath = "./openapi.json"; async function modifyOpenAPIFile(filePath) {
try {
const data = await fs.promises.readFile(filePath)
const openapiContent = JSON.parse(data)
fs.readFile(filePath, (err, data) => { const paths = openapiContent.paths
const openapiContent = JSON.parse(data); for (const pathKey of Object.keys(paths)) {
if (err) throw err; const pathData = paths[pathKey]
for (const method of Object.keys(pathData)) {
const paths = openapiContent.paths; const operation = pathData[method]
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) { if (operation.tags && operation.tags.length > 0) {
const tag = operation.tags[0]; const tag = operation.tags[0]
const operationId = operation.operationId; const operationId = operation.operationId
const toRemove = `${tag}-`; const toRemove = `${tag}-`
if (operationId.startsWith(toRemove)) { if (operationId.startsWith(toRemove)) {
const newOperationId = operationId.substring(toRemove.length); const newOperationId = operationId.substring(toRemove.length)
operation.operationId = newOperationId; operation.operationId = newOperationId
} }
} }
}); }
}); }
fs.writeFile(filePath, JSON.stringify(openapiContent, null, 2), (err) => {
if (err) throw err; await fs.promises.writeFile(
}); filePath,
}); JSON.stringify(openapiContent, null, 2),
)
console.log("File successfully modified")
} catch (err) {
console.error("Error:", err)
}
}
const filePath = "./openapi.json"
modifyOpenAPIFile(filePath)
+1 -1
View File
@@ -4,7 +4,7 @@ server {
location / { location / {
root /usr/share/nginx/html; root /usr/share/nginx/html;
index index.html index.htm; index index.html index.htm;
try_files $uri $uri/ /index.html =404; try_files $uri /index.html =404;
} }
include /etc/nginx/extra-conf.d/*.conf; include /etc/nginx/extra-conf.d/*.conf;
+490 -2878
View File
File diff suppressed because it is too large Load Diff
+12 -15
View File
@@ -6,42 +6,39 @@
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
"build": "tsc && vite build", "build": "tsc && vite build",
"lint": "eslint ./src --ext .ts,.tsx --fix", "lint": "biome check --apply-unsafe --no-errors-on-unmatched --files-ignore-unknown=true ./",
"format": "prettier --write ./src/**/*.{ts,tsx,js,jsx,json,md} --ignore-path .prettierignore",
"preview": "vite preview", "preview": "vite preview",
"generate-client": "openapi --input ./openapi.json --useOptions --useUnionTypes --output ./src/client --client axios --exportSchemas true" "generate-client": "openapi-ts --input ./openapi.json --output ./src/client --client axios --exportSchemas true && biome format --write ./src/client"
}, },
"dependencies": { "dependencies": {
"@chakra-ui/icons": "2.1.1", "@chakra-ui/icons": "2.1.1",
"@chakra-ui/react": "2.8.2", "@chakra-ui/react": "2.8.2",
"@emotion/react": "11.11.3", "@emotion/react": "11.11.3",
"@emotion/styled": "11.11.0", "@emotion/styled": "11.11.0",
"@tanstack/react-query": "^5.28.14",
"@tanstack/react-query-devtools": "^5.28.14",
"@tanstack/react-router": "1.19.1", "@tanstack/react-router": "1.19.1",
"axios": "1.6.2", "axios": "1.6.2",
"form-data": "4.0.0", "form-data": "4.0.0",
"framer-motion": "10.16.16", "framer-motion": "10.16.16",
"react": "^18.2.0", "react": "^18.2.0",
"react-dom": "^18.2.0", "react-dom": "^18.2.0",
"react-error-boundary": "^4.0.13",
"react-hook-form": "7.49.3", "react-hook-form": "7.49.3",
"react-icons": "5.0.1", "react-icons": "5.0.1"
"react-query": "3.39.3",
"zustand": "4.5.0"
}, },
"devDependencies": { "devDependencies": {
"@biomejs/biome": "1.6.1",
"@hey-api/openapi-ts": "^0.34.1",
"@playwright/test": "^1.45.2",
"@tanstack/router-devtools": "1.19.1", "@tanstack/router-devtools": "1.19.1",
"@tanstack/router-vite-plugin": "1.19.0", "@tanstack/router-vite-plugin": "1.19.0",
"@types/node": "20.10.5", "@types/node": "^20.10.5",
"@types/react": "^18.2.37", "@types/react": "^18.2.37",
"@types/react-dom": "^18.2.15", "@types/react-dom": "^18.2.15",
"@typescript-eslint/eslint-plugin": "^6.10.0",
"@typescript-eslint/parser": "^6.10.0",
"@vitejs/plugin-react-swc": "^3.5.0", "@vitejs/plugin-react-swc": "^3.5.0",
"eslint": "^8.53.0", "dotenv": "^16.4.5",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.4",
"openapi-typescript-codegen": "0.25.0",
"prettier": "3.2.5",
"typescript": "^5.2.2", "typescript": "^5.2.2",
"vite": "^5.0.12" "vite": "^5.0.13"
} }
} }
+92
View File
@@ -0,0 +1,92 @@
import { defineConfig, devices } from '@playwright/test';
/**
* Read environment variables from file.
* https://github.com/motdotla/dotenv
*/
// require('dotenv').config();
/**
* See https://playwright.dev/docs/test-configuration.
*/
export default defineConfig({
testDir: './tests',
/* Run tests in files in parallel */
fullyParallel: true,
/* Fail the build on CI if you accidentally left test.only in the source code. */
forbidOnly: !!process.env.CI,
/* Retry on CI only */
retries: process.env.CI ? 2 : 0,
/* Opt out of parallel tests on CI. */
workers: process.env.CI ? 1 : undefined,
/* Reporter to use. See https://playwright.dev/docs/test-reporters */
reporter: 'html',
/* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
use: {
/* Base URL to use in actions like `await page.goto('/')`. */
baseURL: 'http://localhost:5173',
/* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
trace: 'on-first-retry',
},
/* Configure projects for major browsers */
projects: [
{ name: 'setup', testMatch: /.*\.setup\.ts/ },
{
name: 'chromium',
use: {
...devices['Desktop Chrome'],
storageState: 'playwright/.auth/user.json',
},
dependencies: ['setup'],
},
// {
// name: 'firefox',
// use: {
// ...devices['Desktop Firefox'],
// storageState: 'playwright/.auth/user.json',
// },
// dependencies: ['setup'],
// },
// {
// name: 'webkit',
// use: {
// ...devices['Desktop Safari'],
// storageState: 'playwright/.auth/user.json',
// },
// dependencies: ['setup'],
// },
/* Test against mobile viewports. */
// {
// name: 'Mobile Chrome',
// use: { ...devices['Pixel 5'] },
// },
// {
// name: 'Mobile Safari',
// use: { ...devices['iPhone 12'] },
// },
/* Test against branded browsers. */
// {
// name: 'Microsoft Edge',
// use: { ...devices['Desktop Edge'], channel: 'msedge' },
// },
// {
// name: 'Google Chrome',
// use: { ...devices['Desktop Chrome'], channel: 'chrome' },
// },
],
/* Run your local dev server before starting the tests */
webServer: {
command: 'npm run dev',
url: 'http://localhost:5173',
reuseExistingServer: !process.env.CI,
},
});

Before

Width:  |  Height:  |  Size: 6.2 KiB

After

Width:  |  Height:  |  Size: 6.2 KiB

Before

Width:  |  Height:  |  Size: 4.9 KiB

After

Width:  |  Height:  |  Size: 4.9 KiB

+19 -19
View File
@@ -1,25 +1,25 @@
/* generated using openapi-typescript-codegen -- do no edit */ import type { ApiRequestOptions } from "./ApiRequestOptions"
/* istanbul ignore file */ import type { ApiResult } from "./ApiResult"
/* tslint:disable */
/* eslint-disable */
import type { ApiRequestOptions } from './ApiRequestOptions';
import type { ApiResult } from './ApiResult';
export class ApiError extends Error { export class ApiError extends Error {
public readonly url: string; public readonly url: string
public readonly status: number; public readonly status: number
public readonly statusText: string; public readonly statusText: string
public readonly body: any; public readonly body: unknown
public readonly request: ApiRequestOptions; public readonly request: ApiRequestOptions
constructor(request: ApiRequestOptions, response: ApiResult, message: string) { constructor(
super(message); request: ApiRequestOptions,
response: ApiResult,
message: string,
) {
super(message)
this.name = 'ApiError'; this.name = "ApiError"
this.url = response.url; this.url = response.url
this.status = response.status; this.status = response.status
this.statusText = response.statusText; this.statusText = response.statusText
this.body = response.body; this.body = response.body
this.request = request; this.request = request
} }
} }
+19 -16
View File
@@ -1,17 +1,20 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type ApiRequestOptions = { export type ApiRequestOptions = {
readonly method: 'GET' | 'PUT' | 'POST' | 'DELETE' | 'OPTIONS' | 'HEAD' | 'PATCH'; readonly method:
readonly url: string; | "GET"
readonly path?: Record<string, any>; | "PUT"
readonly cookies?: Record<string, any>; | "POST"
readonly headers?: Record<string, any>; | "DELETE"
readonly query?: Record<string, any>; | "OPTIONS"
readonly formData?: Record<string, any>; | "HEAD"
readonly body?: any; | "PATCH"
readonly mediaType?: string; readonly url: string
readonly responseHeader?: string; readonly path?: Record<string, unknown>
readonly errors?: Record<number, string>; readonly cookies?: Record<string, unknown>
}; readonly headers?: Record<string, unknown>
readonly query?: Record<string, unknown>
readonly formData?: Record<string, unknown>
readonly body?: any
readonly mediaType?: string
readonly responseHeader?: string
readonly errors?: Record<number, string>
}
+7 -11
View File
@@ -1,11 +1,7 @@
/* generated using openapi-typescript-codegen -- do no edit */ export type ApiResult<TData = any> = {
/* istanbul ignore file */ readonly body: TData
/* tslint:disable */ readonly ok: boolean
/* eslint-disable */ readonly status: number
export type ApiResult = { readonly statusText: string
readonly url: string; readonly url: string
readonly ok: boolean; }
readonly status: number;
readonly statusText: string;
readonly body: any;
};
+67 -72
View File
@@ -1,131 +1,126 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export class CancelError extends Error { export class CancelError extends Error {
constructor(message: string) { constructor(message: string) {
super(message); super(message)
this.name = 'CancelError'; this.name = "CancelError"
} }
public get isCancelled(): boolean { public get isCancelled(): boolean {
return true; return true
} }
} }
export interface OnCancel { export interface OnCancel {
readonly isResolved: boolean; readonly isResolved: boolean
readonly isRejected: boolean; readonly isRejected: boolean
readonly isCancelled: boolean; readonly isCancelled: boolean
(cancelHandler: () => void): void; (cancelHandler: () => void): void
} }
export class CancelablePromise<T> implements Promise<T> { export class CancelablePromise<T> implements Promise<T> {
#isResolved: boolean; private _isResolved: boolean
#isRejected: boolean; private _isRejected: boolean
#isCancelled: boolean; private _isCancelled: boolean
readonly #cancelHandlers: (() => void)[]; readonly cancelHandlers: (() => void)[]
readonly #promise: Promise<T>; readonly promise: Promise<T>
#resolve?: (value: T | PromiseLike<T>) => void; private _resolve?: (value: T | PromiseLike<T>) => void
#reject?: (reason?: any) => void; private _reject?: (reason?: unknown) => void
constructor( constructor(
executor: ( executor: (
resolve: (value: T | PromiseLike<T>) => void, resolve: (value: T | PromiseLike<T>) => void,
reject: (reason?: any) => void, reject: (reason?: unknown) => void,
onCancel: OnCancel onCancel: OnCancel,
) => void ) => void,
) { ) {
this.#isResolved = false; this._isResolved = false
this.#isRejected = false; this._isRejected = false
this.#isCancelled = false; this._isCancelled = false
this.#cancelHandlers = []; this.cancelHandlers = []
this.#promise = new Promise<T>((resolve, reject) => { this.promise = new Promise<T>((resolve, reject) => {
this.#resolve = resolve; this._resolve = resolve
this.#reject = reject; this._reject = reject
const onResolve = (value: T | PromiseLike<T>): void => { const onResolve = (value: T | PromiseLike<T>): void => {
if (this.#isResolved || this.#isRejected || this.#isCancelled) { if (this._isResolved || this._isRejected || this._isCancelled) {
return; return
}
this._isResolved = true
if (this._resolve) this._resolve(value)
} }
this.#isResolved = true;
this.#resolve?.(value);
};
const onReject = (reason?: any): void => { const onReject = (reason?: unknown): void => {
if (this.#isResolved || this.#isRejected || this.#isCancelled) { if (this._isResolved || this._isRejected || this._isCancelled) {
return; return
}
this._isRejected = true
if (this._reject) this._reject(reason)
} }
this.#isRejected = true;
this.#reject?.(reason);
};
const onCancel = (cancelHandler: () => void): void => { const onCancel = (cancelHandler: () => void): void => {
if (this.#isResolved || this.#isRejected || this.#isCancelled) { if (this._isResolved || this._isRejected || this._isCancelled) {
return; return
}
this.cancelHandlers.push(cancelHandler)
} }
this.#cancelHandlers.push(cancelHandler);
};
Object.defineProperty(onCancel, 'isResolved', { Object.defineProperty(onCancel, "isResolved", {
get: (): boolean => this.#isResolved, get: (): boolean => this._isResolved,
}); })
Object.defineProperty(onCancel, 'isRejected', { Object.defineProperty(onCancel, "isRejected", {
get: (): boolean => this.#isRejected, get: (): boolean => this._isRejected,
}); })
Object.defineProperty(onCancel, 'isCancelled', { Object.defineProperty(onCancel, "isCancelled", {
get: (): boolean => this.#isCancelled, get: (): boolean => this._isCancelled,
}); })
return executor(onResolve, onReject, onCancel as OnCancel); return executor(onResolve, onReject, onCancel as OnCancel)
}); })
} }
get [Symbol.toStringTag]() { get [Symbol.toStringTag]() {
return "Cancellable Promise"; return "Cancellable Promise"
} }
public then<TResult1 = T, TResult2 = never>( public then<TResult1 = T, TResult2 = never>(
onFulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null, onFulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null,
onRejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null onRejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null,
): Promise<TResult1 | TResult2> { ): Promise<TResult1 | TResult2> {
return this.#promise.then(onFulfilled, onRejected); return this.promise.then(onFulfilled, onRejected)
} }
public catch<TResult = never>( public catch<TResult = never>(
onRejected?: ((reason: any) => TResult | PromiseLike<TResult>) | null onRejected?: ((reason: unknown) => TResult | PromiseLike<TResult>) | null,
): Promise<T | TResult> { ): Promise<T | TResult> {
return this.#promise.catch(onRejected); return this.promise.catch(onRejected)
} }
public finally(onFinally?: (() => void) | null): Promise<T> { public finally(onFinally?: (() => void) | null): Promise<T> {
return this.#promise.finally(onFinally); return this.promise.finally(onFinally)
} }
public cancel(): void { public cancel(): void {
if (this.#isResolved || this.#isRejected || this.#isCancelled) { if (this._isResolved || this._isRejected || this._isCancelled) {
return; return
} }
this.#isCancelled = true; this._isCancelled = true
if (this.#cancelHandlers.length) { if (this.cancelHandlers.length) {
try { try {
for (const cancelHandler of this.#cancelHandlers) { for (const cancelHandler of this.cancelHandlers) {
cancelHandler(); cancelHandler()
} }
} catch (error) { } catch (error) {
console.warn('Cancellation threw an error', error); console.warn("Cancellation threw an error", error)
return; return
} }
} }
this.#cancelHandlers.length = 0; this.cancelHandlers.length = 0
this.#reject?.(new CancelError('Request aborted')); if (this._reject) this._reject(new CancelError("Request aborted"))
} }
public get isCancelled(): boolean { public get isCancelled(): boolean {
return this.#isCancelled; return this._isCancelled
} }
} }
+50 -25
View File
@@ -1,32 +1,57 @@
/* generated using openapi-typescript-codegen -- do no edit */ import type { AxiosRequestConfig, AxiosResponse } from "axios"
/* istanbul ignore file */ import type { ApiRequestOptions } from "./ApiRequestOptions"
/* tslint:disable */ import type { TResult } from "./types"
/* eslint-disable */
import type { ApiRequestOptions } from './ApiRequestOptions';
type Resolver<T> = (options: ApiRequestOptions) => Promise<T>; type Headers = Record<string, string>
type Headers = Record<string, string>; type Middleware<T> = (value: T) => T | Promise<T>
type Resolver<T> = (options: ApiRequestOptions) => Promise<T>
export class Interceptors<T> {
_fns: Middleware<T>[]
constructor() {
this._fns = []
}
eject(fn: Middleware<T>) {
const index = this._fns.indexOf(fn)
if (index !== -1) {
this._fns = [...this._fns.slice(0, index), ...this._fns.slice(index + 1)]
}
}
use(fn: Middleware<T>) {
this._fns = [...this._fns, fn]
}
}
export type OpenAPIConfig = { export type OpenAPIConfig = {
BASE: string; BASE: string
VERSION: string; CREDENTIALS: "include" | "omit" | "same-origin"
WITH_CREDENTIALS: boolean; ENCODE_PATH?: ((path: string) => string) | undefined
CREDENTIALS: 'include' | 'omit' | 'same-origin'; HEADERS?: Headers | Resolver<Headers> | undefined
TOKEN?: string | Resolver<string> | undefined; PASSWORD?: string | Resolver<string> | undefined
USERNAME?: string | Resolver<string> | undefined; RESULT?: TResult
PASSWORD?: string | Resolver<string> | undefined; TOKEN?: string | Resolver<string> | undefined
HEADERS?: Headers | Resolver<Headers> | undefined; USERNAME?: string | Resolver<string> | undefined
ENCODE_PATH?: ((path: string) => string) | undefined; VERSION: string
}; WITH_CREDENTIALS: boolean
interceptors: {
request: Interceptors<AxiosRequestConfig>
response: Interceptors<AxiosResponse>
}
}
export const OpenAPI: OpenAPIConfig = { export const OpenAPI: OpenAPIConfig = {
BASE: '', BASE: "",
VERSION: '0.1.0', CREDENTIALS: "include",
WITH_CREDENTIALS: false, ENCODE_PATH: undefined,
CREDENTIALS: 'include', HEADERS: undefined,
PASSWORD: undefined,
RESULT: "body",
TOKEN: undefined, TOKEN: undefined,
USERNAME: undefined, USERNAME: undefined,
PASSWORD: undefined, VERSION: "0.1.0",
HEADERS: undefined, WITH_CREDENTIALS: false,
ENCODE_PATH: undefined, interceptors: { request: new Interceptors(), response: new Interceptors() },
}; }
+235 -178
View File
@@ -1,283 +1,319 @@
/* generated using openapi-typescript-codegen -- do no edit */ import axios from "axios"
/* istanbul ignore file */ import type {
/* tslint:disable */ AxiosError,
/* eslint-disable */ AxiosInstance,
import axios from 'axios'; AxiosRequestConfig,
import type { AxiosError, AxiosRequestConfig, AxiosResponse, AxiosInstance } from 'axios'; AxiosResponse,
import FormData from 'form-data'; } from "axios"
import { ApiError } from './ApiError'; import { ApiError } from "./ApiError"
import type { ApiRequestOptions } from './ApiRequestOptions'; import type { ApiRequestOptions } from "./ApiRequestOptions"
import type { ApiResult } from './ApiResult'; import type { ApiResult } from "./ApiResult"
import { CancelablePromise } from './CancelablePromise'; import { CancelablePromise } from "./CancelablePromise"
import type { OnCancel } from './CancelablePromise'; import type { OnCancel } from "./CancelablePromise"
import type { OpenAPIConfig } from './OpenAPI'; import type { OpenAPIConfig } from "./OpenAPI"
export const isDefined = <T>(value: T | null | undefined): value is Exclude<T, null | undefined> => { export const isString = (value: unknown): value is string => {
return value !== undefined && value !== null; return typeof value === "string"
}; }
export const isString = (value: any): value is string => { export const isStringWithValue = (value: unknown): value is string => {
return typeof value === 'string'; return isString(value) && value !== ""
}; }
export const isStringWithValue = (value: any): value is string => {
return isString(value) && value !== '';
};
export const isBlob = (value: any): value is Blob => { export const isBlob = (value: any): value is Blob => {
return ( return value instanceof Blob
typeof value === 'object' && }
typeof value.type === 'string' &&
typeof value.stream === 'function' &&
typeof value.arrayBuffer === 'function' &&
typeof value.constructor === 'function' &&
typeof value.constructor.name === 'string' &&
/^(Blob|File)$/.test(value.constructor.name) &&
/^(Blob|File)$/.test(value[Symbol.toStringTag])
);
};
export const isFormData = (value: any): value is FormData => { export const isFormData = (value: unknown): value is FormData => {
return value instanceof FormData; return value instanceof FormData
}; }
export const isSuccess = (status: number): boolean => { export const isSuccess = (status: number): boolean => {
return status >= 200 && status < 300; return status >= 200 && status < 300
}; }
export const base64 = (str: string): string => { export const base64 = (str: string): string => {
try { try {
return btoa(str); return btoa(str)
} catch (err) { } catch (err) {
// @ts-ignore // @ts-ignore
return Buffer.from(str).toString('base64'); return Buffer.from(str).toString("base64")
}
} }
};
export const getQueryString = (params: Record<string, any>): string => { export const getQueryString = (params: Record<string, unknown>): string => {
const qs: string[] = []; const qs: string[] = []
const append = (key: string, value: any) => { const append = (key: string, value: unknown) => {
qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`); qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`)
}; }
const encodePair = (key: string, value: unknown) => {
if (value === undefined || value === null) {
return
}
const process = (key: string, value: any) => {
if (isDefined(value)) {
if (Array.isArray(value)) { if (Array.isArray(value)) {
value.forEach(v => { value.forEach((v) => encodePair(key, v))
process(key, v); } else if (typeof value === "object") {
}); Object.entries(value).forEach(([k, v]) => encodePair(`${key}[${k}]`, v))
} else if (typeof value === 'object') {
Object.entries(value).forEach(([k, v]) => {
process(`${key}[${k}]`, v);
});
} else { } else {
append(key, value); append(key, value)
} }
} }
};
Object.entries(params).forEach(([key, value]) => { Object.entries(params).forEach(([key, value]) => encodePair(key, value))
process(key, value);
});
if (qs.length > 0) { return qs.length ? `?${qs.join("&")}` : ""
return `?${qs.join('&')}`;
} }
return '';
};
const getUrl = (config: OpenAPIConfig, options: ApiRequestOptions): string => { const getUrl = (config: OpenAPIConfig, options: ApiRequestOptions): string => {
const encoder = config.ENCODE_PATH || encodeURI; const encoder = config.ENCODE_PATH || encodeURI
const path = options.url const path = options.url
.replace('{api-version}', config.VERSION) .replace("{api-version}", config.VERSION)
.replace(/{(.*?)}/g, (substring: string, group: string) => { .replace(/{(.*?)}/g, (substring: string, group: string) => {
if (options.path?.hasOwnProperty(group)) { if (options.path?.hasOwnProperty(group)) {
return encoder(String(options.path[group])); return encoder(String(options.path[group]))
} }
return substring; return substring
}); })
const url = `${config.BASE}${path}`; const url = config.BASE + path
if (options.query) { return options.query ? url + getQueryString(options.query) : url
return `${url}${getQueryString(options.query)}`;
} }
return url;
};
export const getFormData = (options: ApiRequestOptions): FormData | undefined => { export const getFormData = (
options: ApiRequestOptions,
): FormData | undefined => {
if (options.formData) { if (options.formData) {
const formData = new FormData(); const formData = new FormData()
const process = (key: string, value: any) => { const process = (key: string, value: unknown) => {
if (isString(value) || isBlob(value)) { if (isString(value) || isBlob(value)) {
formData.append(key, value); formData.append(key, value)
} else { } else {
formData.append(key, JSON.stringify(value)); formData.append(key, JSON.stringify(value))
}
} }
};
Object.entries(options.formData) Object.entries(options.formData)
.filter(([_, value]) => isDefined(value)) .filter(([, value]) => value !== undefined && value !== null)
.forEach(([key, value]) => { .forEach(([key, value]) => {
if (Array.isArray(value)) { if (Array.isArray(value)) {
value.forEach(v => process(key, v)); value.forEach((v) => process(key, v))
} else { } else {
process(key, value); process(key, value)
} }
}); })
return formData; return formData
} }
return undefined; return undefined
};
type Resolver<T> = (options: ApiRequestOptions) => Promise<T>;
export const resolve = async <T>(options: ApiRequestOptions, resolver?: T | Resolver<T>): Promise<T | undefined> => {
if (typeof resolver === 'function') {
return (resolver as Resolver<T>)(options);
} }
return resolver;
};
export const getHeaders = async (config: OpenAPIConfig, options: ApiRequestOptions, formData?: FormData): Promise<Record<string, string>> => { type Resolver<T> = (options: ApiRequestOptions) => Promise<T>
const token = await resolve(options, config.TOKEN);
const username = await resolve(options, config.USERNAME); export const resolve = async <T>(
const password = await resolve(options, config.PASSWORD); options: ApiRequestOptions,
const additionalHeaders = await resolve(options, config.HEADERS); resolver?: T | Resolver<T>,
const formHeaders = typeof formData?.getHeaders === 'function' && formData?.getHeaders() || {} ): Promise<T | undefined> => {
if (typeof resolver === "function") {
return (resolver as Resolver<T>)(options)
}
return resolver
}
export const getHeaders = async (
config: OpenAPIConfig,
options: ApiRequestOptions,
): Promise<Record<string, string>> => {
const [token, username, password, additionalHeaders] = await Promise.all([
resolve(options, config.TOKEN),
resolve(options, config.USERNAME),
resolve(options, config.PASSWORD),
resolve(options, config.HEADERS),
])
const headers = Object.entries({ const headers = Object.entries({
Accept: 'application/json', Accept: "application/json",
...additionalHeaders, ...additionalHeaders,
...options.headers, ...options.headers,
...formHeaders,
}) })
.filter(([_, value]) => isDefined(value)) .filter(([, value]) => value !== undefined && value !== null)
.reduce((headers, [key, value]) => ({ .reduce(
(headers, [key, value]) => ({
...headers, ...headers,
[key]: String(value), [key]: String(value),
}), {} as Record<string, string>); }),
{} as Record<string, string>,
)
if (isStringWithValue(token)) { if (isStringWithValue(token)) {
headers['Authorization'] = `Bearer ${token}`; headers.Authorization = `Bearer ${token}`
} }
if (isStringWithValue(username) && isStringWithValue(password)) { if (isStringWithValue(username) && isStringWithValue(password)) {
const credentials = base64(`${username}:${password}`); const credentials = base64(`${username}:${password}`)
headers['Authorization'] = `Basic ${credentials}`; headers.Authorization = `Basic ${credentials}`
} }
if (options.body) { if (options.body !== undefined) {
if (options.mediaType) { if (options.mediaType) {
headers['Content-Type'] = options.mediaType; headers["Content-Type"] = options.mediaType
} else if (isBlob(options.body)) { } else if (isBlob(options.body)) {
headers['Content-Type'] = options.body.type || 'application/octet-stream'; headers["Content-Type"] = options.body.type || "application/octet-stream"
} else if (isString(options.body)) { } else if (isString(options.body)) {
headers['Content-Type'] = 'text/plain'; headers["Content-Type"] = "text/plain"
} else if (!isFormData(options.body)) { } else if (!isFormData(options.body)) {
headers['Content-Type'] = 'application/json'; headers["Content-Type"] = "application/json"
}
} else if (options.formData !== undefined) {
if (options.mediaType) {
headers["Content-Type"] = options.mediaType
} }
} }
return headers; return headers
}; }
export const getRequestBody = (options: ApiRequestOptions): any => { export const getRequestBody = (options: ApiRequestOptions): unknown => {
if (options.body) { if (options.body) {
return options.body; return options.body
}
return undefined
} }
return undefined;
};
export const sendRequest = async <T>( export const sendRequest = async <T>(
config: OpenAPIConfig, config: OpenAPIConfig,
options: ApiRequestOptions, options: ApiRequestOptions,
url: string, url: string,
body: any, body: unknown,
formData: FormData | undefined, formData: FormData | undefined,
headers: Record<string, string>, headers: Record<string, string>,
onCancel: OnCancel, onCancel: OnCancel,
axiosClient: AxiosInstance axiosClient: AxiosInstance,
): Promise<AxiosResponse<T>> => { ): Promise<AxiosResponse<T>> => {
const source = axios.CancelToken.source(); const controller = new AbortController()
const requestConfig: AxiosRequestConfig = { let requestConfig: AxiosRequestConfig = {
url,
headers,
data: body ?? formData, data: body ?? formData,
headers,
method: options.method, method: options.method,
signal: controller.signal,
url,
withCredentials: config.WITH_CREDENTIALS, withCredentials: config.WITH_CREDENTIALS,
cancelToken: source.token, }
};
onCancel(() => source.cancel('The user aborted a request.')); onCancel(() => controller.abort())
for (const fn of config.interceptors.request._fns) {
requestConfig = await fn(requestConfig)
}
try { try {
return await axiosClient.request(requestConfig); return await axiosClient.request(requestConfig)
} catch (error) { } catch (error) {
const axiosError = error as AxiosError<T>; const axiosError = error as AxiosError<T>
if (axiosError.response) { if (axiosError.response) {
return axiosError.response; return axiosError.response
}
throw error
} }
throw error;
} }
};
export const getResponseHeader = (response: AxiosResponse<any>, responseHeader?: string): string | undefined => { export const getResponseHeader = (
response: AxiosResponse<unknown>,
responseHeader?: string,
): string | undefined => {
if (responseHeader) { if (responseHeader) {
const content = response.headers[responseHeader]; const content = response.headers[responseHeader]
if (isString(content)) { if (isString(content)) {
return content; return content
} }
} }
return undefined; return undefined
}; }
export const getResponseBody = (response: AxiosResponse<any>): any => { export const getResponseBody = (response: AxiosResponse<unknown>): unknown => {
if (response.status !== 204) { if (response.status !== 204) {
return response.data; return response.data
}
return undefined
} }
return undefined;
};
export const catchErrorCodes = (options: ApiRequestOptions, result: ApiResult): void => { export const catchErrorCodes = (
options: ApiRequestOptions,
result: ApiResult,
): void => {
const errors: Record<number, string> = { const errors: Record<number, string> = {
400: 'Bad Request', 400: "Bad Request",
401: 'Unauthorized', 401: "Unauthorized",
403: 'Forbidden', 402: "Payment Required",
404: 'Not Found', 403: "Forbidden",
500: 'Internal Server Error', 404: "Not Found",
502: 'Bad Gateway', 405: "Method Not Allowed",
503: 'Service Unavailable', 406: "Not Acceptable",
407: "Proxy Authentication Required",
408: "Request Timeout",
409: "Conflict",
410: "Gone",
411: "Length Required",
412: "Precondition Failed",
413: "Payload Too Large",
414: "URI Too Long",
415: "Unsupported Media Type",
416: "Range Not Satisfiable",
417: "Expectation Failed",
418: "Im a teapot",
421: "Misdirected Request",
422: "Unprocessable Content",
423: "Locked",
424: "Failed Dependency",
425: "Too Early",
426: "Upgrade Required",
428: "Precondition Required",
429: "Too Many Requests",
431: "Request Header Fields Too Large",
451: "Unavailable For Legal Reasons",
500: "Internal Server Error",
501: "Not Implemented",
502: "Bad Gateway",
503: "Service Unavailable",
504: "Gateway Timeout",
505: "HTTP Version Not Supported",
506: "Variant Also Negotiates",
507: "Insufficient Storage",
508: "Loop Detected",
510: "Not Extended",
511: "Network Authentication Required",
...options.errors, ...options.errors,
} }
const error = errors[result.status]; const error = errors[result.status]
if (error) { if (error) {
throw new ApiError(options, result, error); throw new ApiError(options, result, error)
} }
if (!result.ok) { if (!result.ok) {
const errorStatus = result.status ?? 'unknown'; const errorStatus = result.status ?? "unknown"
const errorStatusText = result.statusText ?? 'unknown'; const errorStatusText = result.statusText ?? "unknown"
const errorBody = (() => { const errorBody = (() => {
try { try {
return JSON.stringify(result.body, null, 2); return JSON.stringify(result.body, null, 2)
} catch (e) { } catch (e) {
return undefined; return undefined
} }
})(); })()
throw new ApiError(options, result, throw new ApiError(
`Generic Error: status: ${errorStatus}; status text: ${errorStatusText}; body: ${errorBody}` options,
); result,
`Generic Error: status: ${errorStatus}; status text: ${errorStatusText}; body: ${errorBody}`,
)
}
} }
};
/** /**
* Request method * Request method
@@ -287,18 +323,39 @@ export const catchErrorCodes = (options: ApiRequestOptions, result: ApiResult):
* @returns CancelablePromise<T> * @returns CancelablePromise<T>
* @throws ApiError * @throws ApiError
*/ */
export const request = <T>(config: OpenAPIConfig, options: ApiRequestOptions, axiosClient: AxiosInstance = axios): CancelablePromise<T> => { export const request = <T>(
config: OpenAPIConfig,
options: ApiRequestOptions,
axiosClient: AxiosInstance = axios,
): CancelablePromise<T> => {
return new CancelablePromise(async (resolve, reject, onCancel) => { return new CancelablePromise(async (resolve, reject, onCancel) => {
try { try {
const url = getUrl(config, options); const url = getUrl(config, options)
const formData = getFormData(options); const formData = getFormData(options)
const body = getRequestBody(options); const body = getRequestBody(options)
const headers = await getHeaders(config, options, formData); const headers = await getHeaders(config, options)
if (!onCancel.isCancelled) { if (!onCancel.isCancelled) {
const response = await sendRequest<T>(config, options, url, body, formData, headers, onCancel, axiosClient); let response = await sendRequest<T>(
const responseBody = getResponseBody(response); config,
const responseHeader = getResponseHeader(response, options.responseHeader); options,
url,
body,
formData,
headers,
onCancel,
axiosClient,
)
for (const fn of config.interceptors.response._fns) {
response = await fn(response)
}
const responseBody = getResponseBody(response)
const responseHeader = getResponseHeader(
response,
options.responseHeader,
)
const result: ApiResult = { const result: ApiResult = {
url, url,
@@ -306,14 +363,14 @@ export const request = <T>(config: OpenAPIConfig, options: ApiRequestOptions, ax
status: response.status, status: response.status,
statusText: response.statusText, statusText: response.statusText,
body: responseHeader ?? responseBody, body: responseHeader ?? responseBody,
}; }
catchErrorCodes(options, result); catchErrorCodes(options, result)
resolve(result.body); resolve(result.body)
} }
} catch (error) { } catch (error) {
reject(error); reject(error)
}
})
} }
});
};
+14
View File
@@ -0,0 +1,14 @@
import type { ApiResult } from "./ApiResult"
export type TResult = "body" | "raw"
export type TApiResponse<T extends TResult, TData> = Exclude<
T,
"raw"
> extends never
? ApiResult<TData>
: ApiResult<TData>["body"]
export type TConfig<T extends TResult> = {
_result?: T
}
+7 -48
View File
@@ -1,49 +1,8 @@
/* generated using openapi-typescript-codegen -- do no edit */ export { ApiError } from "./core/ApiError"
/* istanbul ignore file */ export { CancelablePromise, CancelError } from "./core/CancelablePromise"
/* tslint:disable */ export { OpenAPI } from "./core/OpenAPI"
/* eslint-disable */ export type { OpenAPIConfig } from "./core/OpenAPI"
export { ApiError } from './core/ApiError';
export { CancelablePromise, CancelError } from './core/CancelablePromise';
export { OpenAPI } from './core/OpenAPI';
export type { OpenAPIConfig } from './core/OpenAPI';
export type { Body_login_login_access_token } from './models/Body_login_login_access_token'; export * from "./models"
export type { HTTPValidationError } from './models/HTTPValidationError'; export * from "./schemas"
export type { ItemCreate } from './models/ItemCreate'; export * from "./services"
export type { ItemOut } from './models/ItemOut';
export type { ItemsOut } from './models/ItemsOut';
export type { ItemUpdate } from './models/ItemUpdate';
export type { Message } from './models/Message';
export type { NewPassword } from './models/NewPassword';
export type { Token } from './models/Token';
export type { UpdatePassword } from './models/UpdatePassword';
export type { UserCreate } from './models/UserCreate';
export type { UserCreateOpen } from './models/UserCreateOpen';
export type { UserOut } from './models/UserOut';
export type { UsersOut } from './models/UsersOut';
export type { UserUpdate } from './models/UserUpdate';
export type { UserUpdateMe } from './models/UserUpdateMe';
export type { ValidationError } from './models/ValidationError';
export { $Body_login_login_access_token } from './schemas/$Body_login_login_access_token';
export { $HTTPValidationError } from './schemas/$HTTPValidationError';
export { $ItemCreate } from './schemas/$ItemCreate';
export { $ItemOut } from './schemas/$ItemOut';
export { $ItemsOut } from './schemas/$ItemsOut';
export { $ItemUpdate } from './schemas/$ItemUpdate';
export { $Message } from './schemas/$Message';
export { $NewPassword } from './schemas/$NewPassword';
export { $Token } from './schemas/$Token';
export { $UpdatePassword } from './schemas/$UpdatePassword';
export { $UserCreate } from './schemas/$UserCreate';
export { $UserCreateOpen } from './schemas/$UserCreateOpen';
export { $UserOut } from './schemas/$UserOut';
export { $UsersOut } from './schemas/$UsersOut';
export { $UserUpdate } from './schemas/$UserUpdate';
export { $UserUpdateMe } from './schemas/$UserUpdateMe';
export { $ValidationError } from './schemas/$ValidationError';
export { ItemsService } from './services/ItemsService';
export { LoginService } from './services/LoginService';
export { UsersService } from './services/UsersService';
export { UtilsService } from './services/UtilsService';
+99
View File
@@ -0,0 +1,99 @@
export type Body_login_login_access_token = {
grant_type?: string | null
username: string
password: string
scope?: string
client_id?: string | null
client_secret?: string | null
}
export type HTTPValidationError = {
detail?: Array<ValidationError>
}
export type ItemCreate = {
title: string
description?: string | null
}
export type ItemPublic = {
title: string
description?: string | null
id: string
owner_id: string
}
export type ItemUpdate = {
title?: string | null
description?: string | null
}
export type ItemsPublic = {
data: Array<ItemPublic>
count: number
}
export type Message = {
message: string
}
export type NewPassword = {
token: string
new_password: string
}
export type Token = {
access_token: string
token_type?: string
}
export type UpdatePassword = {
current_password: string
new_password: string
}
export type UserCreate = {
email: string
is_active?: boolean
is_superuser?: boolean
full_name?: string | null
password: string
}
export type UserPublic = {
email: string
is_active?: boolean
is_superuser?: boolean
full_name?: string | null
id: string
}
export type UserRegister = {
email: string
password: string
full_name?: string | null
}
export type UserUpdate = {
email?: string | null
is_active?: boolean
is_superuser?: boolean
full_name?: string | null
password?: string | null
}
export type UserUpdateMe = {
full_name?: string | null
email?: string | null
}
export type UsersPublic = {
data: Array<UserPublic>
count: number
}
export type ValidationError = {
loc: Array<string | number>
msg: string
type: string
}
@@ -1,13 +0,0 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type Body_login_login_access_token = {
grant_type?: (string | null);
username: string;
password: string;
scope?: string;
client_id?: (string | null);
client_secret?: (string | null);
};
@@ -1,10 +0,0 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
import type { ValidationError } from './ValidationError';
export type HTTPValidationError = {
detail?: Array<ValidationError>;
};
-9
View File
@@ -1,9 +0,0 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type ItemCreate = {
title: string;
description?: (string | null);
};
-11
View File
@@ -1,11 +0,0 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type ItemOut = {
title: string;
description?: (string | null);
id: number;
owner_id: number;
};
-9
View File
@@ -1,9 +0,0 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type ItemUpdate = {
title?: (string | null);
description?: (string | null);
};
-11
View File
@@ -1,11 +0,0 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
import type { ItemOut } from './ItemOut';
export type ItemsOut = {
data: Array<ItemOut>;
count: number;
};
-8
View File
@@ -1,8 +0,0 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type Message = {
message: string;
};
@@ -1,9 +0,0 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type NewPassword = {
token: string;
new_password: string;
};
-9
View File
@@ -1,9 +0,0 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type Token = {
access_token: string;
token_type?: string;
};
@@ -1,9 +0,0 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type UpdatePassword = {
current_password: string;
new_password: string;
};
-12
View File
@@ -1,12 +0,0 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type UserCreate = {
email: string;
is_active?: boolean;
is_superuser?: boolean;
full_name?: (string | null);
password: string;
};
@@ -1,10 +0,0 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type UserCreateOpen = {
email: string;
password: string;
full_name?: (string | null);
};
-12
View File
@@ -1,12 +0,0 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type UserOut = {
email: string;
is_active?: boolean;
is_superuser?: boolean;
full_name?: (string | null);
id: number;
};
-12
View File
@@ -1,12 +0,0 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type UserUpdate = {
email?: (string | null);
is_active?: boolean;
is_superuser?: boolean;
full_name?: (string | null);
password?: (string | null);
};
@@ -1,9 +0,0 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type UserUpdateMe = {
full_name?: (string | null);
email?: (string | null);
};
-11
View File
@@ -1,11 +0,0 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
import type { UserOut } from './UserOut';
export type UsersOut = {
data: Array<UserOut>;
count: number;
};
@@ -1,10 +0,0 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type ValidationError = {
loc: Array<(string | number)>;
msg: string;
type: string;
};
+444
View File
@@ -0,0 +1,444 @@
export const $Body_login_login_access_token = {
properties: {
grant_type: {
type: "any-of",
contains: [
{
type: "string",
pattern: "password",
},
{
type: "null",
},
],
},
username: {
type: "string",
isRequired: true,
},
password: {
type: "string",
isRequired: true,
},
scope: {
type: "string",
default: "",
},
client_id: {
type: "any-of",
contains: [
{
type: "string",
},
{
type: "null",
},
],
},
client_secret: {
type: "any-of",
contains: [
{
type: "string",
},
{
type: "null",
},
],
},
},
} as const
export const $HTTPValidationError = {
properties: {
detail: {
type: "array",
contains: {
type: "ValidationError",
},
},
},
} as const
export const $ItemCreate = {
properties: {
title: {
type: "string",
isRequired: true,
maxLength: 255,
minLength: 1,
},
description: {
type: "any-of",
contains: [
{
type: "string",
maxLength: 255,
},
{
type: "null",
},
],
},
},
} as const
export const $ItemPublic = {
properties: {
title: {
type: "string",
isRequired: true,
maxLength: 255,
minLength: 1,
},
description: {
type: "any-of",
contains: [
{
type: "string",
maxLength: 255,
},
{
type: "null",
},
],
},
id: {
type: "string",
isRequired: true,
format: "uuid",
},
owner_id: {
type: "string",
isRequired: true,
format: "uuid",
},
},
} as const
export const $ItemUpdate = {
properties: {
title: {
type: "any-of",
contains: [
{
type: "string",
maxLength: 255,
minLength: 1,
},
{
type: "null",
},
],
},
description: {
type: "any-of",
contains: [
{
type: "string",
maxLength: 255,
},
{
type: "null",
},
],
},
},
} as const
export const $ItemsPublic = {
properties: {
data: {
type: "array",
contains: {
type: "ItemPublic",
},
isRequired: true,
},
count: {
type: "number",
isRequired: true,
},
},
} as const
export const $Message = {
properties: {
message: {
type: "string",
isRequired: true,
},
},
} as const
export const $NewPassword = {
properties: {
token: {
type: "string",
isRequired: true,
},
new_password: {
type: "string",
isRequired: true,
maxLength: 40,
minLength: 8,
},
},
} as const
export const $Token = {
properties: {
access_token: {
type: "string",
isRequired: true,
},
token_type: {
type: "string",
default: "bearer",
},
},
} as const
export const $UpdatePassword = {
properties: {
current_password: {
type: "string",
isRequired: true,
maxLength: 40,
minLength: 8,
},
new_password: {
type: "string",
isRequired: true,
maxLength: 40,
minLength: 8,
},
},
} as const
export const $UserCreate = {
properties: {
email: {
type: "string",
isRequired: true,
format: "email",
maxLength: 255,
},
is_active: {
type: "boolean",
default: true,
},
is_superuser: {
type: "boolean",
default: false,
},
full_name: {
type: "any-of",
contains: [
{
type: "string",
maxLength: 255,
},
{
type: "null",
},
],
},
password: {
type: "string",
isRequired: true,
maxLength: 40,
minLength: 8,
},
},
} as const
export const $UserPublic = {
properties: {
email: {
type: "string",
isRequired: true,
format: "email",
maxLength: 255,
},
is_active: {
type: "boolean",
default: true,
},
is_superuser: {
type: "boolean",
default: false,
},
full_name: {
type: "any-of",
contains: [
{
type: "string",
maxLength: 255,
},
{
type: "null",
},
],
},
id: {
type: "string",
isRequired: true,
format: "uuid",
},
},
} as const
export const $UserRegister = {
properties: {
email: {
type: "string",
isRequired: true,
format: "email",
maxLength: 255,
},
password: {
type: "string",
isRequired: true,
maxLength: 40,
minLength: 8,
},
full_name: {
type: "any-of",
contains: [
{
type: "string",
maxLength: 255,
},
{
type: "null",
},
],
},
},
} as const
export const $UserUpdate = {
properties: {
email: {
type: "any-of",
contains: [
{
type: "string",
format: "email",
maxLength: 255,
},
{
type: "null",
},
],
},
is_active: {
type: "boolean",
default: true,
},
is_superuser: {
type: "boolean",
default: false,
},
full_name: {
type: "any-of",
contains: [
{
type: "string",
maxLength: 255,
},
{
type: "null",
},
],
},
password: {
type: "any-of",
contains: [
{
type: "string",
maxLength: 40,
minLength: 8,
},
{
type: "null",
},
],
},
},
} as const
export const $UserUpdateMe = {
properties: {
full_name: {
type: "any-of",
contains: [
{
type: "string",
maxLength: 255,
},
{
type: "null",
},
],
},
email: {
type: "any-of",
contains: [
{
type: "string",
format: "email",
maxLength: 255,
},
{
type: "null",
},
],
},
},
} as const
export const $UsersPublic = {
properties: {
data: {
type: "array",
contains: {
type: "UserPublic",
},
isRequired: true,
},
count: {
type: "number",
isRequired: true,
},
},
} as const
export const $ValidationError = {
properties: {
loc: {
type: "array",
contains: {
type: "any-of",
contains: [
{
type: "string",
},
{
type: "number",
},
],
},
isRequired: true,
},
msg: {
type: "string",
isRequired: true,
},
type: {
type: "string",
isRequired: true,
},
},
} as const
@@ -1,44 +0,0 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export const $Body_login_login_access_token = {
properties: {
grant_type: {
type: 'any-of',
contains: [{
type: 'string',
pattern: 'password',
}, {
type: 'null',
}],
},
username: {
type: 'string',
isRequired: true,
},
password: {
type: 'string',
isRequired: true,
},
scope: {
type: 'string',
},
client_id: {
type: 'any-of',
contains: [{
type: 'string',
}, {
type: 'null',
}],
},
client_secret: {
type: 'any-of',
contains: [{
type: 'string',
}, {
type: 'null',
}],
},
},
} as const;
@@ -1,14 +0,0 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export const $HTTPValidationError = {
properties: {
detail: {
type: 'array',
contains: {
type: 'ValidationError',
},
},
},
} as const;
@@ -1,20 +0,0 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export const $ItemCreate = {
properties: {
title: {
type: 'string',
isRequired: true,
},
description: {
type: 'any-of',
contains: [{
type: 'string',
}, {
type: 'null',
}],
},
},
} as const;
-28
View File
@@ -1,28 +0,0 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export const $ItemOut = {
properties: {
title: {
type: 'string',
isRequired: true,
},
description: {
type: 'any-of',
contains: [{
type: 'string',
}, {
type: 'null',
}],
},
id: {
type: 'number',
isRequired: true,
},
owner_id: {
type: 'number',
isRequired: true,
},
},
} as const;
@@ -1,24 +0,0 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export const $ItemUpdate = {
properties: {
title: {
type: 'any-of',
contains: [{
type: 'string',
}, {
type: 'null',
}],
},
description: {
type: 'any-of',
contains: [{
type: 'string',
}, {
type: 'null',
}],
},
},
} as const;
-19
View File
@@ -1,19 +0,0 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export const $ItemsOut = {
properties: {
data: {
type: 'array',
contains: {
type: 'ItemOut',
},
isRequired: true,
},
count: {
type: 'number',
isRequired: true,
},
},
} as const;
-12
View File
@@ -1,12 +0,0 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export const $Message = {
properties: {
message: {
type: 'string',
isRequired: true,
},
},
} as const;
@@ -1,16 +0,0 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export const $NewPassword = {
properties: {
token: {
type: 'string',
isRequired: true,
},
new_password: {
type: 'string',
isRequired: true,
},
},
} as const;
-15
View File
@@ -1,15 +0,0 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export const $Token = {
properties: {
access_token: {
type: 'string',
isRequired: true,
},
token_type: {
type: 'string',
},
},
} as const;
@@ -1,16 +0,0 @@
/* generated using openapi-typescript-codegen -- do no edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export const $UpdatePassword = {
properties: {
current_password: {
type: 'string',
isRequired: true,
},
new_password: {
type: 'string',
isRequired: true,
},
},
} as const;

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