Compare commits

..
65 Commits
Author SHA1 Message Date
Wu Clan 07d66137cb Update the version number to 1.11.2 (#940) 2025-11-28 12:28:52 +08:00
Wu Clan f918dcd9c2 Update the fba run CLI command output (#941) 2025-11-28 12:28:18 +08:00
Wu Clan ed4e312cb1 Update code generation interface definitions (#939)
* Update code generation interface definitions

* Update more

* Resume irrelevant updates
2025-11-27 19:20:44 +08:00
Wu Clan 0b539f868e Update task application interface definitions (#938)
* Update the task execution interface definition

* Update more
2025-11-27 19:20:03 +08:00
Wu Clan 8899832de9 Update the files interface filename to file (#937) 2025-11-27 16:26:04 +08:00
Wu Clan d844aa323a Bump dependencies and pre-commits (#936) 2025-11-26 11:14:41 +08:00
Wu Clan ef640b0b5c Fix get column types in code generation (#935) 2025-11-25 18:07:09 +08:00
Wu Clan 4d43c6a3ea Update the i18n language file init location (#934) 2025-11-25 18:06:34 +08:00
Wu Clan 407c848145 Optimize the use of some LRU caches (#932) 2025-11-25 16:48:55 +08:00
Wu Clan d58260a0c0 Add env reqs for plugin install and uninstall (#929) 2025-11-21 17:18:27 +08:00
Dylan 16bcaf963d Add distributed deployment support for snowflake ID (#927)
* feat: Add support distributed deployment for Snowflake

* Update the algorithm implementation

* Remove duplicate codes and update error messages
2025-11-19 12:48:24 +08:00
Wu Clan 551dc51c52 Restore captcha uuid naming in the login params (#928) 2025-11-18 19:58:37 +08:00
Wu Clan 0729061438 Fix typos in data rule sql scripts (#926) 2025-11-18 19:33:24 +08:00
Wu Clan 636d867544 Update the changelog for v1.11.1 (#923) 2025-11-16 21:49:29 +08:00
Wu Clan cf9e5dc4f4 Update user and login security configs (#922)
* Update user and login security configs

* Optimize some code definitions

* Update config comments

* Update the captcha check

* Update the config plugin sql scripts

* Add user password history model to init

* Fix some logic errors

* Add last_password_changed_time to user sql

* Fix user update password

* Fix the dynamic config check

* Update the user sql style
2025-11-16 21:23:36 +08:00
linrong 2c0acb1103 Fix the user list query serialization (#921) 2025-11-16 16:04:22 +08:00
Wu Clan 425bc202c2 Add user social binding and unbinding (#919)
* Add user social binding and unbinding

* Add oauth2 state to binding

* Update oauth2 state

* Fix imports

* Update some interface definitions

* Update the authorization type security
2025-11-15 17:03:30 +08:00
Wu Clan 3b24dca935 Fix missing table in alembic migration (#920) 2025-11-14 17:55:15 +08:00
Wu Clan 98db5f4984 Update the changelog for v1.11.0 (#917) 2025-11-12 13:09:47 +08:00
Wu Clan 2b56168ad0 Refactor foreign keys and relationships to pure logic (#901)
* Refactor foreign keys and relationships to pure logic

* Revert of some changes

* More revert

* Update the user paginate

* Update user create and update

* Update dept select and delete

* Rename the join query functions

* Update select_join_serialize doc and README

* Fix typo in README

* Update the user delete

* Update the user social

* Update the dict plugin crud

* Update the dict plugin version

* Bump dependencies and pre-commits

* Update the code generator plugin crud

* Update the menu crud

* Update the role crud

* Update the data scope and rule crud

* Restore get_paginated to get_select

* Update the code generator plugin version

* Add the py version in pre-commit

* Remove the plugin include parameter config

* Add more cache cleaning TODO

* Rename get_with_relation to get_join

* Add the user cache clear

* Fix known compatibility issues

* Update the version number to 1.11.0

* Fix lint

* Optimize select_join_serialize logic

* Delete cache cleanup comments

* Update the oauth2 plugin version

* Fix user-role table cleanup when user update
2025-11-12 13:06:26 +08:00
Wu Clan b9255815e1 Update the changelog for v1.10.4 (#916) 2025-11-12 12:01:57 +08:00
Wu Clan 93e2f0f5f9 Fix dept and menu table subqueries (#914)
* Fix dept and menu table subqueries

* Fix user cache cleanup when updating data scope
2025-11-11 17:31:59 +08:00
Wu Clan 437c026da9 Fix user cache cleanup when updating data scope (#915) 2025-11-11 17:30:43 +08:00
Wu Clan 316079045f Add user social unbinding account interface (#913) 2025-11-11 17:06:11 +08:00
Wu Clan 5ae9f8b288 Fix the user menu sidebar parsing (#912) 2025-11-11 17:05:43 +08:00
Wu Clan bef65e1baa Fix create and delete department validations (#911) 2025-11-11 17:05:24 +08:00
Wu Clan 87a3cd8a9c Fix user cache cleanup when operating data rules (#910) 2025-11-11 17:05:08 +08:00
Wu Clan be7b742891 Fix typo in the data permission prompt (#909) 2025-11-11 17:04:25 +08:00
Wu Clan 1f98797a60 Update the version number to 1.10.4 (#907) 2025-11-10 23:51:28 +08:00
Wu Clan 8505e32757 Add dept validation to user updates (#906) 2025-11-10 23:50:38 +08:00
Wu Clan 91297d1ccd Fix response status codes in the request logs (#905) 2025-11-08 16:40:16 +08:00
Wu Clan 0ea213edfd Optimize the data permission condition build (#904) 2025-11-08 16:35:15 +08:00
Wu Clan 292f5d7e48 Optimize the request params of the service layer (#903) 2025-11-08 16:24:19 +08:00
Wu Clan ef871f3b5c Add the user social independent enum file (#902) 2025-11-08 16:21:51 +08:00
Wu Clan 6b17da59f8 Update the time column type in the task (#900) 2025-11-06 21:04:51 +08:00
Wu Clan 86d580edd8 Optimize redis batch get and delete operations (#899)
* Optimize redis batch get and delete operations

* Fix typo
2025-11-04 20:59:45 +08:00
Wu Clan cdbe37de7d Update the interface timing accuracy in log (#897)
* Update the interface timing accuracy in log

* Update log request finish
2025-11-04 20:59:00 +08:00
Wu Clan f46974ddd9 Bump fastapi oauth2 from 0.0.1 to 0.0.2 (#896) 2025-11-02 19:42:51 +08:00
Wu Clan a14d4243d9 Update the changelog for v1.10.3 (#895) 2025-10-30 19:28:00 +08:00
Wu Clan 90588ebae8 Add the celery rabbitmq vhost config (#894) 2025-10-30 19:24:46 +08:00
Wu Clan 00bc02f49c Fix the venv pip availability in Linux (#893)
* Fix the venv pip availability in Linux

* Remove pip install timeout
2025-10-30 18:06:58 +08:00
Wu Clan 7e9ce2e691 Fix celery compatibility with psycopg version (#892) 2025-10-30 13:32:12 +08:00
Wu Clan 81ec0f0bd9 Fix import in code generation api template (#891) 2025-10-30 11:14:05 +08:00
Wu Clan 37f9716c4f Bump dependencies to the latest version (#890)
* Bump dependencies to the latest version

* Bump fastapi to the latest version

* Fix lint
2025-10-30 11:07:40 +08:00
Wu Clan 4540cd9338 Update the length style of the model columns (#883)
* Update the length style of the model columns

* Fix opera log table username column length

* Fix login log table username column length
2025-10-23 15:00:28 +08:00
Wu Clan 3c39d2f2f3 Add Google OAuth2 callback to opera log exclusion (#882) 2025-10-22 18:58:36 +08:00
Wu Clan 1e01ffc3d9 Fix the OAuth2 link acquisition in HTTPS (#881)
* Fix the OAuth2 link acquisition in HTTPS

* Update OAUTH2_BACKEND_URL to OAUTH2_BACKEND_BASE_URL
2025-10-22 18:52:40 +08:00
Wu Clan f4b1c43b55 Update the serializer of httpurl type (#879)
* Update the serializer of httpurl type

* Fix lint
2025-10-22 17:30:13 +08:00
Wu Clan 02254938b4 Update the length of the user email column (#878) 2025-10-22 15:58:50 +08:00
Wu Clan 054ff0cab2 Fix the httpurl type compatibility with postgresql (#877)
* Fix the httpurl type compatibility with postgresql

* Add noqa comments
2025-10-22 15:58:42 +08:00
Wu Clan 4f898a0264 Update the container naming in docker scripts (#876) 2025-10-22 15:33:10 +08:00
Wu Clan 70d90c2c01 Add port for fba sever in docker compose (#875) 2025-10-22 15:32:56 +08:00
Wu Clan 964143b30d Fix docker default database env variables (#874) 2025-10-22 14:01:18 +08:00
Wu Clan ce9f59e7d6 Update the changelog for v1.10.2 (#873) 2025-10-21 15:56:46 +08:00
Wu Clan 1f958fc42a Bump fastapi to remove warning for python 3.14 (#872) 2025-10-21 15:45:05 +08:00
Wu Clan e6e53296a8 Optimize sqlalchemy types to simplify compatibility (#870)
* Optimize sqlalchemy types to simplify compatibility

* Update TimeZone type comment
2025-10-20 17:41:00 +08:00
Wu Clan f533de8abd Bump rtoml and uvicorn to support python 3.14 (#871) 2025-10-20 12:42:28 +08:00
Wu Clan adc6427aab Update the changelog for v1.10.1 (#869) 2025-10-18 18:29:30 +08:00
Wu Clan d034b78b48 Bump dependencies to the latest version (#868) 2025-10-18 18:14:43 +08:00
Wu Clan 6deda906de Update the release changelog workflow (#867) 2025-10-18 18:08:29 +08:00
Wu Clan a063105de8 Fix the volume in the docker compose script (#865)
* Fix the volume in the docker compose script

* Fix the db comment
2025-10-18 15:57:29 +08:00
Wu Clan 02b4215742 Fix tasks related to deleting db logs (#863) 2025-10-18 15:49:55 +08:00
Wu Clan 56b6e2113f Update the changelog for v1.10.0 (#864) 2025-10-18 15:44:17 +08:00
Wu Clan 4fcc78eb94 Update the changelog for v1.9.0 (#862) 2025-10-18 15:41:28 +08:00
Wu Clan b28a4d7673 Update the primary database to postgresql (#829)
* Update the primary database to postgresql

* Delete the prints

* Fix lint

* Update models in code generation

* Delete print

* Fix the salt column type
2025-10-17 23:03:17 +08:00
127 changed files with 3868 additions and 2250 deletions
+2
View File
@@ -18,4 +18,6 @@ jobs:
with:
file: CHANGELOG.md
pull_request: true
commit_summary_template: 'Update the changelog for %s'
args: -c
github_token: ${{ secrets.GH_TOKEN }}
+1
View File
@@ -7,3 +7,4 @@ venv/
.python-version
.ruff_cache/
.pytest_cache/
.claude/
+6 -2
View File
@@ -1,13 +1,17 @@
default_language_version:
python: '>= 3.10'
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v6.0.0
hooks:
- id: end-of-file-fixer
- id: check-json
- id: check-yaml
- id: check-toml
- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: v0.14.0
rev: v0.14.6
hooks:
- id: ruff-check
args:
@@ -17,7 +21,7 @@ repos:
- id: ruff-format
- repo: https://github.com/astral-sh/uv-pre-commit
rev: 0.9.0
rev: 0.9.12
hooks:
- id: uv-lock
- id: uv-export
+296 -1
View File
@@ -1,3 +1,167 @@
<a id="v1.11.1"></a>
# [v1.11.1](https://github.com/fastapi-practices/fastapi_best_architecture/releases/tag/v1.11.1) - 2025-11-16
## What's Changed
* Update changelog for v1.11.0 by [@wu-clan](https://github.com/wu-clan) in [#917](https://github.com/fastapi-practices/fastapi_best_architecture/pull/917)
* Fix missing table in alembic migration by [@wu-clan](https://github.com/wu-clan) in [#920](https://github.com/fastapi-practices/fastapi_best_architecture/pull/920)
* Add user social binding and unbinding by [@wu-clan](https://github.com/wu-clan) in [#919](https://github.com/fastapi-practices/fastapi_best_architecture/pull/919)
* Fix the user list query serialization by [@linrong](https://github.com/linrong) in [#921](https://github.com/fastapi-practices/fastapi_best_architecture/pull/921)
* Update user and login security configs by [@wu-clan](https://github.com/wu-clan) in [#922](https://github.com/fastapi-practices/fastapi_best_architecture/pull/922)
## New Contributors
* [@linrong](https://github.com/linrong) made their first contribution in [#921](https://github.com/fastapi-practices/fastapi_best_architecture/pull/921)
**Full Changelog**: https://github.com/fastapi-practices/fastapi_best_architecture/compare/v1.11.0...v1.11.1
## Contributors
<a href="https://github.com/linrong"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2Flinrong.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@linrong"></a>
<a href="https://github.com/wu-clan"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2Fwu-clan.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@wu-clan"></a>
[Changes][v1.11.1]
<a id="v1.11.0"></a>
# [v1.11.0](https://github.com/fastapi-practices/fastapi_best_architecture/releases/tag/v1.11.0) - 2025-11-12
## What's Changed
* Update changelog for v1.10.4 by [@wu-clan](https://github.com/wu-clan) in [#916](https://github.com/fastapi-practices/fastapi_best_architecture/pull/916)
* Refactor foreign keys and relationships to pure logic by [@wu-clan](https://github.com/wu-clan) in [#901](https://github.com/fastapi-practices/fastapi_best_architecture/pull/901)
**Full Changelog**: https://github.com/fastapi-practices/fastapi_best_architecture/compare/v1.10.4...v1.11.0
## Contributors
<a href="https://github.com/wu-clan"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2Fwu-clan.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@wu-clan"></a>
[Changes][v1.11.0]
<a id="v1.10.4"></a>
# [v1.10.4](https://github.com/fastapi-practices/fastapi_best_architecture/releases/tag/v1.10.4) - 2025-11-12
## What's Changed
* Update changelog for v1.10.3 by [@wu-clan](https://github.com/wu-clan) in [#895](https://github.com/fastapi-practices/fastapi_best_architecture/pull/895)
* Bump fastapi oauth2 from 0.0.1 to 0.0.2 by [@wu-clan](https://github.com/wu-clan) in [#896](https://github.com/fastapi-practices/fastapi_best_architecture/pull/896)
* Update the interface timing accuracy in log by [@wu-clan](https://github.com/wu-clan) in [#897](https://github.com/fastapi-practices/fastapi_best_architecture/pull/897)
* Optimize redis batch get and delete operations by [@wu-clan](https://github.com/wu-clan) in [#899](https://github.com/fastapi-practices/fastapi_best_architecture/pull/899)
* Update the time column type in the task by [@wu-clan](https://github.com/wu-clan) in [#900](https://github.com/fastapi-practices/fastapi_best_architecture/pull/900)
* Add the user social independent enum file by [@wu-clan](https://github.com/wu-clan) in [#902](https://github.com/fastapi-practices/fastapi_best_architecture/pull/902)
* Optimize the request params of the service layer by [@wu-clan](https://github.com/wu-clan) in [#903](https://github.com/fastapi-practices/fastapi_best_architecture/pull/903)
* Optimize the data permission condition build by [@wu-clan](https://github.com/wu-clan) in [#904](https://github.com/fastapi-practices/fastapi_best_architecture/pull/904)
* Fix response status codes in the request logs by [@wu-clan](https://github.com/wu-clan) in [#905](https://github.com/fastapi-practices/fastapi_best_architecture/pull/905)
* Add dept validation to user updates by [@wu-clan](https://github.com/wu-clan) in [#906](https://github.com/fastapi-practices/fastapi_best_architecture/pull/906)
* Update the version number to 1.10.4 by [@wu-clan](https://github.com/wu-clan) in [#907](https://github.com/fastapi-practices/fastapi_best_architecture/pull/907)
* Fix typo in the data permission prompt by [@wu-clan](https://github.com/wu-clan) in [#909](https://github.com/fastapi-practices/fastapi_best_architecture/pull/909)
* Fix user cache cleanup when operating data rules by [@wu-clan](https://github.com/wu-clan) in [#910](https://github.com/fastapi-practices/fastapi_best_architecture/pull/910)
* Fix create and delete department validations by [@wu-clan](https://github.com/wu-clan) in [#911](https://github.com/fastapi-practices/fastapi_best_architecture/pull/911)
* Fix the user menu sidebar parsing by [@wu-clan](https://github.com/wu-clan) in [#912](https://github.com/fastapi-practices/fastapi_best_architecture/pull/912)
* Add user social unbinding account interface by [@wu-clan](https://github.com/wu-clan) in [#913](https://github.com/fastapi-practices/fastapi_best_architecture/pull/913)
* Fix user cache cleanup when updating data scope by [@wu-clan](https://github.com/wu-clan) in [#915](https://github.com/fastapi-practices/fastapi_best_architecture/pull/915)
* Fix dept and menu table subqueries by [@wu-clan](https://github.com/wu-clan) in [#914](https://github.com/fastapi-practices/fastapi_best_architecture/pull/914)
**Full Changelog**: https://github.com/fastapi-practices/fastapi_best_architecture/compare/v1.10.3...v1.10.4
## Contributors
<a href="https://github.com/wu-clan"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2Fwu-clan.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@wu-clan"></a>
[Changes][v1.10.4]
<a id="v1.10.3"></a>
# [v1.10.3](https://github.com/fastapi-practices/fastapi_best_architecture/releases/tag/v1.10.3) - 2025-10-30
## What's Changed
* Update changelog for v1.10.2 by [@wu-clan](https://github.com/wu-clan) in [#873](https://github.com/fastapi-practices/fastapi_best_architecture/pull/873)
* Fix docker default database env variables by [@wu-clan](https://github.com/wu-clan) in [#874](https://github.com/fastapi-practices/fastapi_best_architecture/pull/874)
* Add port for fba sever in docker compose by [@wu-clan](https://github.com/wu-clan) in [#875](https://github.com/fastapi-practices/fastapi_best_architecture/pull/875)
* Update the container naming in docker scripts by [@wu-clan](https://github.com/wu-clan) in [#876](https://github.com/fastapi-practices/fastapi_best_architecture/pull/876)
* Fix the httpurl type compatibility with postgresql by [@wu-clan](https://github.com/wu-clan) in [#877](https://github.com/fastapi-practices/fastapi_best_architecture/pull/877)
* Update the default length of user email column by [@wu-clan](https://github.com/wu-clan) in [#878](https://github.com/fastapi-practices/fastapi_best_architecture/pull/878)
* Update the serializer of httpurl type by [@wu-clan](https://github.com/wu-clan) in [#879](https://github.com/fastapi-practices/fastapi_best_architecture/pull/879)
* Fix the OAuth2 link acquisition in HTTPS by [@wu-clan](https://github.com/wu-clan) in [#881](https://github.com/fastapi-practices/fastapi_best_architecture/pull/881)
* Add Google OAuth2 callback to opera log exclusion by [@wu-clan](https://github.com/wu-clan) in [#882](https://github.com/fastapi-practices/fastapi_best_architecture/pull/882)
* Update the length style of the model columns by [@wu-clan](https://github.com/wu-clan) in [#883](https://github.com/fastapi-practices/fastapi_best_architecture/pull/883)
* Bump dependencies to the latest version by [@wu-clan](https://github.com/wu-clan) in [#890](https://github.com/fastapi-practices/fastapi_best_architecture/pull/890)
* Fix import in code generation api template by [@wu-clan](https://github.com/wu-clan) in [#891](https://github.com/fastapi-practices/fastapi_best_architecture/pull/891)
* Fix celery compatibility with psycopg version by [@wu-clan](https://github.com/wu-clan) in [#892](https://github.com/fastapi-practices/fastapi_best_architecture/pull/892)
* Fix the venv pip availability in Linux by [@wu-clan](https://github.com/wu-clan) in [#893](https://github.com/fastapi-practices/fastapi_best_architecture/pull/893)
* Add the celery rabbitmq vhost config by [@wu-clan](https://github.com/wu-clan) in [#894](https://github.com/fastapi-practices/fastapi_best_architecture/pull/894)
**Full Changelog**: https://github.com/fastapi-practices/fastapi_best_architecture/compare/v1.10.2...v1.10.3
## Contributors
<a href="https://github.com/wu-clan"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2Fwu-clan.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@wu-clan"></a>
[Changes][v1.10.3]
<a id="v1.10.2"></a>
# [v1.10.2](https://github.com/fastapi-practices/fastapi_best_architecture/releases/tag/v1.10.2) - 2025-10-21
## What's Changed
* Update the changelog for v1.10.1 by [@wu-clan](https://github.com/wu-clan) in [#869](https://github.com/fastapi-practices/fastapi_best_architecture/pull/869)
* Bump rtoml and uvicorn to support python 3.14 by [@wu-clan](https://github.com/wu-clan) in [#871](https://github.com/fastapi-practices/fastapi_best_architecture/pull/871)
* Optimize sqlalchemy types to simplify compatibility by [@wu-clan](https://github.com/wu-clan) in [#870](https://github.com/fastapi-practices/fastapi_best_architecture/pull/870)
* Bump fastapi to remove warning for python 3.14 by [@wu-clan](https://github.com/wu-clan) in [#872](https://github.com/fastapi-practices/fastapi_best_architecture/pull/872)
**Full Changelog**: https://github.com/fastapi-practices/fastapi_best_architecture/compare/v1.10.1...v1.10.2
## Contributors
<a href="https://github.com/wu-clan"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2Fwu-clan.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@wu-clan"></a>
[Changes][v1.10.2]
<a id="v1.10.1"></a>
# [v1.10.1](https://github.com/fastapi-practices/fastapi_best_architecture/releases/tag/v1.10.1) - 2025-10-18
## What's Changed
* Update the changelog for v1.10.0 by [@wu-clan](https://github.com/wu-clan) in [#864](https://github.com/fastapi-practices/fastapi_best_architecture/pull/864)
* Fix tasks related to deleting db logs by [@wu-clan](https://github.com/wu-clan) in [#863](https://github.com/fastapi-practices/fastapi_best_architecture/pull/863)
* Fix the volume in the docker compose script by [@wu-clan](https://github.com/wu-clan) in [#865](https://github.com/fastapi-practices/fastapi_best_architecture/pull/865)
* Update the release changelog workflow by [@wu-clan](https://github.com/wu-clan) in [#867](https://github.com/fastapi-practices/fastapi_best_architecture/pull/867)
* Bump dependencies to the latest version by [@wu-clan](https://github.com/wu-clan) in [#868](https://github.com/fastapi-practices/fastapi_best_architecture/pull/868)
**Full Changelog**: https://github.com/fastapi-practices/fastapi_best_architecture/compare/v1.10.0...v1.10.1
## Contributors
<a href="https://github.com/wu-clan"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2Fwu-clan.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@wu-clan"></a>
[Changes][v1.10.1]
<a id="v1.10.0"></a>
# [v1.10.0](https://github.com/fastapi-practices/fastapi_best_architecture/releases/tag/v1.10.0) - 2025-10-17
## What's Changed
* Fix the import table cli command by [@wu-clan](https://github.com/wu-clan) in [#860](https://github.com/fastapi-practices/fastapi_best_architecture/pull/860)
* Update unique judgment logic for dict data by [@wu-clan](https://github.com/wu-clan) in [#859](https://github.com/fastapi-practices/fastapi_best_architecture/pull/859)
* Fix the api ninja in code generation by [@wu-clan](https://github.com/wu-clan) in [#858](https://github.com/fastapi-practices/fastapi_best_architecture/pull/858)
* Fix dict plugin pgsql init script missing by [@wu-clan](https://github.com/wu-clan) in [#857](https://github.com/fastapi-practices/fastapi_best_architecture/pull/857)
* Update the changelog for v1.9.0 by [@wu-clan](https://github.com/wu-clan) in [#856](https://github.com/fastapi-practices/fastapi_best_architecture/pull/856)
* Fix ctx in validation exception handler by [@wu-clan](https://github.com/wu-clan) in [#861](https://github.com/fastapi-practices/fastapi_best_architecture/pull/861)
* Update the primary database to postgresql by [@wu-clan](https://github.com/wu-clan) in [#829](https://github.com/fastapi-practices/fastapi_best_architecture/pull/829)
**Full Changelog**: https://github.com/fastapi-practices/fastapi_best_architecture/compare/v1.9.0...v1.10.0
## Contributors
<a href="https://github.com/wu-clan"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2Fwu-clan.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@wu-clan"></a>
[Changes][v1.10.0]
<a id="v1.9.0"></a>
# [v1.9.0](https://github.com/fastapi-practices/fastapi_best_architecture/releases/tag/v1.9.0) - 2025-10-16
@@ -13,6 +177,10 @@
**Full Changelog**: https://github.com/fastapi-practices/fastapi_best_architecture/compare/v1.8.3...v1.9.0
## Contributors
<a href="https://github.com/wu-clan"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2Fwu-clan.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@wu-clan"></a>
[Changes][v1.9.0]
@@ -31,6 +199,10 @@
**Full Changelog**: https://github.com/fastapi-practices/fastapi_best_architecture/compare/v1.8.2...v1.8.3
## Contributors
<a href="https://github.com/wu-clan"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2Fwu-clan.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@wu-clan"></a>
[Changes][v1.8.3]
@@ -66,6 +238,12 @@
**Full Changelog**: https://github.com/fastapi-practices/fastapi_best_architecture/compare/v1.8.1...v1.8.2
## Contributors
<a href="https://github.com/MortyZhaoy"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2FMortyZhaoy.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@MortyZhaoy"></a>
<a href="https://github.com/byte-voyager"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2Fbyte-voyager.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@byte-voyager"></a>
<a href="https://github.com/wu-clan"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2Fwu-clan.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@wu-clan"></a>
[Changes][v1.8.2]
@@ -110,6 +288,15 @@
**Full Changelog**: https://github.com/fastapi-practices/fastapi_best_architecture/compare/v1.8.0...v1.8.1
## Contributors
<a href="https://github.com/IAseven"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2FIAseven.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@IAseven"></a>
<a href="https://github.com/siyue-wang"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2Fsiyue-wang.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@siyue-wang"></a>
<a href="https://github.com/wu-clan"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2Fwu-clan.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@wu-clan"></a>
<a href="https://github.com/wuyao4"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2Fwuyao4.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@wuyao4"></a>
<a href="https://github.com/yanlingsishao"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2Fyanlingsishao.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@yanlingsishao"></a>
<a href="https://github.com/yzbf-lin"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2Fyzbf-lin.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@yzbf-lin"></a>
[Changes][v1.8.1]
@@ -154,6 +341,12 @@
**Full Changelog**: https://github.com/fastapi-practices/fastapi_best_architecture/compare/v1.7.0...v1.8.0
## Contributors
<a href="https://github.com/IAseven"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2FIAseven.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@IAseven"></a>
<a href="https://github.com/downdawn"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2Fdowndawn.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@downdawn"></a>
<a href="https://github.com/wu-clan"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2Fwu-clan.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@wu-clan"></a>
[Changes][v1.8.0]
@@ -189,6 +382,10 @@
**Full Changelog**: https://github.com/fastapi-practices/fastapi_best_architecture/compare/v1.6.0...v1.7.0
## Contributors
<a href="https://github.com/wu-clan"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2Fwu-clan.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@wu-clan"></a>
[Changes][v1.7.0]
@@ -212,6 +409,10 @@
**Full Changelog**: https://github.com/fastapi-practices/fastapi_best_architecture/compare/v1.5.2...v1.6.0
## Contributors
<a href="https://github.com/wu-clan"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2Fwu-clan.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@wu-clan"></a>
[Changes][v1.6.0]
@@ -238,6 +439,11 @@
**Full Changelog**: https://github.com/fastapi-practices/fastapi_best_architecture/compare/v1.5.1...v1.5.2
## Contributors
<a href="https://github.com/downdawn"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2Fdowndawn.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@downdawn"></a>
<a href="https://github.com/wu-clan"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2Fwu-clan.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@wu-clan"></a>
[Changes][v1.5.2]
@@ -254,6 +460,11 @@
**Full Changelog**: https://github.com/fastapi-practices/fastapi_best_architecture/compare/v1.5.0...v1.5.1
## Contributors
<a href="https://github.com/downdawn"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2Fdowndawn.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@downdawn"></a>
<a href="https://github.com/wu-clan"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2Fwu-clan.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@wu-clan"></a>
[Changes][v1.5.1]
@@ -277,6 +488,10 @@
**Full Changelog**: https://github.com/fastapi-practices/fastapi_best_architecture/compare/v1.4.3...v1.5.0
## Contributors
<a href="https://github.com/wu-clan"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2Fwu-clan.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@wu-clan"></a>
[Changes][v1.5.0]
@@ -298,6 +513,10 @@
**Full Changelog**: https://github.com/fastapi-practices/fastapi_best_architecture/compare/v1.4.2...v1.4.3
## Contributors
<a href="https://github.com/wu-clan"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2Fwu-clan.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@wu-clan"></a>
[Changes][v1.4.3]
@@ -319,6 +538,11 @@
**Full Changelog**: https://github.com/fastapi-practices/fastapi_best_architecture/compare/v1.4.1...v1.4.2
## Contributors
<a href="https://github.com/huyuwei1996"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2Fhuyuwei1996.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@huyuwei1996"></a>
<a href="https://github.com/wu-clan"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2Fwu-clan.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@wu-clan"></a>
[Changes][v1.4.2]
@@ -336,6 +560,10 @@
**Full Changelog**: https://github.com/fastapi-practices/fastapi_best_architecture/compare/v1.4.0...v1.4.1
## Contributors
<a href="https://github.com/wu-clan"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2Fwu-clan.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@wu-clan"></a>
[Changes][v1.4.1]
@@ -357,6 +585,10 @@
**Full Changelog**: https://github.com/fastapi-practices/fastapi_best_architecture/compare/v1.3.0...v1.4.0
## Contributors
<a href="https://github.com/wu-clan"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2Fwu-clan.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@wu-clan"></a>
[Changes][v1.4.0]
@@ -374,6 +606,10 @@
**Full Changelog**: https://github.com/fastapi-practices/fastapi_best_architecture/compare/v1.2.0...v1.3.0
## Contributors
<a href="https://github.com/wu-clan"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2Fwu-clan.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@wu-clan"></a>
[Changes][v1.3.0]
@@ -391,6 +627,10 @@
**Full Changelog**: https://github.com/fastapi-practices/fastapi_best_architecture/compare/v1.1.2...v1.2.0
## Contributors
<a href="https://github.com/wu-clan"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2Fwu-clan.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@wu-clan"></a>
[Changes][v1.2.0]
@@ -408,6 +648,10 @@
**Full Changelog**: https://github.com/fastapi-practices/fastapi_best_architecture/compare/v1.1.1...v1.1.2
## Contributors
<a href="https://github.com/wu-clan"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2Fwu-clan.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@wu-clan"></a>
[Changes][v1.1.2]
@@ -422,6 +666,10 @@
**Full Changelog**: https://github.com/fastapi-practices/fastapi_best_architecture/compare/v1.1.0...v1.1.1
## Contributors
<a href="https://github.com/wu-clan"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2Fwu-clan.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@wu-clan"></a>
[Changes][v1.1.1]
@@ -441,6 +689,11 @@
**Full Changelog**: https://github.com/fastapi-practices/fastapi_best_architecture/compare/v1.0.5...v1.1.0
## Contributors
<a href="https://github.com/huyuwei1996"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2Fhuyuwei1996.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@huyuwei1996"></a>
<a href="https://github.com/wu-clan"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2Fwu-clan.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@wu-clan"></a>
[Changes][v1.1.0]
@@ -465,6 +718,10 @@
**Full Changelog**: https://github.com/fastapi-practices/fastapi_best_architecture/compare/v1.0.4...v1.0.5
## Contributors
<a href="https://github.com/wu-clan"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2Fwu-clan.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@wu-clan"></a>
[Changes][v1.0.5]
@@ -493,6 +750,12 @@
**Full Changelog**: https://github.com/fastapi-practices/fastapi_best_architecture/compare/v1.0.3...v1.0.4
## Contributors
<a href="https://github.com/PoetryL"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2FPoetryL.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@PoetryL"></a>
<a href="https://github.com/ThankCat"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2FThankCat.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@ThankCat"></a>
<a href="https://github.com/wu-clan"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2Fwu-clan.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@wu-clan"></a>
[Changes][v1.0.4]
@@ -511,6 +774,11 @@
**Full Changelog**: https://github.com/fastapi-practices/fastapi_best_architecture/compare/v1.0.2...v1.0.3
## Contributors
<a href="https://github.com/huyuwei1996"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2Fhuyuwei1996.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@huyuwei1996"></a>
<a href="https://github.com/wu-clan"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2Fwu-clan.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@wu-clan"></a>
[Changes][v1.0.3]
@@ -526,6 +794,10 @@
**Full Changelog**: https://github.com/fastapi-practices/fastapi_best_architecture/compare/v1.0.1...v1.0.2
## Contributors
<a href="https://github.com/wu-clan"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2Fwu-clan.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@wu-clan"></a>
[Changes][v1.0.2]
@@ -545,6 +817,11 @@
**Full Changelog**: https://github.com/fastapi-practices/fastapi_best_architecture/compare/v1.0.0...v1.0.1
## Contributors
<a href="https://github.com/huyuwei1996"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2Fhuyuwei1996.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@huyuwei1996"></a>
<a href="https://github.com/wu-clan"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2Fwu-clan.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@wu-clan"></a>
[Changes][v1.0.1]
@@ -870,9 +1147,27 @@
**Full Changelog**: https://github.com/fastapi-practices/fastapi_best_architecture/commits/v1.0.0
## Contributors
<a href="https://github.com/Meepoljdx"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2FMeepoljdx.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@Meepoljdx"></a>
<a href="https://github.com/dependabot"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2Fdependabot.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@dependabot"></a>
<a href="https://github.com/dividduang"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2Fdividduang.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@dividduang"></a>
<a href="https://github.com/downdawn"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2Fdowndawn.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@downdawn"></a>
<a href="https://github.com/obrua"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2Fobrua.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@obrua"></a>
<a href="https://github.com/qhp13654398483"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2Fqhp13654398483.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@qhp13654398483"></a>
<a href="https://github.com/wu-clan"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2Fwu-clan.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@wu-clan"></a>
<a href="https://github.com/yshan2028"><img src="https://wsrv.nl/?url=https%3A%2F%2Fgithub.com%2Fyshan2028.png&w=128&h=128&fit=cover&mask=circle" width="64" height="64" alt="@yshan2028"></a>
[Changes][v1.0.0]
[v1.11.1]: https://github.com/fastapi-practices/fastapi_best_architecture/compare/v1.11.0...v1.11.1
[v1.11.0]: https://github.com/fastapi-practices/fastapi_best_architecture/compare/v1.10.4...v1.11.0
[v1.10.4]: https://github.com/fastapi-practices/fastapi_best_architecture/compare/v1.10.3...v1.10.4
[v1.10.3]: https://github.com/fastapi-practices/fastapi_best_architecture/compare/v1.10.2...v1.10.3
[v1.10.2]: https://github.com/fastapi-practices/fastapi_best_architecture/compare/v1.10.1...v1.10.2
[v1.10.1]: https://github.com/fastapi-practices/fastapi_best_architecture/compare/v1.10.0...v1.10.1
[v1.10.0]: https://github.com/fastapi-practices/fastapi_best_architecture/compare/v1.9.0...v1.10.0
[v1.9.0]: https://github.com/fastapi-practices/fastapi_best_architecture/compare/v1.8.3...v1.9.0
[v1.8.3]: https://github.com/fastapi-practices/fastapi_best_architecture/compare/v1.8.2...v1.8.3
[v1.8.2]: https://github.com/fastapi-practices/fastapi_best_architecture/compare/v1.8.1...v1.8.2
@@ -899,4 +1194,4 @@
[v1.0.1]: https://github.com/fastapi-practices/fastapi_best_architecture/compare/v1.0.0...v1.0.1
[v1.0.0]: https://github.com/fastapi-practices/fastapi_best_architecture/tree/v1.0.0
<!-- Generated by https://github.com/rhysd/changelog-from-release v3.9.0 -->
<!-- Generated by https://github.com/rhysd/changelog-from-release v3.9.1 -->
+6 -6
View File
@@ -1,5 +1,5 @@
# Select the image to build based on SERVER_TYPE, defaulting to fastapi_server, or docker-compose build args
ARG SERVER_TYPE=fastapi_server
# Select the image to build based on SERVER_TYPE, defaulting to fba_server, or docker-compose build args
ARG SERVER_TYPE=fba_server
# === Python environment from uv ===
FROM ghcr.io/astral-sh/uv:python3.10-bookworm-slim AS builder
@@ -41,22 +41,22 @@ COPY deploy/backend/supervisord.conf /etc/supervisor/supervisord.conf
WORKDIR /fba/backend
# === FastAPI server image ===
FROM base_server AS fastapi_server
FROM base_server AS fba_server
COPY deploy/backend/fba_server.conf /etc/supervisor/conf.d/
RUN mkdir -p /var/log/fastapi_server
RUN mkdir -p /var/log/fba
EXPOSE 8001
CMD ["/usr/local/bin/granian", "main:app", "--interface", "asgi", "--host", "0.0.0.0", "--port","8000"]
# === Celery server image ===
FROM base_server AS celery
FROM base_server AS fba_celery
COPY deploy/backend/fba_celery.conf /etc/supervisor/conf.d/
RUN mkdir -p /var/log/celery
RUN mkdir -p /var/log/fba
RUN chmod +x celery-start.sh
+3 -3
View File
@@ -1,10 +1,10 @@
# Env
ENVIRONMENT='dev'
# Database
DATABASE_TYPE='mysql'
DATABASE_TYPE='postgresql'
DATABASE_HOST='127.0.0.1'
DATABASE_PORT=3306
DATABASE_USER='root'
DATABASE_PORT=5432
DATABASE_USER='postgres'
DATABASE_PASSWORD='123456'
# Redis
REDIS_HOST='127.0.0.1'
+3 -3
View File
@@ -50,10 +50,10 @@
4. Format and Lint
Auto-formatting and lint via `pre-commit`
Auto-formatting and lint via `prek`
```shell
pre-commit run --all-files
prek run --all-files
```
5. Commit and push
@@ -78,6 +78,6 @@
- `scripts/format.sh`: Perform ruff format check
- `scripts/lint.sh`: Perform pre-commit formatting
- `scripts/lint.sh`: Perform prek formatting
- `scripts/export.sh`: Execute uv export dependency package
+1 -7
View File
@@ -1,7 +1 @@
from backend.common.i18n import i18n
__version__ = '1.8.2'
# 初始化 i18n
i18n.load_locales()
__version__ = '1.11.2'
-1
View File
@@ -12,7 +12,6 @@ def get_app_models() -> list[type]:
apps = [d for d in list_dirs if os.path.isdir(os.path.join(app_path, d)) and d != '__pycache__']
objs = []
for app in apps:
module_path = f'backend.app.{app}.model'
obj = get_model_objects(module_path)
+1 -1
View File
@@ -20,7 +20,7 @@ async def login_swagger(
db: CurrentSessionTransaction, obj: Annotated[HTTPBasicCredentials, Depends()]
) -> GetSwaggerToken:
token, user = await auth_service.swagger_login(db=db, obj=obj)
return GetSwaggerToken(access_token=token, user=user)
return GetSwaggerToken(access_token=token, user=user) # type: ignore
@router.post(
+15 -11
View File
@@ -1,4 +1,4 @@
from uuid import uuid4
import uuid
from fast_captcha import img_captcha
from fastapi import APIRouter, Depends
@@ -8,7 +8,9 @@ from starlette.concurrency import run_in_threadpool
from backend.app.admin.schema.captcha import GetCaptchaDetail
from backend.common.response.response_schema import ResponseSchemaModel, response_base
from backend.core.conf import settings
from backend.database.db import CurrentSession
from backend.database.redis import redis_client
from backend.utils.dynamic_config import load_login_config
router = APIRouter()
@@ -18,17 +20,19 @@ router = APIRouter()
summary='获取登录验证码',
dependencies=[Depends(RateLimiter(times=5, seconds=10))],
)
async def get_captcha() -> ResponseSchemaModel[GetCaptchaDetail]:
"""
此接口可能存在性能损耗,尽管是异步接口,但是验证码生成是IO密集型任务,使用线程池尽量减少性能损耗
"""
img_type: str = 'base64'
img, code = await run_in_threadpool(img_captcha, img_byte=img_type)
uuid = str(uuid4())
async def get_captcha(db: CurrentSession) -> ResponseSchemaModel[GetCaptchaDetail]:
await load_login_config(db)
img, code = await run_in_threadpool(img_captcha, img_byte='base64')
captcha_uuid = str(uuid.uuid4())
await redis_client.set(
f'{settings.CAPTCHA_LOGIN_REDIS_PREFIX}:{uuid}',
f'{settings.LOGIN_CAPTCHA_REDIS_PREFIX}:{captcha_uuid}',
code,
ex=settings.CAPTCHA_LOGIN_EXPIRE_SECONDS,
ex=settings.LOGIN_CAPTCHA_EXPIRE_SECONDS,
)
data = GetCaptchaDetail(
is_enabled=settings.LOGIN_CAPTCHA_ENABLED,
expire_seconds=settings.LOGIN_CAPTCHA_EXPIRE_SECONDS,
uuid=captcha_uuid,
image=img,
)
data = GetCaptchaDetail(uuid=uuid, img_type=img_type, image=img)
return response_base.success(data=data)
+1 -1
View File
@@ -18,7 +18,7 @@ router = APIRouter()
async def get_sessions(
username: Annotated[str | None, Query(description='用户名')] = None,
) -> ResponseSchemaModel[list[GetTokenDetail]]:
token_keys = await redis_client.keys(f'{settings.TOKEN_REDIS_PREFIX}:*')
token_keys = await redis_client.get_prefix(f'{settings.TOKEN_REDIS_PREFIX}:*')
online_clients = await redis_client.smembers(settings.TOKEN_ONLINE_REDIS_PREFIX)
data: list[GetTokenDetail] = []
+1 -1
View File
@@ -3,7 +3,7 @@ from fastapi import APIRouter
from backend.app.admin.api.v1.sys.data_rule import router as data_rule_router
from backend.app.admin.api.v1.sys.data_scope import router as data_scope_router
from backend.app.admin.api.v1.sys.dept import router as dept_router
from backend.app.admin.api.v1.sys.files import router as file_router
from backend.app.admin.api.v1.sys.file import router as file_router
from backend.app.admin.api.v1.sys.menu import router as menu_router
from backend.app.admin.api.v1.sys.plugin import router as plugin_router
from backend.app.admin.api.v1.sys.role import router as role_router
+3 -1
View File
@@ -30,7 +30,9 @@ async def get_dept_tree(
phone: Annotated[str | None, Query(description='联系电话')] = None,
status: Annotated[int | None, Query(description='状态')] = None,
) -> ResponseSchemaModel[list[GetDeptTree]]:
dept = await dept_service.get_tree(db=db, request=request, name=name, leader=leader, phone=phone, status=status)
dept = await dept_service.get_tree(
db=db, request_user=request.user, name=name, leader=leader, phone=phone, status=status
)
return response_base.success(data=dept)
@@ -13,7 +13,7 @@ router = APIRouter()
@router.post(
'/upload',
summary='文件上传',
summary='本地文件上传',
dependencies=[
Depends(RequestPermission('sys:file:upload')),
DependsRBAC,
+4 -4
View File
@@ -102,7 +102,7 @@ async def update_user_permission(
async def update_user_password(
db: CurrentSessionTransaction, request: Request, obj: ResetPasswordParam
) -> ResponseModel:
count = await user_service.update_password(db=db, request=request, obj=obj)
count = await user_service.update_password(db=db, user_id=request.user.id, obj=obj)
if count > 0:
return response_base.success()
return response_base.fail()
@@ -126,7 +126,7 @@ async def update_user_nickname(
request: Request,
nickname: Annotated[str, Body(embed=True, description='用户昵称')],
) -> ResponseModel:
count = await user_service.update_nickname(db=db, request=request, nickname=nickname)
count = await user_service.update_nickname(db=db, user_id=request.user.id, nickname=nickname)
if count > 0:
return response_base.success()
return response_base.fail()
@@ -138,7 +138,7 @@ async def update_user_avatar(
request: Request,
avatar: Annotated[str, Body(embed=True, description='用户头像地址')],
) -> ResponseModel:
count = await user_service.update_avatar(db=db, request=request, avatar=avatar)
count = await user_service.update_avatar(db=db, user_id=request.user.id, avatar=avatar)
if count > 0:
return response_base.success()
return response_base.fail()
@@ -151,7 +151,7 @@ async def update_user_email(
captcha: Annotated[str, Body(embed=True, description='邮箱验证码')],
email: Annotated[str, Body(embed=True, description='用户邮箱')],
) -> ResponseModel:
count = await user_service.update_email(db=db, request=request, captcha=captcha, email=email)
count = await user_service.update_email(db=db, user_id=request.user.id, captcha=captcha, email=email)
if count > 0:
return response_base.success()
return response_base.fail()
+1 -1
View File
@@ -33,7 +33,7 @@ class CRUDDataRule(CRUDPlus[DataRule]):
if name is not None:
filters['name__like'] = f'%{name}%'
return await self.select_order('id', load_strategies={'scopes': 'noload'}, **filters)
return await self.select_order('id', **filters)
async def get_by_name(self, db: AsyncSession, name: str) -> DataRule | None:
"""
+35 -13
View File
@@ -1,11 +1,18 @@
from collections.abc import Sequence
from typing import Any
from sqlalchemy import Select, select
from sqlalchemy import Select, delete, insert
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy_crud_plus import CRUDPlus
from sqlalchemy_crud_plus import CRUDPlus, JoinConfig
from backend.app.admin.model import DataRule, DataScope
from backend.app.admin.schema.data_scope import CreateDataScopeParam, UpdateDataScopeParam, UpdateDataScopeRuleParam
from backend.app.admin.model import DataRule, DataScope, data_scope_rule
from backend.app.admin.schema.data_scope import (
CreateDataScopeParam,
CreateDataScopeRuleParam,
UpdateDataScopeParam,
UpdateDataScopeRuleParam,
)
from backend.utils.serializers import select_join_serialize
class CRUDDataScope(CRUDPlus[DataScope]):
@@ -31,7 +38,7 @@ class CRUDDataScope(CRUDPlus[DataScope]):
"""
return await self.select_model_by_column(db, name=name)
async def get_with_relation(self, db: AsyncSession, pk: int) -> DataScope:
async def get_join(self, db: AsyncSession, pk: int) -> Any:
"""
获取数据范围关联数据
@@ -39,7 +46,16 @@ class CRUDDataScope(CRUDPlus[DataScope]):
:param pk: 范围 ID
:return:
"""
return await self.select_model(db, pk, load_strategies=['rules'])
result = await self.select_models(
db,
id=pk,
join_conditions=[
JoinConfig(model=data_scope_rule, join_on=data_scope_rule.c.data_scope_id == self.model.id),
JoinConfig(model=DataRule, join_on=DataRule.id == data_scope_rule.c.data_rule_id, fill_result=True),
],
)
return select_join_serialize(result, relationships=['DataScope-m2m-DataRule:rules'])
async def get_all(self, db: AsyncSession) -> Sequence[DataScope]:
"""
@@ -65,7 +81,7 @@ class CRUDDataScope(CRUDPlus[DataScope]):
if status is not None:
filters['status'] = status
return await self.select_order('id', load_strategies={'rules': 'noload', 'roles': 'noload'}, **filters)
return await self.select_order('id', **filters)
async def create(self, db: AsyncSession, obj: CreateDataScopeParam) -> None:
"""
@@ -88,7 +104,8 @@ class CRUDDataScope(CRUDPlus[DataScope]):
"""
return await self.update_model(db, pk, obj)
async def update_rules(self, db: AsyncSession, pk: int, rule_ids: UpdateDataScopeRuleParam) -> int:
@staticmethod
async def update_rules(db: AsyncSession, pk: int, rule_ids: UpdateDataScopeRuleParam) -> int:
"""
更新数据范围规则
@@ -97,11 +114,16 @@ class CRUDDataScope(CRUDPlus[DataScope]):
:param rule_ids: 数据规则 ID 列表
:return:
"""
current_data_scope = await self.get_with_relation(db, pk)
stmt = select(DataRule).where(DataRule.id.in_(rule_ids.rules))
rules = await db.execute(stmt)
current_data_scope.rules = rules.scalars().all()
return len(current_data_scope.rules)
data_scope_rule_stmt = delete(data_scope_rule).where(data_scope_rule.c.data_scope_id == pk)
await db.execute(data_scope_rule_stmt)
data_scope_rule_data = [
CreateDataScopeRuleParam(data_scope_id=pk, data_rule_id=rule_id).model_dump() for rule_id in rule_ids.rules
]
data_scope_rule_stmt = insert(data_scope_rule)
await db.execute(data_scope_rule_stmt, data_scope_rule_data)
return len(rule_ids.rules)
async def delete(self, db: AsyncSession, pks: list[int]) -> int:
"""
+20 -13
View File
@@ -1,12 +1,14 @@
from collections.abc import Sequence
from typing import Any
from fastapi import Request
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy_crud_plus import CRUDPlus
from sqlalchemy_crud_plus import CRUDPlus, JoinConfig
from backend.app.admin.model import Dept
from backend.app.admin.model import Dept, User
from backend.app.admin.schema.dept import CreateDeptParam, UpdateDeptParam
from backend.app.admin.schema.user import GetUserInfoWithRelationDetail
from backend.common.security.permission import filter_data_permission
from backend.utils.serializers import select_join_serialize
class CRUDDept(CRUDPlus[Dept]):
@@ -20,7 +22,7 @@ class CRUDDept(CRUDPlus[Dept]):
:param dept_id: 部门 ID
:return:
"""
return await self.select_model_by_column(db, id=dept_id, del_flag=0)
return await self.select_model_by_column(db, id=dept_id, del_flag=False)
async def get_by_name(self, db: AsyncSession, name: str) -> Dept | None:
"""
@@ -30,12 +32,12 @@ class CRUDDept(CRUDPlus[Dept]):
:param name: 部门名称
:return:
"""
return await self.select_model_by_column(db, name=name, del_flag=0)
return await self.select_model_by_column(db, name=name, del_flag=False)
async def get_all(
self,
request: Request,
db: AsyncSession,
request_user: GetUserInfoWithRelationDetail,
name: str | None,
leader: str | None,
phone: str | None,
@@ -44,15 +46,15 @@ class CRUDDept(CRUDPlus[Dept]):
"""
获取所有部门
:param request: FastAPI 请求对象
:param db: 数据库会话
:param request_user: 请求用户
:param name: 部门名称
:param leader: 负责人
:param phone: 联系电话
:param status: 部门状态
:return:
"""
filters = {'del_flag': 0}
filters = {'del_flag': False}
if name is not None:
filters['name__like'] = f'%{name}%'
@@ -63,8 +65,8 @@ class CRUDDept(CRUDPlus[Dept]):
if status is not None:
filters['status'] = status
data_filtered = await filter_data_permission(db, request)
return await self.select_models_order(db, 'sort', 'desc', data_filtered, **filters)
data_filter = filter_data_permission(request_user)
return await self.select_models_order(db, 'sort', 'desc', data_filter, **filters)
async def create(self, db: AsyncSession, obj: CreateDeptParam) -> None:
"""
@@ -97,7 +99,7 @@ class CRUDDept(CRUDPlus[Dept]):
"""
return await self.delete_model_by_column(db, id=dept_id, logical_deletion=True, deleted_flag_column='del_flag')
async def get_with_relation(self, db: AsyncSession, dept_id: int) -> Dept | None:
async def get_join(self, db: AsyncSession, dept_id: int) -> Any | None:
"""
获取部门及关联数据
@@ -105,7 +107,12 @@ class CRUDDept(CRUDPlus[Dept]):
:param dept_id: 部门 ID
:return:
"""
return await self.select_model(db, dept_id, load_strategies=['users'])
result = await self.select_model(
db,
dept_id,
join_conditions=[JoinConfig(model=User, join_on=User.dept_id == self.model.id, fill_result=True)],
)
return select_join_serialize(result, relationships=['Dept-o2m-User'])
async def get_children(self, db: AsyncSession, dept_id: int) -> Sequence[Dept | None]:
"""
@@ -115,7 +122,7 @@ class CRUDDept(CRUDPlus[Dept]):
:param dept_id: 部门 ID
:return:
"""
return await self.select_models(db, parent_id=dept_id, del_flag=0)
return await self.select_models(db, parent_id=dept_id, del_flag=False)
dept_dao: CRUDDept = CRUDDept(Dept)
+7 -4
View File
@@ -1,9 +1,10 @@
from collections.abc import Sequence
from sqlalchemy import delete
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy_crud_plus import CRUDPlus
from backend.app.admin.model import Menu
from backend.app.admin.model import Menu, role_menu
from backend.app.admin.schema.menu import CreateMenuParam, UpdateMenuParam
@@ -92,9 +93,12 @@ class CRUDMenu(CRUDPlus[Menu]):
:param menu_id: 菜单 ID
:return:
"""
role_menu_stmt = delete(role_menu).where(role_menu.c.menu_id == menu_id)
await db.execute(role_menu_stmt)
return await self.delete_model(db, menu_id)
async def get_children(self, db: AsyncSession, menu_id: int) -> list[Menu | None]:
async def get_children(self, db: AsyncSession, menu_id: int) -> Sequence[Menu | None]:
"""
获取子菜单列表
@@ -102,8 +106,7 @@ class CRUDMenu(CRUDPlus[Menu]):
:param menu_id: 菜单 ID
:return:
"""
menu = await self.select_model(db, menu_id, load_strategies=['children'])
return menu.children
return await self.select_models(db, parent_id=menu_id)
menu_dao: CRUDMenu = CRUDMenu(Menu)
+58 -26
View File
@@ -1,16 +1,20 @@
from collections.abc import Sequence
from typing import Any
from sqlalchemy import Select, select
from sqlalchemy import Select, delete, insert, select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy_crud_plus import CRUDPlus
from sqlalchemy_crud_plus import CRUDPlus, JoinConfig
from backend.app.admin.model import DataScope, Menu, Role
from backend.app.admin.model import DataScope, Menu, Role, role_data_scope, role_menu
from backend.app.admin.schema.role import (
CreateRoleMenuParam,
CreateRoleParam,
CreateRoleScopeParam,
UpdateRoleMenuParam,
UpdateRoleParam,
UpdateRoleScopeParam,
)
from backend.utils.serializers import select_join_serialize
class CRUDRole(CRUDPlus[Role]):
@@ -26,7 +30,20 @@ class CRUDRole(CRUDPlus[Role]):
"""
return await self.select_model(db, role_id)
async def get_with_relation(self, db: AsyncSession, role_id: int) -> Role | None:
@staticmethod
async def get_menus(db: AsyncSession, role_id: int) -> Sequence[Menu] | None:
"""
获取角色菜单
:param db: 数据库会话
:param role_id: 角色 ID
:return:
"""
menu_stmt = select(Menu).join(role_menu, Menu.id == role_menu.c.menu_id).where(role_menu.c.role_id == role_id)
result = await db.execute(menu_stmt)
return result.scalars().all()
async def get_join(self, db: AsyncSession, role_id: int) -> Any:
"""
获取角色及关联数据
@@ -34,7 +51,18 @@ class CRUDRole(CRUDPlus[Role]):
:param role_id: 角色 ID
:return:
"""
return await self.select_model(db, role_id, load_strategies=['menus', 'scopes'])
result = await self.select_models(
db,
id=role_id,
join_conditions=[
JoinConfig(model=role_menu, join_on=role_menu.c.role_id == self.model.id),
JoinConfig(model=Menu, join_on=Menu.id == role_menu.c.menu_id, fill_result=True),
JoinConfig(model=role_data_scope, join_on=role_data_scope.c.role_id == self.model.id),
JoinConfig(model=DataScope, join_on=DataScope.id == role_data_scope.c.data_scope_id, fill_result=True),
],
)
return select_join_serialize(result, relationships=['Role-m2m-Menu', 'Role-m2m-DataScope:scopes'])
async def get_all(self, db: AsyncSession) -> Sequence[Role]:
"""
@@ -61,15 +89,7 @@ class CRUDRole(CRUDPlus[Role]):
if status is not None:
filters['status'] = status
return await self.select_order(
'id',
load_strategies={
'users': 'noload',
'menus': 'noload',
'scopes': 'noload',
},
**filters,
)
return await self.select_order('id', **filters)
async def get_by_name(self, db: AsyncSession, name: str) -> Role | None:
"""
@@ -102,7 +122,8 @@ class CRUDRole(CRUDPlus[Role]):
"""
return await self.update_model(db, role_id, obj)
async def update_menus(self, db: AsyncSession, role_id: int, menu_ids: UpdateRoleMenuParam) -> int:
@staticmethod
async def update_menus(db: AsyncSession, role_id: int, menu_ids: UpdateRoleMenuParam) -> int:
"""
更新角色菜单
@@ -111,13 +132,19 @@ class CRUDRole(CRUDPlus[Role]):
:param menu_ids: 菜单 ID 列表
:return:
"""
current_role = await self.get_with_relation(db, role_id)
stmt = select(Menu).where(Menu.id.in_(menu_ids.menus))
menus = await db.execute(stmt)
current_role.menus = menus.scalars().all()
return len(current_role.menus)
role_menu_stmt = delete(role_menu).where(role_menu.c.role_id == role_id)
await db.execute(role_menu_stmt)
async def update_scopes(self, db: AsyncSession, role_id: int, scope_ids: UpdateRoleScopeParam) -> int:
role_menu_data = [
CreateRoleMenuParam(role_id=role_id, menu_id=menu_id).model_dump() for menu_id in menu_ids.menus
]
role_menu_stmt = insert(role_menu)
await db.execute(role_menu_stmt, role_menu_data)
return len(menu_ids.menus)
@staticmethod
async def update_scopes(db: AsyncSession, role_id: int, scope_ids: UpdateRoleScopeParam) -> int:
"""
更新角色数据范围
@@ -126,11 +153,16 @@ class CRUDRole(CRUDPlus[Role]):
:param scope_ids: 权限范围 ID 列表
:return:
"""
current_role = await self.get_with_relation(db, role_id)
stmt = select(DataScope).where(DataScope.id.in_(scope_ids.scopes))
scopes = await db.execute(stmt)
current_role.scopes = scopes.scalars().all()
return len(current_role.scopes)
role_scope_stmt = delete(role_data_scope).where(role_data_scope.c.role_id == role_id)
await db.execute(role_scope_stmt)
role_scope_data = [
CreateRoleScopeParam(role_id=role_id, data_scope_id=scope_id).model_dump() for scope_id in scope_ids.scopes
]
role_scope_stmt = insert(role_data_scope)
await db.execute(role_scope_stmt, role_scope_data)
return len(scope_ids.scopes)
async def delete(self, db: AsyncSession, role_ids: list[int]) -> int:
"""
+150 -83
View File
@@ -1,18 +1,32 @@
from typing import Any
import bcrypt
from sqlalchemy import select
from sqlalchemy import Select, delete, insert, select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import noload, selectinload
from sqlalchemy.sql import Select
from sqlalchemy_crud_plus import CRUDPlus
from sqlalchemy_crud_plus import CRUDPlus, JoinConfig
from backend.app.admin.model import Dept, Role, User
from backend.app.admin.model import (
DataRule,
DataScope,
Dept,
Menu,
Role,
User,
data_scope_rule,
role_data_scope,
role_menu,
user_role,
)
from backend.app.admin.schema.user import (
AddOAuth2UserParam,
AddUserParam,
AddUserRoleParam,
UpdateUserParam,
)
from backend.common.security.jwt import get_hash_password
from backend.app.admin.utils.password_security import get_hash_password
from backend.plugin.oauth2.crud.crud_user_social import user_social_dao
from backend.utils.serializers import select_join_serialize
from backend.utils.timezone import timezone
@@ -49,15 +63,47 @@ class CRUDUser(CRUDPlus[User]):
"""
return await self.select_model_by_column(db, nickname=nickname)
async def update_login_time(self, db: AsyncSession, username: str) -> int:
async def check_email(self, db: AsyncSession, email: str) -> User | None:
"""
更新用户最后登录时间
检查邮箱是否已被绑定
:param db: 数据库会话
:param username: 用户名
:param email: 电子邮箱
:return:
"""
return await self.update_model_by_column(db, {'last_login_time': timezone.now()}, username=username)
return await self.select_model_by_column(db, email=email)
async def get_select(self, dept: int | None, username: str | None, phone: str | None, status: int | None) -> Select:
"""
获取用户列表查询表达式
:param dept: 部门 ID
:param username: 用户名
:param phone: 电话号码
:param status: 用户状态
:return:
"""
filters = {}
if dept:
filters['dept_id'] = dept
if username:
filters['username__like'] = f'%{username}%'
if phone:
filters['phone__like'] = f'%{phone}%'
if status is not None:
filters['status'] = status
return await self.select_order(
'id',
'desc',
join_conditions=[
JoinConfig(model=Dept, join_on=Dept.id == self.model.dept_id, fill_result=True),
JoinConfig(model=user_role, join_on=user_role.c.user_id == self.model.id),
JoinConfig(model=Role, join_on=Role.id == user_role.c.role_id, fill_result=True),
],
**filters,
)
async def add(self, db: AsyncSession, obj: AddUserParam) -> None:
"""
@@ -69,15 +115,20 @@ class CRUDUser(CRUDPlus[User]):
"""
salt = bcrypt.gensalt()
obj.password = get_hash_password(obj.password, salt)
dict_obj = obj.model_dump(exclude={'roles'})
dict_obj.update({'salt': salt})
new_user = self.model(**dict_obj)
stmt = select(Role).where(Role.id.in_(obj.roles))
roles = await db.execute(stmt)
new_user.roles = roles.scalars().all()
db.add(new_user)
await db.flush()
role_stmt = select(Role).where(Role.id.in_(obj.roles))
result = await db.execute(role_stmt)
roles = result.scalars().all()
user_role_data = [AddUserRoleParam(user_id=new_user.id, role_id=role.id).model_dump() for role in roles]
user_role_stmt = insert(user_role)
await db.execute(user_role_stmt, user_role_data)
async def add_by_oauth2(self, db: AsyncSession, obj: AddOAuth2UserParam) -> None:
"""
@@ -90,31 +141,63 @@ class CRUDUser(CRUDPlus[User]):
dict_obj = obj.model_dump()
dict_obj.update({'is_staff': True, 'salt': None})
new_user = self.model(**dict_obj)
stmt = select(Role)
role = await db.execute(stmt)
new_user.roles = [role.scalars().first()] # 默认绑定第一个角色
db.add(new_user)
await db.flush()
async def update(self, db: AsyncSession, input_user: User, obj: UpdateUserParam) -> int:
role_stmt = select(Role)
result = await db.execute(role_stmt)
role = result.scalars().first() # 默认绑定第一个角色
user_role_stmt = insert(user_role).values(AddUserRoleParam(user_id=new_user.id, role_id=role.id).model_dump())
await db.execute(user_role_stmt)
async def update(self, db: AsyncSession, user_id: int, obj: UpdateUserParam) -> int:
"""
更新用户信息
:param db: 数据库会话
:param input_user: 用户 ID
:param user_id: 用户 ID
:param obj: 更新用户参数
:return:
"""
role_ids = obj.roles
del obj.roles
count = await self.update_model(db, input_user.id, obj)
stmt = select(Role).where(Role.id.in_(role_ids))
roles = await db.execute(stmt)
input_user.roles = roles.scalars().all()
count = await self.update_model(db, user_id, obj)
role_stmt = select(Role).where(Role.id.in_(role_ids))
result = await db.execute(role_stmt)
roles = result.scalars().all()
user_role_stmt = delete(user_role).where(user_role.c.user_id == user_id)
await db.execute(user_role_stmt)
user_role_data = [AddUserRoleParam(user_id=user_id, role_id=role.id).model_dump() for role in roles]
user_role_stmt = insert(user_role)
await db.execute(user_role_stmt, user_role_data)
return count
async def update_login_time(self, db: AsyncSession, username: str) -> int:
"""
更新用户上次登录时间
:param db: 数据库会话
:param username: 用户名
:return:
"""
return await self.update_model_by_column(db, {'last_login_time': timezone.now()}, username=username)
async def update_password_changed_time(self, db: AsyncSession, user_id: int) -> int:
"""
更新用户上次密码变更时间
:param db: 数据库会话
:param user_id: 用户 ID
:return:
"""
return await self.update_model(db, user_id, {'last_password_changed_time': timezone.now()})
async def update_nickname(self, db: AsyncSession, user_id: int, nickname: str) -> int:
"""
更新用户昵称
@@ -148,26 +231,6 @@ class CRUDUser(CRUDPlus[User]):
"""
return await self.update_model(db, user_id, {'email': email})
async def delete(self, db: AsyncSession, user_id: int) -> int:
"""
删除用户
:param db: 数据库会话
:param user_id: 用户 ID
:return:
"""
return await self.delete_model(db, user_id)
async def check_email(self, db: AsyncSession, email: str) -> User | None:
"""
检查邮箱是否已被绑定
:param db: 数据库会话
:param email: 电子邮箱
:return:
"""
return await self.select_model_by_column(db, email=email)
async def reset_password(self, db: AsyncSession, pk: int, password: str) -> int:
"""
重置用户密码
@@ -179,38 +242,7 @@ class CRUDUser(CRUDPlus[User]):
"""
salt = bcrypt.gensalt()
new_pwd = get_hash_password(password, salt)
return await self.update_model(db, pk, {'password': new_pwd, 'salt': salt})
async def get_select(self, dept: int | None, username: str | None, phone: str | None, status: int | None) -> Select:
"""
获取用户列表查询表达式
:param dept: 部门 ID
:param username: 用户名
:param phone: 电话号码
:param status: 用户状态
:return:
"""
filters = {}
if dept:
filters['dept_id'] = dept
if username:
filters['username__like'] = f'%{username}%'
if phone:
filters['phone__like'] = f'%{phone}%'
if status is not None:
filters['status'] = status
return await self.select_order(
'id',
'desc',
load_options=[
selectinload(self.model.dept).options(noload(Dept.parent), noload(Dept.children), noload(Dept.users)),
selectinload(self.model.roles).options(noload(Role.users), noload(Role.menus), noload(Role.scopes)),
],
**filters,
)
return await self.update_model(db, pk, {'password': new_pwd, 'salt': salt}, flush=True)
async def set_super(self, db: AsyncSession, user_id: int, *, is_super: bool) -> int:
"""
@@ -256,13 +288,28 @@ class CRUDUser(CRUDPlus[User]):
"""
return await self.update_model(db, user_id, {'is_multi_login': multi_login})
async def get_with_relation(
async def delete(self, db: AsyncSession, user_id: int) -> int:
"""
删除用户
:param db: 数据库会话
:param user_id: 用户 ID
:return:
"""
user_role_stmt = delete(user_role).where(user_role.c.user_id == user_id)
await db.execute(user_role_stmt)
await user_social_dao.delete_by_user_id(db, user_id)
return await self.delete_model(db, user_id)
async def get_join(
self,
db: AsyncSession,
*,
user_id: int | None = None,
username: str | None = None,
) -> User | None:
) -> Any | None:
"""
获取用户关联信息
@@ -278,12 +325,32 @@ class CRUDUser(CRUDPlus[User]):
if username:
filters['username'] = username
return await self.select_model_by_column(
result = await self.select_models(
db,
load_options=[selectinload(self.model.roles).options(selectinload(Role.menus), selectinload(Role.scopes))],
load_strategies=['dept'],
join_conditions=[
JoinConfig(model=Dept, join_on=Dept.id == self.model.dept_id, fill_result=True),
JoinConfig(model=user_role, join_on=user_role.c.user_id == self.model.id),
JoinConfig(model=Role, join_on=Role.id == user_role.c.role_id, fill_result=True),
JoinConfig(model=role_menu, join_on=role_menu.c.role_id == Role.id),
JoinConfig(model=Menu, join_on=Menu.id == role_menu.c.menu_id, fill_result=True),
JoinConfig(model=role_data_scope, join_on=role_data_scope.c.role_id == Role.id),
JoinConfig(model=DataScope, join_on=DataScope.id == role_data_scope.c.data_scope_id, fill_result=True),
JoinConfig(model=data_scope_rule, join_on=data_scope_rule.c.data_scope_id == DataScope.id),
JoinConfig(model=DataRule, join_on=DataRule.id == data_scope_rule.c.data_rule_id, fill_result=True),
],
**filters,
)
return select_join_serialize(
result,
relationships=[
'User-m2o-Dept',
'User-m2m-Role',
'Role-m2m-Menu',
'Role-m2m-DataScope:scopes',
'DataScope-m2m-DataRule:rules',
],
)
user_dao: CRUDUser = CRUDUser(User)
@@ -0,0 +1,34 @@
from collections.abc import Sequence
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy_crud_plus import CRUDPlus
from backend.app.admin.model.user_password_history import UserPasswordHistory
from backend.app.admin.schema.user_password_history import CreateUserPasswordHistoryParam
class CRUDUserPasswordHistory(CRUDPlus[UserPasswordHistory]):
"""用户密码历史记录数据库操作类"""
async def create(self, db: AsyncSession, obj: CreateUserPasswordHistoryParam) -> None:
"""
创建密码历史记录
:param db: 数据库会话
:param obj: 创建密码历史记录参数
:return:
"""
await self.create_model(db, obj)
async def get_by_user_id(self, db: AsyncSession, user_id: int) -> Sequence[UserPasswordHistory]:
"""
获取用户的密码历史记录
:param db: 数据库会话
:param user_id: 用户 ID
:return:
"""
return await self.select_models_order(db, 'id', 'desc', self.model.user_id == user_id)
user_password_history_dao: CRUDUserPasswordHistory = CRUDUserPasswordHistory(UserPasswordHistory)
+5
View File
@@ -2,7 +2,12 @@ from backend.app.admin.model.data_rule import DataRule as DataRule
from backend.app.admin.model.data_scope import DataScope as DataScope
from backend.app.admin.model.dept import Dept as Dept
from backend.app.admin.model.login_log import LoginLog as LoginLog
from backend.app.admin.model.m2m import data_scope_rule as data_scope_rule
from backend.app.admin.model.m2m import role_data_scope as role_data_scope
from backend.app.admin.model.m2m import role_menu as role_menu
from backend.app.admin.model.m2m import user_role as user_role
from backend.app.admin.model.menu import Menu as Menu
from backend.app.admin.model.opera_log import OperaLog as OperaLog
from backend.app.admin.model.role import Role as Role
from backend.app.admin.model.user import User as User
from backend.app.admin.model.user_password_history import UserPasswordHistory as UserPasswordHistory
+6 -16
View File
@@ -1,16 +1,9 @@
from __future__ import annotations
import sqlalchemy as sa
from typing import TYPE_CHECKING
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy import String
from sqlalchemy.orm import Mapped, mapped_column, relationship
from backend.app.admin.model.m2m import sys_data_scope_rule
from backend.common.model import Base, id_key
if TYPE_CHECKING:
from backend.app.admin.model import DataScope
class DataRule(Base):
"""数据规则表"""
@@ -18,14 +11,11 @@ class DataRule(Base):
__tablename__ = 'sys_data_rule'
id: Mapped[id_key] = mapped_column(init=False)
name: Mapped[str] = mapped_column(String(500), unique=True, comment='名称')
model: Mapped[str] = mapped_column(String(50), comment='SQLA 模型名,对应 DATA_PERMISSION_MODELS 键名')
column: Mapped[str] = mapped_column(String(20), comment='模型字段名')
name: Mapped[str] = mapped_column(sa.String(512), unique=True, comment='名称')
model: Mapped[str] = mapped_column(sa.String(64), comment='模型名称')
column: Mapped[str] = mapped_column(sa.String(32), comment='模型字段名')
operator: Mapped[int] = mapped_column(comment='运算符(0and、1or')
expression: Mapped[int] = mapped_column(
comment='表达式(0==、1!=、2>、3>=、4<、5<=、6in、7not_in',
)
value: Mapped[str] = mapped_column(String(255), comment='规则值')
# 数据范围规则多对多
scopes: Mapped[list[DataScope]] = relationship(init=False, secondary=sys_data_scope_rule, back_populates='rules')
value: Mapped[str] = mapped_column(sa.String(256), comment='规则值')
+3 -16
View File
@@ -1,16 +1,9 @@
from __future__ import annotations
import sqlalchemy as sa
from typing import TYPE_CHECKING
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy import String
from sqlalchemy.orm import Mapped, mapped_column, relationship
from backend.app.admin.model.m2m import sys_data_scope_rule, sys_role_data_scope
from backend.common.model import Base, id_key
if TYPE_CHECKING:
from backend.app.admin.model import DataRule, Role
class DataScope(Base):
"""数据范围表"""
@@ -18,11 +11,5 @@ class DataScope(Base):
__tablename__ = 'sys_data_scope'
id: Mapped[id_key] = mapped_column(init=False)
name: Mapped[str] = mapped_column(String(50), unique=True, comment='名称')
name: Mapped[str] = mapped_column(sa.String(64), unique=True, comment='名称')
status: Mapped[int] = mapped_column(default=1, comment='状态(0停用 1正常)')
# 数据范围规则多对多
rules: Mapped[list[DataRule]] = relationship(init=False, secondary=sys_data_scope_rule, back_populates='scopes')
# 角色数据范围多对多
roles: Mapped[list[Role]] = relationship(init=False, secondary=sys_role_data_scope, back_populates='scopes')
+9 -31
View File
@@ -1,16 +1,9 @@
from __future__ import annotations
import sqlalchemy as sa
from typing import TYPE_CHECKING
from sqlalchemy import BigInteger, Boolean, ForeignKey, String
from sqlalchemy.dialects.postgresql import INTEGER
from sqlalchemy.orm import Mapped, mapped_column, relationship
from sqlalchemy.orm import Mapped, mapped_column
from backend.common.model import Base, id_key
if TYPE_CHECKING:
from backend.app.admin.model import User
class Dept(Base):
"""部门表"""
@@ -18,28 +11,13 @@ class Dept(Base):
__tablename__ = 'sys_dept'
id: Mapped[id_key] = mapped_column(init=False)
name: Mapped[str] = mapped_column(String(50), comment='部门名称')
name: Mapped[str] = mapped_column(sa.String(64), comment='部门名称')
sort: Mapped[int] = mapped_column(default=0, comment='排序')
leader: Mapped[str | None] = mapped_column(String(20), default=None, comment='负责人')
phone: Mapped[str | None] = mapped_column(String(11), default=None, comment='手机')
email: Mapped[str | None] = mapped_column(String(50), default=None, comment='邮箱')
leader: Mapped[str | None] = mapped_column(sa.String(32), default=None, comment='负责人')
phone: Mapped[str | None] = mapped_column(sa.String(11), default=None, comment='手机')
email: Mapped[str | None] = mapped_column(sa.String(64), default=None, comment='邮箱')
status: Mapped[int] = mapped_column(default=1, comment='部门状态(0停用 1正常)')
del_flag: Mapped[bool] = mapped_column(
Boolean().with_variant(INTEGER, 'postgresql'),
default=False,
comment='删除标志(0删除 1存在)',
)
del_flag: Mapped[bool] = mapped_column(default=False, comment='删除标志(0删除 1存在)')
# 父级部门一对多
parent_id: Mapped[int | None] = mapped_column(
BigInteger,
ForeignKey('sys_dept.id', ondelete='SET NULL'),
default=None,
index=True,
comment='父部门ID',
)
parent: Mapped[Dept | None] = relationship(init=False, back_populates='children', remote_side=[id])
children: Mapped[list[Dept] | None] = relationship(init=False, back_populates='parent')
# 部门用户一对多
users: Mapped[list[User]] = relationship(init=False, back_populates='dept')
# 父级部门
parent_id: Mapped[int | None] = mapped_column(sa.BigInteger, default=None, index=True, comment='父部门ID')
+14 -15
View File
@@ -1,11 +1,10 @@
from datetime import datetime
from sqlalchemy import String
from sqlalchemy.dialects.mysql import LONGTEXT
from sqlalchemy.dialects.postgresql import TEXT
import sqlalchemy as sa
from sqlalchemy.orm import Mapped, mapped_column
from backend.common.model import DataClassBase, TimeZone, id_key
from backend.common.model import DataClassBase, TimeZone, UniversalText, id_key
from backend.utils.timezone import timezone
@@ -15,18 +14,18 @@ class LoginLog(DataClassBase):
__tablename__ = 'sys_login_log'
id: Mapped[id_key] = mapped_column(init=False)
user_uuid: Mapped[str] = mapped_column(String(50), comment='用户UUID')
username: Mapped[str] = mapped_column(String(20), comment='用户名')
user_uuid: Mapped[str] = mapped_column(sa.String(64), comment='用户UUID')
username: Mapped[str] = mapped_column(sa.String(64), comment='用户名')
status: Mapped[int] = mapped_column(insert_default=0, comment='登录状态(0失败 1成功)')
ip: Mapped[str] = mapped_column(String(50), comment='登录IP地址')
country: Mapped[str | None] = mapped_column(String(50), comment='国家')
region: Mapped[str | None] = mapped_column(String(50), comment='地区')
city: Mapped[str | None] = mapped_column(String(50), comment='城市')
user_agent: Mapped[str] = mapped_column(String(255), comment='请求头')
os: Mapped[str | None] = mapped_column(String(50), comment='操作系统')
browser: Mapped[str | None] = mapped_column(String(50), comment='浏览器')
device: Mapped[str | None] = mapped_column(String(50), comment='设备')
msg: Mapped[str] = mapped_column(LONGTEXT().with_variant(TEXT, 'postgresql'), comment='提示消息')
ip: Mapped[str] = mapped_column(sa.String(64), comment='登录IP地址')
country: Mapped[str | None] = mapped_column(sa.String(64), comment='国家')
region: Mapped[str | None] = mapped_column(sa.String(64), comment='地区')
city: Mapped[str | None] = mapped_column(sa.String(64), comment='城市')
user_agent: Mapped[str] = mapped_column(sa.String(256), comment='请求头')
os: Mapped[str | None] = mapped_column(sa.String(64), comment='操作系统')
browser: Mapped[str | None] = mapped_column(sa.String(64), comment='浏览器')
device: Mapped[str | None] = mapped_column(sa.String(64), comment='设备')
msg: Mapped[str] = mapped_column(UniversalText, comment='提示消息')
login_time: Mapped[datetime] = mapped_column(TimeZone, comment='登录时间')
created_time: Mapped[datetime] = mapped_column(
TimeZone,
+21 -35
View File
@@ -1,53 +1,39 @@
from sqlalchemy import BigInteger, Column, ForeignKey, Table
import sqlalchemy as sa
from backend.common.model import MappedBase
sys_user_role = Table(
# 用户角色表
user_role = sa.Table(
'sys_user_role',
MappedBase.metadata,
Column('id', BigInteger, primary_key=True, unique=True, index=True, autoincrement=True, comment='主键ID'),
Column('user_id', BigInteger, ForeignKey('sys_user.id', ondelete='CASCADE'), primary_key=True, comment='用户ID'),
Column('role_id', BigInteger, ForeignKey('sys_role.id', ondelete='CASCADE'), primary_key=True, comment='角色ID'),
sa.Column('id', sa.BigInteger, primary_key=True, unique=True, index=True, autoincrement=True, comment='主键ID'),
sa.Column('user_id', sa.BigInteger, primary_key=True, comment='用户ID'),
sa.Column('role_id', sa.BigInteger, primary_key=True, comment='角色ID'),
)
sys_role_menu = Table(
# 角色菜单表
role_menu = sa.Table(
'sys_role_menu',
MappedBase.metadata,
Column('id', BigInteger, primary_key=True, unique=True, index=True, autoincrement=True, comment='主键ID'),
Column('role_id', BigInteger, ForeignKey('sys_role.id', ondelete='CASCADE'), primary_key=True, comment='角色ID'),
Column('menu_id', BigInteger, ForeignKey('sys_menu.id', ondelete='CASCADE'), primary_key=True, comment='菜单ID'),
sa.Column('id', sa.BigInteger, primary_key=True, unique=True, index=True, autoincrement=True, comment='主键ID'),
sa.Column('role_id', sa.BigInteger, primary_key=True, comment='角色ID'),
sa.Column('menu_id', sa.BigInteger, primary_key=True, comment='菜单ID'),
)
sys_role_data_scope = Table(
# 角色数据范围表
role_data_scope = sa.Table(
'sys_role_data_scope',
MappedBase.metadata,
Column('id', BigInteger, primary_key=True, unique=True, index=True, autoincrement=True, comment='主键 ID'),
Column('role_id', BigInteger, ForeignKey('sys_role.id', ondelete='CASCADE'), primary_key=True, comment='角色 ID'),
Column(
'data_scope_id',
BigInteger,
ForeignKey('sys_data_scope.id', ondelete='CASCADE'),
primary_key=True,
comment='数据范围 ID',
),
sa.Column('id', sa.BigInteger, primary_key=True, unique=True, index=True, autoincrement=True, comment='主键 ID'),
sa.Column('role_id', sa.BigInteger, primary_key=True, comment='角色 ID'),
sa.Column('data_scope_id', sa.BigInteger, primary_key=True, comment='数据范围 ID'),
)
sys_data_scope_rule = Table(
# 数据范围规则表
data_scope_rule = sa.Table(
'sys_data_scope_rule',
MappedBase.metadata,
Column('id', BigInteger, primary_key=True, unique=True, index=True, autoincrement=True, comment='主键ID'),
Column(
'data_scope_id',
BigInteger,
ForeignKey('sys_data_scope.id', ondelete='CASCADE'),
primary_key=True,
comment='数据范围 ID',
),
Column(
'data_rule_id',
BigInteger,
ForeignKey('sys_data_rule.id', ondelete='CASCADE'),
primary_key=True,
comment='数据规则 ID',
),
sa.Column('id', sa.BigInteger, primary_key=True, unique=True, index=True, autoincrement=True, comment='主键ID'),
sa.Column('data_scope_id', sa.BigInteger, primary_key=True, comment='数据范围 ID'),
sa.Column('data_rule_id', sa.BigInteger, primary_key=True, comment='数据规则 ID'),
)
+13 -41
View File
@@ -1,17 +1,8 @@
from __future__ import annotations
import sqlalchemy as sa
from typing import TYPE_CHECKING
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy import BigInteger, ForeignKey, String
from sqlalchemy.dialects.mysql import LONGTEXT
from sqlalchemy.dialects.postgresql import TEXT
from sqlalchemy.orm import Mapped, mapped_column, relationship
from backend.app.admin.model.m2m import sys_role_menu
from backend.common.model import Base, id_key
if TYPE_CHECKING:
from backend.app.admin.model import Role
from backend.common.model import Base, UniversalText, id_key
class Menu(Base):
@@ -20,38 +11,19 @@ class Menu(Base):
__tablename__ = 'sys_menu'
id: Mapped[id_key] = mapped_column(init=False)
title: Mapped[str] = mapped_column(String(50), comment='菜单标题')
name: Mapped[str] = mapped_column(String(50), comment='菜单名称')
path: Mapped[str | None] = mapped_column(String(200), comment='路由地址')
title: Mapped[str] = mapped_column(sa.String(64), comment='菜单标题')
name: Mapped[str] = mapped_column(sa.String(64), comment='菜单名称')
path: Mapped[str | None] = mapped_column(sa.String(200), comment='路由地址')
sort: Mapped[int] = mapped_column(default=0, comment='排序')
icon: Mapped[str | None] = mapped_column(String(100), default=None, comment='菜单图标')
icon: Mapped[str | None] = mapped_column(sa.String(128), default=None, comment='菜单图标')
type: Mapped[int] = mapped_column(default=0, comment='菜单类型(0目录 1菜单 2按钮 3内嵌 4外链)')
component: Mapped[str | None] = mapped_column(String(255), default=None, comment='组件路径')
perms: Mapped[str | None] = mapped_column(String(100), default=None, comment='权限标识')
component: Mapped[str | None] = mapped_column(sa.String(256), default=None, comment='组件路径')
perms: Mapped[str | None] = mapped_column(sa.String(128), default=None, comment='权限标识')
status: Mapped[int] = mapped_column(default=1, comment='菜单状态(0停用 1正常)')
display: Mapped[int] = mapped_column(default=1, comment='是否显示(0否 1是)')
cache: Mapped[int] = mapped_column(default=1, comment='是否缓存(0否 1是)')
link: Mapped[str | None] = mapped_column(
LONGTEXT().with_variant(TEXT, 'postgresql'),
default=None,
comment='外链地址',
)
remark: Mapped[str | None] = mapped_column(
LONGTEXT().with_variant(TEXT, 'postgresql'),
default=None,
comment='备注',
)
link: Mapped[str | None] = mapped_column(UniversalText, default=None, comment='外链地址')
remark: Mapped[str | None] = mapped_column(UniversalText, default=None, comment='备注')
# 父级菜单一对多
parent_id: Mapped[int | None] = mapped_column(
BigInteger,
ForeignKey('sys_menu.id', ondelete='SET NULL'),
default=None,
index=True,
comment='父菜单ID',
)
parent: Mapped[Menu | None] = relationship(init=False, back_populates='children', remote_side=[id])
children: Mapped[list[Menu] | None] = relationship(init=False, back_populates='parent')
# 菜单角色多对多
roles: Mapped[list[Role]] = relationship(init=False, secondary=sys_role_menu, back_populates='menus')
# 父级菜单
parent_id: Mapped[int | None] = mapped_column(sa.BigInteger, default=None, index=True, comment='父菜单ID')
+20 -24
View File
@@ -1,11 +1,10 @@
from datetime import datetime
from sqlalchemy import String
from sqlalchemy.dialects.mysql import JSON, LONGTEXT
from sqlalchemy.dialects.postgresql import TEXT
import sqlalchemy as sa
from sqlalchemy.orm import Mapped, mapped_column
from backend.common.model import DataClassBase, TimeZone, id_key
from backend.common.model import DataClassBase, TimeZone, UniversalText, id_key
from backend.utils.timezone import timezone
@@ -15,28 +14,25 @@ class OperaLog(DataClassBase):
__tablename__ = 'sys_opera_log'
id: Mapped[id_key] = mapped_column(init=False)
trace_id: Mapped[str] = mapped_column(String(32), comment='请求跟踪 ID')
username: Mapped[str | None] = mapped_column(String(20), comment='用户名')
method: Mapped[str] = mapped_column(String(20), comment='请求类型')
title: Mapped[str] = mapped_column(String(255), comment='操作模块')
path: Mapped[str] = mapped_column(String(500), comment='请求路径')
ip: Mapped[str] = mapped_column(String(50), comment='IP地址')
country: Mapped[str | None] = mapped_column(String(50), comment='国家')
region: Mapped[str | None] = mapped_column(String(50), comment='地区')
city: Mapped[str | None] = mapped_column(String(50), comment='城市')
user_agent: Mapped[str] = mapped_column(LONGTEXT().with_variant(TEXT, 'postgresql'), comment='请求头')
os: Mapped[str | None] = mapped_column(String(50), comment='操作系统')
browser: Mapped[str | None] = mapped_column(String(50), comment='浏览器')
device: Mapped[str | None] = mapped_column(String(50), comment='设备')
args: Mapped[str | None] = mapped_column(JSON(), comment='请求参数')
trace_id: Mapped[str] = mapped_column(sa.String(32), comment='请求跟踪 ID')
username: Mapped[str | None] = mapped_column(sa.String(64), comment='用户名')
method: Mapped[str] = mapped_column(sa.String(32), comment='请求类型')
title: Mapped[str] = mapped_column(sa.String(256), comment='操作模块')
path: Mapped[str] = mapped_column(sa.String(512), comment='请求路径')
ip: Mapped[str] = mapped_column(sa.String(64), comment='IP地址')
country: Mapped[str | None] = mapped_column(sa.String(64), comment='国家')
region: Mapped[str | None] = mapped_column(sa.String(64), comment='地区')
city: Mapped[str | None] = mapped_column(sa.String(64), comment='城市')
user_agent: Mapped[str] = mapped_column(sa.String(512), comment='请求头')
os: Mapped[str | None] = mapped_column(sa.String(64), comment='操作系统')
browser: Mapped[str | None] = mapped_column(sa.String(64), comment='浏览器')
device: Mapped[str | None] = mapped_column(sa.String(64), comment='设备')
args: Mapped[str | None] = mapped_column(sa.JSON(), comment='请求参数')
status: Mapped[int] = mapped_column(comment='操作状态(0异常 1正常)')
code: Mapped[str] = mapped_column(String(20), insert_default='200', comment='操作状态码')
msg: Mapped[str | None] = mapped_column(LONGTEXT().with_variant(TEXT, 'postgresql'), comment='提示消息')
code: Mapped[str] = mapped_column(sa.String(32), insert_default='200', comment='操作状态码')
msg: Mapped[str | None] = mapped_column(UniversalText, comment='提示消息')
cost_time: Mapped[float] = mapped_column(insert_default=0.0, comment='请求耗时(ms')
opera_time: Mapped[datetime] = mapped_column(TimeZone, comment='操作时间')
created_time: Mapped[datetime] = mapped_column(
TimeZone,
init=False,
default_factory=timezone.now,
comment='创建时间',
TimeZone, init=False, default_factory=timezone.now, comment='创建时间'
)
+6 -32
View File
@@ -1,17 +1,8 @@
from __future__ import annotations
import sqlalchemy as sa
from typing import TYPE_CHECKING
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy import Boolean, String
from sqlalchemy.dialects.mysql import LONGTEXT
from sqlalchemy.dialects.postgresql import INTEGER, TEXT
from sqlalchemy.orm import Mapped, mapped_column, relationship
from backend.app.admin.model.m2m import sys_role_data_scope, sys_role_menu, sys_user_role
from backend.common.model import Base, id_key
if TYPE_CHECKING:
from backend.app.admin.model import DataScope, Menu, User
from backend.common.model import Base, UniversalText, id_key
class Role(Base):
@@ -20,24 +11,7 @@ class Role(Base):
__tablename__ = 'sys_role'
id: Mapped[id_key] = mapped_column(init=False)
name: Mapped[str] = mapped_column(String(20), unique=True, comment='角色名称')
name: Mapped[str] = mapped_column(sa.String(32), unique=True, comment='角色名称')
status: Mapped[int] = mapped_column(default=1, comment='角色状态(0停用 1正常)')
is_filter_scopes: Mapped[bool] = mapped_column(
Boolean().with_variant(INTEGER, 'postgresql'),
default=True,
comment='过滤数据权限(0否 1是)',
)
remark: Mapped[str | None] = mapped_column(
LONGTEXT().with_variant(TEXT, 'postgresql'),
default=None,
comment='备注',
)
# 角色用户多对多
users: Mapped[list[User]] = relationship(init=False, secondary=sys_user_role, back_populates='roles')
# 角色菜单多对多
menus: Mapped[list[Menu]] = relationship(init=False, secondary=sys_role_menu, back_populates='roles')
# 角色数据范围多对多
scopes: Mapped[list[DataScope]] = relationship(init=False, secondary=sys_role_data_scope, back_populates='roles')
is_filter_scopes: Mapped[bool] = mapped_column(default=True, comment='过滤数据权限(0否 1是)')
remark: Mapped[str | None] = mapped_column(UniversalText, default=None, comment='备注')
+20 -47
View File
@@ -1,20 +1,13 @@
from __future__ import annotations
from datetime import datetime
from typing import TYPE_CHECKING
from sqlalchemy import VARBINARY, Boolean, ForeignKey, String
from sqlalchemy.dialects.postgresql import BYTEA, INTEGER
from sqlalchemy.orm import Mapped, mapped_column, relationship
import sqlalchemy as sa
from sqlalchemy.orm import Mapped, mapped_column
from backend.app.admin.model.m2m import sys_user_role
from backend.common.model import Base, TimeZone, id_key
from backend.database.db import uuid4_str
from backend.utils.timezone import timezone
if TYPE_CHECKING:
from backend.app.admin.model import Dept, Role
class User(Base):
"""用户表"""
@@ -22,45 +15,25 @@ class User(Base):
__tablename__ = 'sys_user'
id: Mapped[id_key] = mapped_column(init=False)
uuid: Mapped[str] = mapped_column(String(50), init=False, default_factory=uuid4_str, unique=True)
username: Mapped[str] = mapped_column(String(20), unique=True, index=True, comment='用户名')
nickname: Mapped[str] = mapped_column(String(20), comment='昵称')
password: Mapped[str | None] = mapped_column(String(255), comment='密码')
salt: Mapped[bytes | None] = mapped_column(VARBINARY(255).with_variant(BYTEA(255), 'postgresql'), comment='加密盐')
email: Mapped[str | None] = mapped_column(String(50), default=None, unique=True, index=True, comment='邮箱')
phone: Mapped[str | None] = mapped_column(String(11), default=None, comment='手机号')
avatar: Mapped[str | None] = mapped_column(String(255), default=None, comment='头像')
uuid: Mapped[str] = mapped_column(sa.String(64), init=False, default_factory=uuid4_str, unique=True)
username: Mapped[str] = mapped_column(sa.String(64), unique=True, index=True, comment='用户名')
nickname: Mapped[str] = mapped_column(sa.String(64), comment='昵称')
password: Mapped[str | None] = mapped_column(sa.String(256), comment='密码')
salt: Mapped[bytes | None] = mapped_column(sa.LargeBinary(255), comment='加密盐')
email: Mapped[str | None] = mapped_column(sa.String(256), default=None, unique=True, index=True, comment='邮箱')
phone: Mapped[str | None] = mapped_column(sa.String(11), default=None, comment='手机号')
avatar: Mapped[str | None] = mapped_column(sa.String(256), default=None, comment='头像')
status: Mapped[int] = mapped_column(default=1, index=True, comment='用户账号状态(0停用 1正常)')
is_superuser: Mapped[bool] = mapped_column(
Boolean().with_variant(INTEGER, 'postgresql'),
default=False,
comment='超级权限(0否 1是)',
)
is_staff: Mapped[bool] = mapped_column(
Boolean().with_variant(INTEGER, 'postgresql'),
default=False,
comment='后台管理登陆(0否 1是)',
)
is_multi_login: Mapped[bool] = mapped_column(
Boolean().with_variant(INTEGER, 'postgresql'),
default=False,
comment='是否重复登陆(0否 1是)',
)
is_superuser: Mapped[bool] = mapped_column(default=False, comment='超级权限(0否 1是)')
is_staff: Mapped[bool] = mapped_column(default=False, comment='后台管理登陆(0否 1是)')
is_multi_login: Mapped[bool] = mapped_column(default=False, comment='是否重复登陆(0否 1是)')
join_time: Mapped[datetime] = mapped_column(TimeZone, init=False, default_factory=timezone.now, comment='注册时间')
last_login_time: Mapped[datetime | None] = mapped_column(
TimeZone,
init=False,
onupdate=timezone.now,
comment='上次登录',
TimeZone, init=False, onupdate=timezone.now, comment='上次登录时间'
)
last_password_changed_time: Mapped[datetime | None] = mapped_column(
TimeZone, init=False, default_factory=timezone.now, comment='上次密码变更时间'
)
# 部门用户一对多
dept_id: Mapped[int | None] = mapped_column(
ForeignKey('sys_dept.id', ondelete='SET NULL'),
default=None,
comment='部门关联ID',
)
dept: Mapped[Dept | None] = relationship(init=False, back_populates='users')
# 用户角色多对多
roles: Mapped[list[Role]] = relationship(init=False, secondary=sys_user_role, back_populates='users')
# 逻辑外键
dept_id: Mapped[int | None] = mapped_column(sa.BigInteger, default=None, comment='部门关联ID')
@@ -0,0 +1,24 @@
from datetime import datetime
import sqlalchemy as sa
from sqlalchemy.orm import Mapped, mapped_column
from backend.common.model import DataClassBase, TimeZone, id_key
from backend.utils.timezone import timezone
class UserPasswordHistory(DataClassBase):
"""用户密码历史记录表"""
__tablename__ = 'sys_user_password_history'
id: Mapped[id_key] = mapped_column(init=False)
user_id: Mapped[int] = mapped_column(sa.BigInteger, index=True, comment='用户 ID')
password: Mapped[str] = mapped_column(sa.String(256), comment='历史密码')
created_time: Mapped[datetime] = mapped_column(
TimeZone,
init=False,
default_factory=timezone.now,
comment='创建时间',
)
+2 -1
View File
@@ -6,6 +6,7 @@ from backend.common.schema import SchemaBase
class GetCaptchaDetail(SchemaBase):
"""验证码详情"""
is_enabled: bool = Field(description='是否启用')
expire_seconds: int = Field(description='过期秒数')
uuid: str = Field(description='图片唯一标识')
img_type: str = Field(description='图片类型')
image: str = Field(description='图片内容')
+1 -1
View File
@@ -34,7 +34,7 @@ class DeleteDataRuleParam(SchemaBase):
class GetDataRuleDetail(DataRuleSchemaBase):
"""数据规则详情"""
model_config = ConfigDict(from_attributes=True)
model_config = ConfigDict(from_attributes=True, frozen=True)
id: int = Field(description='规则 ID')
created_time: datetime = Field(description='创建时间')
+8 -1
View File
@@ -22,6 +22,13 @@ class UpdateDataScopeParam(DataScopeBase):
"""更新数据范围参数"""
class CreateDataScopeRuleParam(SchemaBase):
"""创建数据范围规则参数"""
data_scope_id: int = Field(description='数据范围 ID')
data_rule_id: int = Field(description='数据规则 ID')
class UpdateDataScopeRuleParam(SchemaBase):
"""更新数据范围规则参数"""
@@ -47,4 +54,4 @@ class GetDataScopeDetail(DataScopeBase):
class GetDataScopeWithRelationDetail(GetDataScopeDetail):
"""数据范围关联详情"""
rules: list[GetDataRuleDetail] = Field([], description='数据规则列表')
rules: list[GetDataRuleDetail | None] = Field([], description='数据规则列表')
+16 -2
View File
@@ -2,7 +2,7 @@ from datetime import datetime
from pydantic import ConfigDict, Field
from backend.app.admin.schema.data_scope import GetDataScopeDetail
from backend.app.admin.schema.data_scope import GetDataScopeWithRelationDetail
from backend.app.admin.schema.menu import GetMenuDetail
from backend.common.enums import StatusType
from backend.common.schema import SchemaBase
@@ -31,12 +31,26 @@ class DeleteRoleParam(SchemaBase):
pks: list[int] = Field(description='角色 ID 列表')
class CreateRoleMenuParam(SchemaBase):
"""创建角色菜单参数"""
role_id: int = Field(description='角色 ID')
menu_id: int = Field(description='菜单 ID')
class UpdateRoleMenuParam(SchemaBase):
"""更新角色菜单参数"""
menus: list[int] = Field(description='菜单 ID 列表')
class CreateRoleScopeParam(SchemaBase):
"""创建角色数据范围参数"""
role_id: int = Field(description='角色 ID')
data_scope_id: int = Field(description='数据范围 ID')
class UpdateRoleScopeParam(SchemaBase):
"""更新角色数据范围参数"""
@@ -57,4 +71,4 @@ class GetRoleWithRelationDetail(GetRoleDetail):
"""角色关联详情"""
menus: list[GetMenuDetail | None] = Field([], description='菜单详情列表')
scopes: list[GetDataScopeDetail | None] = Field([], description='数据范围列表')
scopes: list[GetDataScopeWithRelationDetail | None] = Field([], description='数据范围列表')
+1
View File
@@ -30,6 +30,7 @@ class GetNewToken(AccessTokenBase):
class GetLoginToken(AccessTokenBase):
"""获取登录令牌"""
password_expire_days_remaining: int | None = Field(None, description='密码过期剩余天数')
user: GetUserInfoDetail = Field(description='用户信息')
+14 -7
View File
@@ -1,13 +1,13 @@
from datetime import datetime
from typing import Any
from typing import Annotated, Any
from pydantic import ConfigDict, Field, HttpUrl, model_validator
from pydantic import ConfigDict, Field, HttpUrl, PlainSerializer, model_validator
from typing_extensions import Self
from backend.app.admin.schema.dept import GetDeptDetail
from backend.app.admin.schema.role import GetRoleWithRelationDetail
from backend.common.enums import StatusType
from backend.common.schema import CustomEmailStr, CustomPhoneNumber, SchemaBase
from backend.common.schema import CustomEmailStr, CustomPhoneNumber, SchemaBase, ser_string
class AuthSchemaBase(SchemaBase):
@@ -20,8 +20,8 @@ class AuthSchemaBase(SchemaBase):
class AuthLoginParam(AuthSchemaBase):
"""用户登录参数"""
uuid: str = Field(description='验证码 UUID')
captcha: str = Field(description='验证码')
uuid: str | None = Field(None, description='验证码 UUID')
captcha: str | None = Field(None, description='验证码')
class AddUserParam(AuthSchemaBase):
@@ -34,13 +34,20 @@ class AddUserParam(AuthSchemaBase):
roles: list[int] = Field(description='角色 ID 列表')
class AddUserRoleParam(SchemaBase):
"""添加用户角色"""
user_id: int = Field(description='用户 ID')
role_id: int = Field(description='角色 ID')
class AddOAuth2UserParam(AuthSchemaBase):
"""添加 OAuth2 用户参数"""
password: str | None = Field(None, description='密码')
nickname: str | None = Field(None, description='昵称')
email: CustomEmailStr | None = Field(None, description='邮箱')
avatar: HttpUrl | None = Field(None, description='头像地址')
avatar: Annotated[HttpUrl, PlainSerializer(ser_string)] | None = Field(None, description='头像地址')
class ResetPasswordParam(SchemaBase):
@@ -57,7 +64,7 @@ class UserInfoSchemaBase(SchemaBase):
dept_id: int | None = Field(None, description='部门 ID')
username: str = Field(description='用户名')
nickname: str = Field(description='昵称')
avatar: HttpUrl | None = Field(None, description='头像地址')
avatar: Annotated[HttpUrl, PlainSerializer(ser_string)] | None = Field(None, description='头像地址')
email: CustomEmailStr | None = Field(None, description='邮箱')
phone: CustomPhoneNumber | None = Field(None, description='手机号')
@@ -0,0 +1,14 @@
from pydantic import Field
from backend.common.schema import SchemaBase
class UserPasswordHistoryBase(SchemaBase):
"""用户历史密码记录基础模型"""
user_id: int = Field(description='用户 ID')
password: str = Field(description='历史密码')
class CreateUserPasswordHistoryParam(UserPasswordHistoryBase):
"""创建用户历史密码记录"""
+36 -24
View File
@@ -9,6 +9,8 @@ from backend.app.admin.model import User
from backend.app.admin.schema.token import GetLoginToken, GetNewToken
from backend.app.admin.schema.user import AuthLoginParam
from backend.app.admin.service.login_log_service import login_log_service
from backend.app.admin.service.user_password_history_service import password_security_service
from backend.app.admin.utils.password_security import password_verify
from backend.common.context import ctx
from backend.common.enums import LoginLogStatusType
from backend.common.exception import errors
@@ -21,11 +23,11 @@ from backend.common.security.jwt import (
create_refresh_token,
get_token,
jwt_decode,
password_verify,
)
from backend.core.conf import settings
from backend.database.db import uuid4_str
from backend.database.redis import redis_client
from backend.utils.dynamic_config import load_login_config
from backend.utils.timezone import timezone
@@ -33,7 +35,7 @@ class AuthService:
"""认证服务类"""
@staticmethod
async def user_verify(db: AsyncSession, username: str, password: str) -> User:
async def user_verify(db: AsyncSession, username: str, password: str) -> tuple[User, int | None]:
"""
验证用户名和密码
@@ -46,15 +48,19 @@ class AuthService:
if not user:
raise errors.NotFoundError(msg='用户名或密码有误')
if user.password is None:
raise errors.AuthorizationError(msg='用户名或密码有误')
if not password_verify(password, user.password):
await password_security_service.check_status(user.id, user.status)
if user.password is None or not password_verify(password, user.password):
await password_security_service.handle_login_failure(db, user.id)
raise errors.AuthorizationError(msg='用户名或密码有误')
if not user.status:
raise errors.AuthorizationError(msg='用户已被锁定, 请联系统管理员')
days_remaining = await password_security_service.check_password_expiry_status(
db, user.last_password_changed_time
)
return user
await password_security_service.handle_login_success(user.id)
return user, days_remaining
async def swagger_login(self, *, db: AsyncSession, obj: HTTPBasicCredentials) -> tuple[str, User]:
"""
@@ -64,15 +70,15 @@ class AuthService:
:param obj: 登录凭证
:return:
"""
user = await self.user_verify(db, obj.username, obj.password)
user, _ = await self.user_verify(db, obj.username, obj.password)
await user_dao.update_login_time(db, obj.username)
access_token = await create_access_token(
access_token_data = await create_access_token(
user.id,
multi_login=user.is_multi_login,
# extra info
swagger=True,
)
return access_token.access_token, user
return access_token_data.access_token, user
async def login(
self,
@@ -86,7 +92,6 @@ class AuthService:
用户登录
:param db: 数据库会话
:param request: 请求对象
:param response: 响应对象
:param obj: 登录参数
:param background_tasks: 后台任务
@@ -94,16 +99,22 @@ class AuthService:
"""
user = None
try:
user = await self.user_verify(db, obj.username, obj.password)
captcha_code = await redis_client.get(f'{settings.CAPTCHA_LOGIN_REDIS_PREFIX}:{obj.uuid}')
user, days_remaining = await self.user_verify(db, obj.username, obj.password)
await load_login_config(db)
if settings.LOGIN_CAPTCHA_ENABLED:
if not obj.uuid or not obj.captcha:
raise errors.RequestError(msg=t('error.captcha.invalid'))
captcha_code = await redis_client.get(f'{settings.LOGIN_CAPTCHA_REDIS_PREFIX}:{obj.uuid}')
if not captcha_code:
raise errors.RequestError(msg=t('error.captcha.expired'))
if captcha_code.lower() != obj.captcha.lower():
raise errors.CustomError(error=CustomErrorCode.CAPTCHA_ERROR)
await redis_client.delete(f'{settings.CAPTCHA_LOGIN_REDIS_PREFIX}:{obj.uuid}')
await redis_client.delete(f'{settings.LOGIN_CAPTCHA_REDIS_PREFIX}:{obj.uuid}')
await user_dao.update_login_time(db, obj.username)
await db.refresh(user)
access_token = await create_access_token(
access_token_data = await create_access_token(
user.id,
multi_login=user.is_multi_login,
# extra info
@@ -115,16 +126,16 @@ class AuthService:
browser=ctx.browser,
device=ctx.device,
)
refresh_token = await create_refresh_token(
access_token.session_uuid,
refresh_token_data = await create_refresh_token(
access_token_data.session_uuid,
user.id,
multi_login=user.is_multi_login,
)
response.set_cookie(
key=settings.COOKIE_REFRESH_TOKEN_KEY,
value=refresh_token.refresh_token,
value=refresh_token_data.refresh_token,
max_age=settings.COOKIE_REFRESH_TOKEN_EXPIRE_SECONDS,
expires=timezone.to_utc(refresh_token.refresh_token_expire_time),
expires=timezone.to_utc(refresh_token_data.refresh_token_expire_time),
httponly=True,
)
except errors.NotFoundError as e:
@@ -157,9 +168,10 @@ class AuthService:
msg=t('success.login.success'),
)
data = GetLoginToken(
access_token=access_token.access_token,
access_token_expire_time=access_token.access_token_expire_time,
session_uuid=access_token.session_uuid,
access_token=access_token_data.access_token,
access_token_expire_time=access_token_data.access_token_expire_time,
session_uuid=access_token_data.session_uuid,
password_expire_days_remaining=days_remaining,
user=user, # type: ignore
)
return data
@@ -208,7 +220,7 @@ class AuthService:
raise errors.NotFoundError(msg='用户不存在')
if not user.status:
raise errors.AuthorizationError(msg='用户已被锁定, 请联系统管理员')
if not user.is_multi_login and await redis_client.keys(match=f'{settings.TOKEN_REDIS_PREFIX}:{user.id}:*'):
if not user.is_multi_login and await redis_client.get_prefix(f'{settings.TOKEN_REDIS_PREFIX}:{user.id}:*'):
raise errors.ForbiddenError(msg='此用户已在异地登录,请重新登录并及时修改密码')
new_token = await create_new_token(
refresh_token,
@@ -11,6 +11,7 @@ from backend.app.admin.schema.data_rule import (
GetDataRuleColumnDetail,
UpdateDataRuleParam,
)
from backend.app.admin.utils.cache import user_cache_manager
from backend.common.exception import errors
from backend.common.pagination import paging_data
from backend.core.conf import settings
@@ -113,6 +114,7 @@ class DataRuleService:
if data_rule.name != obj.name and await data_rule_dao.get_by_name(db, obj.name):
raise errors.ConflictError(msg='数据规则已存在')
count = await data_rule_dao.update(db, pk, obj)
await user_cache_manager.clear_by_data_rule_id(db, [pk])
return count
@staticmethod
@@ -125,6 +127,7 @@ class DataRuleService:
:return:
"""
count = await data_rule_dao.delete(db, obj.pks)
await user_cache_manager.clear_by_data_rule_id(db, obj.pks)
return count
@@ -11,10 +11,9 @@ from backend.app.admin.schema.data_scope import (
UpdateDataScopeParam,
UpdateDataScopeRuleParam,
)
from backend.app.admin.utils.cache import user_cache_manager
from backend.common.exception import errors
from backend.common.pagination import paging_data
from backend.core.conf import settings
from backend.database.redis import redis_client
class DataScopeService:
@@ -57,7 +56,7 @@ class DataScopeService:
:return:
"""
data_scope = await data_scope_dao.get_with_relation(db, pk)
data_scope = await data_scope_dao.get_join(db, pk)
if not data_scope:
raise errors.NotFoundError(msg='数据范围不存在')
return data_scope
@@ -105,9 +104,7 @@ class DataScopeService:
if data_scope.name != obj.name and await data_scope_dao.get_by_name(db, obj.name):
raise errors.ConflictError(msg='数据范围已存在')
count = await data_scope_dao.update(db, pk, obj)
for role in await data_scope.awaitable_attrs.roles:
for user in await role.awaitable_attrs.users:
await redis_client.delete(f'{settings.JWT_USER_REDIS_PREFIX}:{user.id}')
await user_cache_manager.clear_by_data_scope_id(db, [pk])
return count
@staticmethod
@@ -115,11 +112,13 @@ class DataScopeService:
"""
更新数据范围规则
:param db: 数据库会话
:param pk: 范围 ID
:param rule_ids: 规则 ID 列表
:return:
"""
count = await data_scope_dao.update_rules(db, pk, rule_ids)
await user_cache_manager.clear_by_data_scope_id(db, [pk])
return count
@staticmethod
@@ -132,12 +131,7 @@ class DataScopeService:
:return:
"""
count = await data_scope_dao.delete(db, obj.pks)
for pk in obj.pks:
data_rule = await data_scope_dao.get(db, pk)
if data_rule:
for role in await data_rule.awaitable_attrs.roles:
for user in await role.awaitable_attrs.users:
await redis_client.delete(f'{settings.JWT_USER_REDIS_PREFIX}:{user.id}')
await user_cache_manager.clear_by_data_scope_id(db, obj.pks)
return count
+8 -6
View File
@@ -1,11 +1,11 @@
from typing import Any
from fastapi import Request
from sqlalchemy.ext.asyncio import AsyncSession
from backend.app.admin.crud.crud_dept import dept_dao
from backend.app.admin.model import Dept
from backend.app.admin.schema.dept import CreateDeptParam, UpdateDeptParam
from backend.app.admin.schema.user import GetUserInfoWithRelationDetail
from backend.common.exception import errors
from backend.core.conf import settings
from backend.database.redis import redis_client
@@ -34,7 +34,7 @@ class DeptService:
async def get_tree(
*,
db: AsyncSession,
request: Request,
request_user: GetUserInfoWithRelationDetail,
name: str | None,
leader: str | None,
phone: str | None,
@@ -44,7 +44,7 @@ class DeptService:
获取部门树形结构
:param db: 数据库会话
:param request: FastAPI 请求对象
:param request_user: 请求用户
:param name: 部门名称
:param leader: 部门负责人
:param phone: 联系电话
@@ -52,7 +52,7 @@ class DeptService:
:return:
"""
dept_select = await dept_dao.get_all(request, db, name, leader, phone, status)
dept_select = await dept_dao.get_all(db, request_user, name, leader, phone, status)
tree_data = get_tree_data(dept_select)
return tree_data
@@ -68,7 +68,7 @@ class DeptService:
dept = await dept_dao.get_by_name(db, obj.name)
if dept:
raise errors.ConflictError(msg='部门名称已存在')
if obj.parent_id:
if obj.parent_id is not None:
parent_dept = await dept_dao.get(db, obj.parent_id)
if not parent_dept:
raise errors.NotFoundError(msg='父级部门不存在')
@@ -107,7 +107,9 @@ class DeptService:
:param pk: 部门 ID
:return:
"""
dept = await dept_dao.get_with_relation(db, pk)
dept = await dept_dao.get_join(db, pk)
if not dept:
raise errors.NotFoundError(msg='部门不存在')
if dept.users:
raise errors.ConflictError(msg='部门下存在用户,无法删除')
children = await dept_dao.get_children(db, pk)
+10 -13
View File
@@ -6,9 +6,8 @@ from sqlalchemy.ext.asyncio import AsyncSession
from backend.app.admin.crud.crud_menu import menu_dao
from backend.app.admin.model import Menu
from backend.app.admin.schema.menu import CreateMenuParam, UpdateMenuParam
from backend.app.admin.utils.cache import user_cache_manager
from backend.common.exception import errors
from backend.core.conf import settings
from backend.database.redis import redis_client
from backend.utils.build_tree import get_tree_data, get_vben5_tree_data
@@ -54,7 +53,7 @@ class MenuService:
:param request: FastAPI 请求对象
:return:
"""
menu_data = None
if request.user.is_superuser:
menu_data = await menu_dao.get_sidebar(db, None)
else:
@@ -64,8 +63,11 @@ class MenuService:
for role in roles:
menu_ids.update(menu.id for menu in role.menus)
menu_data = await menu_dao.get_sidebar(db, list(menu_ids))
menu_tree = get_vben5_tree_data(menu_data)
return menu_tree
if menu_data:
return get_vben5_tree_data(menu_data)
return []
@staticmethod
async def create(*, db: AsyncSession, obj: CreateMenuParam) -> None:
@@ -109,9 +111,7 @@ class MenuService:
if obj.parent_id == menu.id:
raise errors.ForbiddenError(msg='禁止关联自身为父级')
count = await menu_dao.update(db, pk, obj)
for role in await menu.awaitable_attrs.roles:
for user in await role.awaitable_attrs.users:
await redis_client.delete(f'{settings.JWT_USER_REDIS_PREFIX}:{user.id}')
await user_cache_manager.clear_by_menu_id(db, [pk])
return count
@staticmethod
@@ -127,12 +127,9 @@ class MenuService:
children = await menu_dao.get_children(db, pk)
if children:
raise errors.ConflictError(msg='菜单下存在子菜单,无法删除')
menu = await menu_dao.get(db, pk)
count = await menu_dao.delete(db, pk)
if menu:
for role in await menu.awaitable_attrs.roles:
for user in await role.awaitable_attrs.users:
await redis_client.delete(f'{settings.JWT_USER_REDIS_PREFIX}:{user.id}')
if count:
await user_cache_manager.clear_by_menu_id(db, [pk])
return count
@@ -48,6 +48,8 @@ class PluginService:
:param repo_url: git 仓库地址
:return:
"""
if settings.ENVIRONMENT != 'dev':
raise errors.RequestError(msg='禁止在非开发环境下安装插件')
if type == PluginType.zip:
if not file:
raise errors.RequestError(msg='ZIP 压缩包不能为空')
@@ -64,6 +66,8 @@ class PluginService:
:param plugin: 插件名称
:return:
"""
if settings.ENVIRONMENT != 'dev':
raise errors.RequestError(msg='禁止在非开发环境下卸载插件')
plugin_dir = anyio.Path(PLUGIN_DIR / plugin)
if not await plugin_dir.exists():
raise errors.NotFoundError(msg='插件不存在')
+10 -17
View File
@@ -14,10 +14,9 @@ from backend.app.admin.schema.role import (
UpdateRoleParam,
UpdateRoleScopeParam,
)
from backend.app.admin.utils.cache import user_cache_manager
from backend.common.exception import errors
from backend.common.pagination import paging_data
from backend.core.conf import settings
from backend.database.redis import redis_client
from backend.utils.build_tree import get_tree_data
@@ -34,7 +33,7 @@ class RoleService:
:return:
"""
role = await role_dao.get_with_relation(db, pk)
role = await role_dao.get_join(db, pk)
if not role:
raise errors.NotFoundError(msg='角色不存在')
return role
@@ -74,10 +73,11 @@ class RoleService:
:return:
"""
role = await role_dao.get_with_relation(db, pk)
role = await role_dao.get(db, pk)
if not role:
raise errors.NotFoundError(msg='角色不存在')
menu_tree = get_tree_data(role.menus) if role.menus else []
menus = await role_dao.get_menus(db, pk)
menu_tree = get_tree_data(menus) if menus else []
return menu_tree
@staticmethod
@@ -90,7 +90,7 @@ class RoleService:
:return:
"""
role = await role_dao.get_with_relation(db, pk)
role = await role_dao.get_join(db, pk)
if not role:
raise errors.NotFoundError(msg='角色不存在')
scope_ids = [scope.id for scope in role.scopes]
@@ -128,8 +128,7 @@ class RoleService:
if role.name != obj.name and await role_dao.get_by_name(db, obj.name):
raise errors.ConflictError(msg='角色已存在')
count = await role_dao.update(db, pk, obj)
for user in await role.awaitable_attrs.users:
await redis_client.delete_prefix(f'{settings.JWT_USER_REDIS_PREFIX}:{user.id}')
await user_cache_manager.clear_by_role_id(db, [pk])
return count
@staticmethod
@@ -151,8 +150,7 @@ class RoleService:
if not menu:
raise errors.NotFoundError(msg='菜单不存在')
count = await role_dao.update_menus(db, pk, menu_ids)
for user in await role.awaitable_attrs.users:
await redis_client.delete_prefix(f'{settings.JWT_USER_REDIS_PREFIX}:{user.id}')
await user_cache_manager.clear_by_role_id(db, [pk])
return count
@staticmethod
@@ -174,8 +172,7 @@ class RoleService:
if not scope:
raise errors.NotFoundError(msg='数据范围不存在')
count = await role_dao.update_scopes(db, pk, scope_ids)
for user in await role.awaitable_attrs.users:
await redis_client.delete(f'{settings.JWT_USER_REDIS_PREFIX}:{user.id}')
await user_cache_manager.clear_by_role_id(db, [pk])
return count
@staticmethod
@@ -189,11 +186,7 @@ class RoleService:
"""
count = await role_dao.delete(db, obj.pks)
for pk in obj.pks:
role = await role_dao.get(db, pk)
if role:
for user in await role.awaitable_attrs.users:
await redis_client.delete(f'{settings.JWT_USER_REDIS_PREFIX}:{user.id}')
await user_cache_manager.clear_by_role_id(db, obj.pks)
return count
@@ -0,0 +1,118 @@
import math
from datetime import datetime, timedelta
from sqlalchemy.ext.asyncio import AsyncSession
from backend.app.admin.crud.crud_user_password_history import user_password_history_dao
from backend.app.admin.schema.user_password_history import CreateUserPasswordHistoryParam
from backend.common.exception import errors
from backend.core.conf import settings
from backend.database.redis import redis_client
from backend.utils.dynamic_config import load_user_security_config
from backend.utils.timezone import timezone
class UserPasswordHistoryService:
"""用户密码历史服务类"""
@staticmethod
async def check_status(user_id: int, user_status: int) -> None:
"""
检查用户状态
:param user_id: 用户 ID
:param user_status: 用户状态
:return:
"""
if not user_status:
raise errors.AuthorizationError(msg='用户已被锁定, 请联系统管理员')
locked_until_str = await redis_client.get(f'{settings.USER_LOCK_REDIS_PREFIX}:{user_id}')
if locked_until_str:
locked_until = timezone.from_str(locked_until_str)
now = timezone.now()
if locked_until > now:
remaining_minutes = math.ceil((locked_until - now).total_seconds() / 60)
raise errors.AuthorizationError(msg=f'账号已被锁定,请在 {remaining_minutes} 分钟后重试')
await redis_client.delete(f'{settings.USER_LOCK_REDIS_PREFIX}:{user_id}')
await redis_client.delete(f'{settings.LOGIN_FAILURE_PREFIX}:{user_id}')
@staticmethod
async def handle_login_failure(db: AsyncSession, user_id: int) -> None:
"""
处理登录失败
:param db: 数据库会话
:param user_id: 用户 ID
:return:
"""
await load_user_security_config(db)
if settings.USER_LOCK_THRESHOLD == 0:
return
failure_count = await redis_client.get(f'{settings.LOGIN_FAILURE_PREFIX}:{user_id}')
failure_count = int(failure_count) if failure_count else 0
failure_count += 1
await redis_client.set(f'{settings.LOGIN_FAILURE_PREFIX}:{user_id}', str(failure_count))
if failure_count >= settings.USER_LOCK_THRESHOLD:
locked_until = timezone.now() + timedelta(seconds=settings.USER_LOCK_SECONDS)
await redis_client.set(f'{settings.USER_LOCK_REDIS_PREFIX}:{user_id}', timezone.to_str(locked_until))
raise errors.AuthorizationError(msg='登录失败次数过多,账号已被锁定')
@staticmethod
async def check_password_expiry_status(db: AsyncSession, password_changed_time: datetime) -> int | None:
"""
检查密码过期状态
:param db: 数据库会话
:param password_changed_time: 密码修改时间
:return:
"""
await load_user_security_config(db)
if settings.USER_PASSWORD_EXPIRY_DAYS == 0:
return None
if not password_changed_time:
raise errors.AuthorizationError(msg='密码已过期,请修改密码后重新登录')
expiry_time = password_changed_time + timedelta(days=settings.USER_PASSWORD_EXPIRY_DAYS)
days_remaining = (expiry_time - timezone.now()).days
if days_remaining < 0:
raise errors.AuthorizationError(msg='密码已过期,请修改密码后重新登录')
if days_remaining <= settings.USER_PASSWORD_REMINDER_DAYS:
return days_remaining
return None
@staticmethod
async def handle_login_success(user_id: int) -> None:
"""
处理登录成功
:param user_id: 用户 ID
:return:
"""
await redis_client.delete(f'{settings.USER_LOCK_REDIS_PREFIX}:{user_id}')
await redis_client.delete(f'{settings.LOGIN_FAILURE_PREFIX}:{user_id}')
@staticmethod
async def save_password_history(db: AsyncSession, obj: CreateUserPasswordHistoryParam) -> None:
"""
保存密码历史记录
:param db: 数据库会话
:param obj: 创建密码历史记录参数
:return:
"""
await user_password_history_dao.create(db, obj)
password_security_service: UserPasswordHistoryService = UserPasswordHistoryService()
+54 -46
View File
@@ -15,14 +15,18 @@ from backend.app.admin.schema.user import (
ResetPasswordParam,
UpdateUserParam,
)
from backend.app.admin.schema.user_password_history import CreateUserPasswordHistoryParam
from backend.app.admin.service.user_password_history_service import password_security_service
from backend.app.admin.utils.password_security import password_verify, validate_new_password
from backend.common.context import ctx
from backend.common.enums import UserPermissionType
from backend.common.exception import errors
from backend.common.pagination import paging_data
from backend.common.response.response_code import CustomErrorCode
from backend.common.security.jwt import get_token, jwt_decode, password_verify
from backend.common.security.jwt import get_token, jwt_decode
from backend.core.conf import settings
from backend.database.redis import redis_client
from backend.utils.serializers import select_join_serialize
class UserService:
@@ -38,7 +42,7 @@ class UserService:
:param username: 用户名
:return:
"""
user = await user_dao.get_with_relation(db, user_id=pk, username=username)
user = await user_dao.get_join(db, user_id=pk, username=username)
if not user:
raise errors.NotFoundError(msg='用户不存在')
return user
@@ -52,7 +56,7 @@ class UserService:
:param pk: 用户 ID
:return:
"""
user = await user_dao.get_with_relation(db, user_id=pk)
user = await user_dao.get_join(db, user_id=pk)
if not user:
raise errors.NotFoundError(msg='用户不存在')
return user.roles
@@ -70,7 +74,12 @@ class UserService:
:return:
"""
user_select = await user_dao.get_select(dept=dept, username=username, phone=phone, status=status)
return await paging_data(db, user_select)
data = await paging_data(db, user_select)
if data['items']:
serialized_items = select_join_serialize(data['items'], relationships=['User-m2o-Dept', 'User-m2m-Role'])
# 确保返回的是列表,即使只有一个元素
data['items'] = [serialized_items] if not isinstance(serialized_items, list) else serialized_items
return data
@staticmethod
async def create(*, db: AsyncSession, obj: AddUserParam) -> None:
@@ -103,15 +112,17 @@ class UserService:
:param obj: 用户更新参数
:return:
"""
user = await user_dao.get_with_relation(db, user_id=pk)
user = await user_dao.get_join(db, user_id=pk)
if not user:
raise errors.NotFoundError(msg='用户不存在')
if obj.username != user.username and await user_dao.get_by_username(db, obj.username):
raise errors.ConflictError(msg='用户名已注册')
if obj.dept_id and obj.dept_id != user.dept_id and not await dept_dao.get(db, dept_id=obj.dept_id):
raise errors.NotFoundError(msg='部门不存在')
for role_id in obj.roles:
if not await role_dao.get(db, role_id):
raise errors.NotFoundError(msg='角色不存在')
count = await user_dao.update(db, user, obj)
count = await user_dao.update(db, user.id, obj)
await redis_client.delete(f'{settings.JWT_USER_REDIS_PREFIX}:{user.id}')
return count
@@ -189,7 +200,14 @@ class UserService:
user = await user_dao.get(db, pk)
if not user:
raise errors.NotFoundError(msg='用户不存在')
await validate_new_password(db, user.id, password)
count = await user_dao.reset_password(db, user.id, password)
history_obj = CreateUserPasswordHistoryParam(user_id=user.id, password=user.password)
await password_security_service.save_password_history(db, history_obj)
await user_dao.update_password_changed_time(db, user.id)
key_prefix = [
f'{settings.TOKEN_REDIS_PREFIX}:{user.id}',
f'{settings.TOKEN_REFRESH_REDIS_PREFIX}:{user.id}',
@@ -200,93 +218,83 @@ class UserService:
return count
@staticmethod
async def update_nickname(*, db: AsyncSession, request: Request, nickname: str) -> int:
async def update_nickname(*, db: AsyncSession, user_id: int, nickname: str) -> int:
"""
更新当前用户昵称
:param db: 数据库会话
:param request: FastAPI 请求对象
:param user_id: 用户 ID
:param nickname: 用户昵称
:return:
"""
token = get_token(request)
token_payload = jwt_decode(token)
user = await user_dao.get(db, token_payload.id)
if not user:
raise errors.NotFoundError(msg='用户不存在')
count = await user_dao.update_nickname(db, token_payload.id, nickname)
await redis_client.delete(f'{settings.JWT_USER_REDIS_PREFIX}:{user.id}')
count = await user_dao.update_nickname(db, user_id, nickname)
await redis_client.delete(f'{settings.JWT_USER_REDIS_PREFIX}:{user_id}')
return count
@staticmethod
async def update_avatar(*, db: AsyncSession, request: Request, avatar: str) -> int:
async def update_avatar(*, db: AsyncSession, user_id: int, avatar: str) -> int:
"""
更新当前用户头像
:param db: 数据库会话
:param request: FastAPI 请求对象
:param user_id: 用户 ID
:param avatar: 头像地址
:return:
"""
token = get_token(request)
token_payload = jwt_decode(token)
user = await user_dao.get(db, token_payload.id)
if not user:
raise errors.NotFoundError(msg='用户不存在')
count = await user_dao.update_avatar(db, token_payload.id, avatar)
await redis_client.delete(f'{settings.JWT_USER_REDIS_PREFIX}:{user.id}')
count = await user_dao.update_avatar(db, user_id, avatar)
await redis_client.delete(f'{settings.JWT_USER_REDIS_PREFIX}:{user_id}')
return count
@staticmethod
async def update_email(*, db: AsyncSession, request: Request, captcha: str, email: str) -> int:
async def update_email(*, db: AsyncSession, user_id: int, captcha: str, email: str) -> int:
"""
更新当前用户邮箱
:param db: 数据库会话
:param request: FastAPI 请求对象
:param user_id: 用户 ID
:param captcha: 邮箱验证码
:param email: 邮箱
:return:
"""
token = get_token(request)
token_payload = jwt_decode(token)
user = await user_dao.get(db, token_payload.id)
if not user:
raise errors.NotFoundError(msg='用户不存在')
captcha_code = await redis_client.get(f'{settings.EMAIL_CAPTCHA_REDIS_PREFIX}:{ctx.ip}')
if not captcha_code:
raise errors.RequestError(msg='验证码已失效,请重新获取')
if captcha != captcha_code:
raise errors.CustomError(error=CustomErrorCode.CAPTCHA_ERROR)
await redis_client.delete(f'{settings.EMAIL_CAPTCHA_REDIS_PREFIX}:{ctx.ip}')
count = await user_dao.update_email(db, token_payload.id, email)
await redis_client.delete(f'{settings.JWT_USER_REDIS_PREFIX}:{user.id}')
count = await user_dao.update_email(db, user_id, email)
await redis_client.delete(f'{settings.JWT_USER_REDIS_PREFIX}:{user_id}')
return count
@staticmethod
async def update_password(*, db: AsyncSession, request: Request, obj: ResetPasswordParam) -> int:
async def update_password(*, db: AsyncSession, user_id: int, obj: ResetPasswordParam) -> int:
"""
更新当前用户密码
:param db: 数据库会话
:param request: FastAPI 请求对象
:param user_id: 用户 ID
:param obj: 密码重置参数
:return:
"""
token = get_token(request)
token_payload = jwt_decode(token)
user = await user_dao.get(db, token_payload.id)
if not user:
raise errors.NotFoundError(msg='用户不存在')
if not password_verify(obj.old_password, user.password):
user = await user_dao.get(db, user_id)
if user.password and not password_verify(obj.old_password, user.password):
raise errors.RequestError(msg='原密码错误')
if obj.new_password != obj.confirm_password:
raise errors.RequestError(msg='密码输入不一致')
count = await user_dao.reset_password(db, user.id, obj.new_password)
raise errors.RequestError(msg='两次密码输入不一致')
await validate_new_password(db, user_id, obj.new_password)
count = await user_dao.reset_password(db, user_id, obj.new_password)
history_obj = CreateUserPasswordHistoryParam(user_id=user.id, password=user.password)
await password_security_service.save_password_history(db, history_obj)
await user_dao.update_password_changed_time(db, user.id)
key_prefix = [
f'{settings.TOKEN_REDIS_PREFIX}:{user.id}',
f'{settings.TOKEN_REFRESH_REDIS_PREFIX}:{user.id}',
f'{settings.JWT_USER_REDIS_PREFIX}:{user.id}',
f'{settings.TOKEN_REDIS_PREFIX}:{user_id}',
f'{settings.TOKEN_REFRESH_REDIS_PREFIX}:{user_id}',
f'{settings.JWT_USER_REDIS_PREFIX}:{user_id}',
]
for prefix in key_prefix:
await redis_client.delete_prefix(prefix)
View File
+98
View File
@@ -0,0 +1,98 @@
from collections.abc import Sequence
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from backend.app.admin.model import data_scope_rule, role_data_scope, role_menu, user_role
from backend.core.conf import settings
from backend.database.redis import redis_client
class UserCacheManager:
"""用户缓存管理"""
@staticmethod
async def clear(user_ids: Sequence[int]) -> None:
"""
清理用户缓存
:param user_ids: 用户 ID 列表
:return:
"""
if user_ids:
await redis_client.delete(*[f'{settings.JWT_USER_REDIS_PREFIX}:{user_id}' for user_id in user_ids])
async def clear_by_role_id(self, db: AsyncSession, role_ids: list[int]) -> None:
"""
通过角色 ID 清理用户缓存
:param db: 数据库会话
:param role_ids: 角色 ID 列表
:return:
"""
stmt = select(user_role.c.user_id).where(user_role.c.role_id.in_(role_ids)).distinct()
result = await db.execute(stmt)
user_ids = result.scalars().all()
await self.clear(user_ids)
async def clear_by_menu_id(self, db: AsyncSession, menu_ids: list[int]) -> None:
"""
通过菜单 ID 清理用户缓存
:param db: 数据库会话
:param menu_ids: 菜单 ID 列表
:return:
"""
stmt = (
select(user_role.c.user_id)
.join(role_menu, user_role.c.role_id == role_menu.c.role_id)
.where(role_menu.c.menu_id.in_(menu_ids))
.distinct()
)
result = await db.execute(stmt)
user_ids = result.scalars().all()
await self.clear(user_ids)
async def clear_by_data_scope_id(self, db: AsyncSession, scope_ids: list[int]) -> None:
"""
通过数据范围 ID 清理用户缓存
:param db: 数据库会话
:param scope_ids: 数据范围 ID 列表
:return:
"""
stmt = (
select(user_role.c.user_id)
.join(role_data_scope, user_role.c.role_id == role_data_scope.c.role_id)
.where(role_data_scope.c.data_scope_id.in_(scope_ids))
.distinct()
)
result = await db.execute(stmt)
user_ids = result.scalars().all()
await self.clear(user_ids)
async def clear_by_data_rule_id(self, db: AsyncSession, rule_ids: list[int]) -> None:
"""
通过数据规则 ID 清理用户缓存
:param db: 数据库会话
:param rule_ids: 数据规则 ID 列表
:return:
"""
stmt = (
select(user_role.c.user_id)
.join(role_data_scope, user_role.c.role_id == role_data_scope.c.role_id)
.join(data_scope_rule, role_data_scope.c.data_scope_id == data_scope_rule.c.data_scope_id)
.where(data_scope_rule.c.data_rule_id.in_(rule_ids))
.distinct()
)
result = await db.execute(stmt)
user_ids = result.scalars().all()
await self.clear(user_ids)
user_cache_manager: UserCacheManager = UserCacheManager()
@@ -0,0 +1,68 @@
from pwdlib import PasswordHash
from pwdlib.hashers.bcrypt import BcryptHasher
from sqlalchemy.ext.asyncio import AsyncSession
from backend.app.admin.crud.crud_user_password_history import user_password_history_dao
from backend.common.exception import errors
from backend.core.conf import settings
from backend.utils.dynamic_config import load_user_security_config
from backend.utils.re_verify import is_has_letter, is_has_number, is_has_special_char
password_hash = PasswordHash((BcryptHasher(),))
def get_hash_password(password: str, salt: bytes | None) -> str:
"""
使用哈希算法加密密码
:param password: 密码
:param salt: 盐值
:return:
"""
return password_hash.hash(password, salt=salt)
def password_verify(plain_password: str, hashed_password: str) -> bool:
"""
密码验证
:param plain_password: 待验证的密码
:param hashed_password: 哈希密码
:return:
"""
return password_hash.verify(plain_password, hashed_password)
async def validate_new_password(db: AsyncSession, user_id: int, new_password: str) -> None:
"""
验证新密码
:param db: 数据库会话
:param user_id: 用户ID
:param new_password: 新密码
:return:
"""
await load_user_security_config(db)
if len(new_password) < settings.USER_PASSWORD_MIN_LENGTH:
raise errors.RequestError(msg=f'密码长度不能少于 {settings.USER_PASSWORD_MIN_LENGTH} 个字符')
if len(new_password) > settings.USER_PASSWORD_MAX_LENGTH:
raise errors.RequestError(msg=f'密码长度不能超过 {settings.USER_PASSWORD_MAX_LENGTH} 个字符')
if not is_has_number(new_password):
raise errors.RequestError(msg='密码必须包含数字')
if not is_has_letter(new_password):
raise errors.RequestError(msg='密码必须包含字母')
if settings.USER_PASSWORD_REQUIRE_SPECIAL_CHAR and not is_has_special_char(new_password):
raise errors.RequestError(msg='密码必须包含特殊字符(如:!@#$%')
password_history = await user_password_history_dao.get_by_user_id(db, user_id)
for hist in password_history[: settings.USER_PASSWORD_HISTORY_CHECK_COUNT]:
if password_verify(new_password, hist.password):
raise errors.RequestError(
msg=f'新密码不能与最近 {settings.USER_PASSWORD_HISTORY_CHECK_COUNT} 次使用的密码相同'
)
+3 -3
View File
@@ -5,8 +5,8 @@ from backend.app.task.api.v1.result import router as task_result_router
from backend.app.task.api.v1.scheduler import router as task_scheduler_router
from backend.core.conf import settings
v1 = APIRouter(prefix=f'{settings.FASTAPI_API_V1_PATH}/tasks', tags=['任务'])
v1 = APIRouter(prefix=settings.FASTAPI_API_V1_PATH, tags=['任务'])
v1.include_router(task_control_router)
v1.include_router(task_result_router, prefix='/results')
v1.include_router(task_control_router, prefix='/tasks')
v1.include_router(task_result_router, prefix='/task-results')
v1.include_router(task_scheduler_router, prefix='/schedulers')
+2 -2
View File
@@ -117,8 +117,8 @@ async def delete_task_scheduler(
@router.post(
'/{pk}/executions',
summary='手动执行任务',
'/{pk}/execute',
summary='执行任务',
dependencies=[
Depends(RequestPermission('sys:task:exec')),
DependsRBAC,
+10 -5
View File
@@ -27,15 +27,20 @@ def init_celery() -> celery.Celery:
celery.app.trace.build_tracer = celery_aio_pool.build_async_tracer
celery.app.trace.reset_worker_optimizations()
broker_url = f'amqp://{settings.CELERY_RABBITMQ_USERNAME}:{settings.CELERY_RABBITMQ_PASSWORD}@{settings.CELERY_RABBITMQ_HOST}:{settings.CELERY_RABBITMQ_PORT}/{settings.CELERY_RABBITMQ_VHOST}'
if settings.CELERY_BROKER == 'redis':
broker_url = f'redis://:{settings.REDIS_PASSWORD}@{settings.REDIS_HOST}:{settings.REDIS_PORT}/{settings.CELERY_BROKER_REDIS_DATABASE}'
result_backend = f'db+postgresql+psycopg://{settings.DATABASE_USER}:{settings.DATABASE_PASSWORD}@{settings.DATABASE_HOST}:{settings.DATABASE_PORT}/{settings.DATABASE_SCHEMA}'
if settings.DATABASE_TYPE == 'mysql':
result_backend = result_backend.replace('postgresql+psycopg', 'mysql+pymysql')
# https://docs.celeryq.dev/en/stable/userguide/configuration.html
app = celery.Celery(
'fba_celery',
broker_url=f'redis://:{settings.REDIS_PASSWORD}@{settings.REDIS_HOST}:{settings.REDIS_PORT}/{settings.CELERY_BROKER_REDIS_DATABASE}'
if settings.CELERY_BROKER == 'redis'
else f'amqp://{settings.CELERY_RABBITMQ_USERNAME}:{settings.CELERY_RABBITMQ_PASSWORD}@{settings.CELERY_RABBITMQ_HOST}:{settings.CELERY_RABBITMQ_PORT}',
broker_url=broker_url,
broker_connection_retry_on_startup=True,
result_backend=f'db+{settings.DATABASE_TYPE}+{"pymysql" if settings.DATABASE_TYPE == "mysql" else "psycopg"}'
f'://{settings.DATABASE_USER}:{settings.DATABASE_PASSWORD}@{settings.DATABASE_HOST}:{settings.DATABASE_PORT}/{settings.DATABASE_SCHEMA}',
result_backend=result_backend,
result_extended=True,
database_engine_options={'echo': settings.DATABASE_ECHO},
# result_expires=0,
+7 -8
View File
@@ -1,11 +1,10 @@
from datetime import datetime, timezone
import sqlalchemy as sa
from celery import states
from sqlalchemy.types import PickleType
from backend.common.model import MappedBase
from backend.common.model import MappedBase, TimeZone
from backend.utils.timezone import timezone
"""
重写 celery.backends.database.models 内部所有模型适配 fba 创建表和 alembic 迁移
@@ -20,12 +19,12 @@ class Task(MappedBase):
id = sa.Column(sa.Integer, sa.Sequence('task_id_sequence'), primary_key=True, autoincrement=True)
task_id = sa.Column(sa.String(155), unique=True)
status = sa.Column(sa.String(50), default=states.PENDING)
status = sa.Column(sa.String(64), default=states.PENDING)
result = sa.Column(PickleType, nullable=True)
date_done = sa.Column(
sa.DateTime,
default=datetime.now(timezone.utc),
onupdate=datetime.now(timezone.utc),
TimeZone,
default=timezone.now,
onupdate=timezone.now,
nullable=True,
)
traceback = sa.Column(sa.Text, nullable=True)
@@ -87,7 +86,7 @@ class TaskSet(MappedBase):
id = sa.Column(sa.Integer, sa.Sequence('taskset_id_sequence'), autoincrement=True, primary_key=True)
taskset_id = sa.Column(sa.String(155), unique=True)
result = sa.Column(PickleType, nullable=True)
date_done = sa.Column(sa.DateTime, default=datetime.now(timezone.utc), nullable=True)
date_done = sa.Column(TimeZone, default=timezone.now, nullable=True)
def __init__(self, taskset_id, result) -> None: # noqa: ANN001
self.taskset_id = taskset_id
+16 -33
View File
@@ -2,18 +2,13 @@ import asyncio
from datetime import datetime
from sqlalchemy import (
JSON,
Boolean,
String,
event,
)
from sqlalchemy.dialects.mysql import LONGTEXT
from sqlalchemy.dialects.postgresql import INTEGER, TEXT
import sqlalchemy as sa
from sqlalchemy import event
from sqlalchemy.orm import Mapped, mapped_column
from backend.common.exception import errors
from backend.common.model import Base, TimeZone, id_key
from backend.common.model import Base, TimeZone, UniversalText, id_key
from backend.core.conf import settings
from backend.database.redis import redis_client
from backend.utils.timezone import timezone
@@ -25,37 +20,25 @@ class TaskScheduler(Base):
__tablename__ = 'task_scheduler'
id: Mapped[id_key] = mapped_column(init=False)
name: Mapped[str] = mapped_column(String(50), unique=True, comment='任务名称')
task: Mapped[str] = mapped_column(String(255), comment='要运行的 Celery 任务')
args: Mapped[str | None] = mapped_column(JSON(), comment='任务可接收的位置参数')
kwargs: Mapped[str | None] = mapped_column(JSON(), comment='任务可接收的关键字参数')
queue: Mapped[str | None] = mapped_column(String(255), comment='CELERY_TASK_QUEUES 中定义的队列')
exchange: Mapped[str | None] = mapped_column(String(255), comment='低级别 AMQP 路由的交换机')
routing_key: Mapped[str | None] = mapped_column(String(255), comment='低级别 AMQP 路由的路由密钥')
name: Mapped[str] = mapped_column(sa.String(64), unique=True, comment='任务名称')
task: Mapped[str] = mapped_column(sa.String(256), comment='要运行的 Celery 任务')
args: Mapped[str | None] = mapped_column(sa.JSON(), comment='任务可接收的位置参数')
kwargs: Mapped[str | None] = mapped_column(sa.JSON(), comment='任务可接收的关键字参数')
queue: Mapped[str | None] = mapped_column(sa.String(256), comment='CELERY_TASK_QUEUES 中定义的队列')
exchange: Mapped[str | None] = mapped_column(sa.String(256), comment='低级别 AMQP 路由的交换机')
routing_key: Mapped[str | None] = mapped_column(sa.String(256), comment='低级别 AMQP 路由的路由密钥')
start_time: Mapped[datetime | None] = mapped_column(TimeZone, comment='任务开始触发的时间')
expire_time: Mapped[datetime | None] = mapped_column(TimeZone, comment='任务不再触发的截止时间')
expire_seconds: Mapped[int | None] = mapped_column(comment='任务不再触发的秒数时间差')
type: Mapped[int] = mapped_column(comment='调度类型(0间隔 1定时)')
interval_every: Mapped[int | None] = mapped_column(comment='任务再次运行前的间隔周期数')
interval_period: Mapped[str | None] = mapped_column(String(255), comment='任务运行之间的周期类型')
crontab: Mapped[str | None] = mapped_column(String(50), default='* * * * *', comment='任务运行的 Crontab 计划')
one_off: Mapped[bool] = mapped_column(
Boolean().with_variant(INTEGER, 'postgresql'),
default=False,
comment='是否仅运行一次',
)
enabled: Mapped[bool] = mapped_column(
Boolean().with_variant(INTEGER, 'postgresql'),
default=True,
comment='是否启用任务',
)
interval_period: Mapped[str | None] = mapped_column(sa.String(256), comment='任务运行之间的周期类型')
crontab: Mapped[str | None] = mapped_column(sa.String(64), default='* * * * *', comment='任务运行的 Crontab 计划')
one_off: Mapped[bool] = mapped_column(default=False, comment='是否仅运行一次')
enabled: Mapped[bool] = mapped_column(default=True, comment='是否启用任务')
total_run_count: Mapped[int] = mapped_column(default=0, comment='任务触发的总次数')
last_run_time: Mapped[datetime | None] = mapped_column(TimeZone, default=None, comment='任务最后触发的时间')
remark: Mapped[str | None] = mapped_column(
LONGTEXT().with_variant(TEXT, 'postgresql'),
default=None,
comment='备注',
)
remark: Mapped[str | None] = mapped_column(UniversalText, default=None, comment='备注')
no_changes: bool = False
+5 -2
View File
@@ -2,17 +2,20 @@ from celery import shared_task
from backend.app.admin.service.login_log_service import login_log_service
from backend.app.admin.service.opera_log_service import opera_log_service
from backend.database.db import async_db_session
@shared_task
async def delete_db_opera_log() -> str:
"""自动删除数据库操作日志"""
await opera_log_service.delete_all()
async with async_db_session.begin() as db:
await opera_log_service.delete_all(db=db)
return 'Success'
@shared_task
async def delete_db_login_log() -> str:
"""自动删除数据库登录日志"""
await login_log_service.delete_all()
async with async_db_session.begin() as db:
await login_log_service.delete_all(db=db)
return 'Success'
+1 -1
View File
@@ -399,7 +399,7 @@ class DatabaseScheduler(Scheduler):
"""获取所有任务调度"""
async with async_db_session() as db:
logger.debug('DatabaseScheduler: Fetching database schedule')
stmt = select(TaskScheduler).where(TaskScheduler.enabled == 1)
stmt = select(TaskScheduler).where(TaskScheduler.enabled == True) # noqa: E712
query = await db.execute(stmt)
schedulers = query.scalars().all()
s = {}
+26 -9
View File
@@ -1,5 +1,6 @@
import asyncio
import subprocess
import sys
from dataclasses import dataclass
from typing import Annotated, Literal
@@ -23,7 +24,7 @@ from backend.database.db import async_db_session
from backend.plugin.code_generator.schema.code import ImportParam
from backend.plugin.code_generator.service.business_service import gen_business_service
from backend.plugin.code_generator.service.code_service import gen_service
from backend.plugin.tools import get_plugin_sql
from backend.plugin.tools import get_plugin_sql, get_plugins
from backend.utils._await import run_await
from backend.utils.console import console
from backend.utils.file_ops import install_git_plugin, install_zip_plugin, parse_sql_script
@@ -45,16 +46,32 @@ def run(host: str, port: int, reload: bool, workers: int) -> None: # noqa: FBT0
openapi_url = url + (settings.FASTAPI_OPENAPI_URL or '')
panel_content = Text()
panel_content.append(f'当前版本: v{__version__}')
panel_content.append(f'\n服务地址: {url}')
panel_content.append('\n官方文档: https://fastapi-practices.github.io/fastapi_best_architecture_docs/')
panel_content.append('Python 版本:', style='bold cyan')
panel_content.append(f'{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}', style='white')
panel_content.append('\nAPI 请求地址: ', style='bold cyan')
panel_content.append(f'{url}{settings.FASTAPI_API_V1_PATH}', style='blue')
panel_content.append('\n\n环境模式:', style='bold green')
env_style = 'yellow' if settings.ENVIRONMENT == 'dev' else 'green'
panel_content.append(f'{settings.ENVIRONMENT.upper()}', style=env_style)
plugins = get_plugins()
panel_content.append('\n已安装插件:', style='bold green')
if plugins:
panel_content.append(f'{", ".join(plugins)}', style='yellow')
else:
panel_content.append('', style='white')
if settings.ENVIRONMENT == 'dev':
panel_content.append(f'\n\n📖 Swagger 文档: {docs_url}', style='yellow')
panel_content.append(f'\n📚 Redoc 文档: {redoc_url}', style='blue')
panel_content.append(f'\n📡 OpenAPI JSON: {openapi_url}', style='green')
panel_content.append(f'\n\n📖 Swagger 文档: {docs_url}', style='bold magenta')
panel_content.append(f'\n📚 Redoc 文档: {redoc_url}', style='bold magenta')
panel_content.append(f'\n📡 OpenAPI JSON: {openapi_url}', style='bold magenta')
console.print(Panel(panel_content, title='fba 服务信息', border_style='purple', padding=(1, 2)))
panel_content.append('\n🌐 架构官方文档: ', style='bold magenta')
panel_content.append('https://fastapi-practices.github.io/fastapi_best_architecture_docs/')
console.print(Panel(panel_content, title=f'fba v{__version__}', border_style='purple', padding=(1, 2)))
granian.Granian(
target='backend.main:app',
interface='asgi',
@@ -276,7 +293,7 @@ class Add:
]
db_type: Annotated[
DataBaseType,
cappa.Arg(default='mysql', help='执行插件 SQL 脚本的数据库类型'),
cappa.Arg(default='postgresql', help='执行插件 SQL 脚本的数据库类型'),
]
pk_type: Annotated[
PrimaryKeyType,
+2 -2
View File
@@ -70,6 +70,6 @@ class UploadUrl:
class SnowflakeInfo:
timestamp: int
datetime: str
cluster_id: int
node_id: int
datacenter_id: int
worker_id: int
sequence: int
-8
View File
@@ -103,14 +103,6 @@ class StatusType(IntEnum):
enable = 1
class UserSocialType(StrEnum):
"""用户社交类型"""
github = 'GitHub'
google = 'Google'
linux_do = 'LinuxDo'
class FileType(StrEnum):
"""文件类型"""
+1
View File
@@ -16,6 +16,7 @@ class I18n:
def __init__(self) -> None:
self.locales: dict[str, dict[str, Any]] = {}
self.current_language: str = settings.I18N_DEFAULT_LANGUAGE
self.load_locales()
def load_locales(self) -> None:
"""加载语言文本"""
+22 -7
View File
@@ -1,10 +1,12 @@
from datetime import datetime
from typing import Annotated
from sqlalchemy import BigInteger, DateTime, TypeDecorator
from sqlalchemy import BigInteger, DateTime, Text, TypeDecorator
from sqlalchemy.dialects.mysql import LONGTEXT
from sqlalchemy.ext.asyncio import AsyncAttrs
from sqlalchemy.orm import DeclarativeBase, Mapped, MappedAsDataclass, declared_attr, mapped_column
from backend.core.conf import settings
from backend.utils.snowflake import snowflake
from backend.utils.timezone import timezone
@@ -41,16 +43,21 @@ snowflake_id_key = Annotated[
]
# Mixin: 一种面向对象编程概念, 使结构变得更加清晰, `Wiki <https://en.wikipedia.org/wiki/Mixin/>`__
class UserMixin(MappedAsDataclass):
"""用户 Mixin 数据类"""
class UniversalText(TypeDecorator[str]):
"""PostgreSQL、MySQL 兼容性(长)文本类型"""
created_by: Mapped[int] = mapped_column(sort_order=998, comment='创建者')
updated_by: Mapped[int | None] = mapped_column(init=False, default=None, sort_order=998, comment='修改者')
impl = LONGTEXT if settings.DATABASE_TYPE == 'mysql' else Text
cache_ok = True
def process_bind_param(self, value: str | None, dialect) -> str | None: # noqa: ANN001
return value
def process_result_value(self, value: str | None, dialect) -> str | None: # noqa: ANN001
return value
class TimeZone(TypeDecorator[datetime]):
"""时区感知 DateTime"""
"""PostgreSQL、MySQL 兼容性时区感知类型"""
impl = DateTime(timezone=True)
cache_ok = True
@@ -71,6 +78,14 @@ class TimeZone(TypeDecorator[datetime]):
return value
# Mixin: 一种面向对象编程概念, 使结构变得更加清晰, `Wiki <https://en.wikipedia.org/wiki/Mixin/>`__
class UserMixin(MappedAsDataclass):
"""用户 Mixin 数据类"""
created_by: Mapped[int] = mapped_column(sort_order=998, comment='创建者')
updated_by: Mapped[int | None] = mapped_column(init=False, default=None, sort_order=998, comment='修改者')
class DateTimeMixin(MappedAsDataclass):
"""日期时间 Mixin 数据类"""
+7 -1
View File
@@ -1,5 +1,5 @@
from datetime import datetime
from typing import Annotated
from typing import Annotated, Any
from pydantic import BaseModel, ConfigDict, EmailStr, Field, validate_email
@@ -27,3 +27,9 @@ class SchemaBase(BaseModel):
else timezone.to_str(x),
},
)
def ser_string(value: Any) -> str | None:
if value:
return str(value)
return value
+7 -53
View File
@@ -1,16 +1,13 @@
import json
import uuid
from datetime import timedelta
from typing import Any
from uuid import uuid4
from fastapi import Depends, HTTPException, Request
from fastapi import Depends, Request
from fastapi.security import HTTPBearer
from fastapi.security.http import HTTPAuthorizationCredentials
from fastapi.security.utils import get_authorization_scheme_param
from jose import ExpiredSignatureError, JWTError, jwt
from pwdlib import PasswordHash
from pwdlib.hashers.bcrypt import BcryptHasher
from pydantic_core import from_json
from sqlalchemy.ext.asyncio import AsyncSession
@@ -18,56 +15,13 @@ from backend.app.admin.model import User
from backend.app.admin.schema.user import GetUserInfoWithRelationDetail
from backend.common.dataclasses import AccessToken, NewToken, RefreshToken, TokenPayload
from backend.common.exception import errors
from backend.common.exception.errors import TokenError
from backend.core.conf import settings
from backend.database.db import async_db_session
from backend.database.redis import redis_client
from backend.utils.serializers import select_as_dict
from backend.utils.timezone import timezone
class CustomHTTPBearer(HTTPBearer):
"""
自定义 HTTPBearer 认证类
Issues: https://github.com/fastapi/fastapi/issues/10177
"""
async def __call__(self, request: Request) -> HTTPAuthorizationCredentials | None:
try:
return await super().__call__(request)
except HTTPException as e:
if e.status_code == 403:
raise TokenError
raise
# JWT authorizes dependency injection
DependsJwtAuth = Depends(CustomHTTPBearer())
password_hash = PasswordHash((BcryptHasher(),))
def get_hash_password(password: str, salt: bytes | None) -> str:
"""
使用哈希算法加密密码
:param password: 密码
:param salt: 盐值
:return:
"""
return password_hash.hash(password, salt=salt)
def password_verify(plain_password: str, hashed_password: str) -> bool:
"""
密码验证
:param plain_password: 待验证的密码
:param hashed_password: 哈希密码
:return:
"""
return password_hash.verify(plain_password, hashed_password)
# JWT dependency injection
DependsJwtAuth = Depends(HTTPBearer())
def jwt_encode(payload: dict[str, Any]) -> str:
@@ -120,7 +74,7 @@ async def create_access_token(user_id: int, *, multi_login: bool, **kwargs) -> A
:return:
"""
expire = timezone.now() + timedelta(seconds=settings.TOKEN_EXPIRE_SECONDS)
session_uuid = str(uuid4())
session_uuid = str(uuid.uuid4())
access_token = jwt_encode({
'session_uuid': session_uuid,
'exp': timezone.to_utc(expire).timestamp(),
@@ -246,7 +200,7 @@ async def get_current_user(db: AsyncSession, pk: int) -> User:
"""
from backend.app.admin.crud.crud_user import user_dao
user = await user_dao.get_with_relation(db, user_id=pk)
user = await user_dao.get_join(db, user_id=pk)
if not user:
raise errors.TokenError(msg='Token 无效')
if not user.status:
@@ -297,7 +251,7 @@ async def jwt_authentication(token: str) -> GetUserInfoWithRelationDetail:
if not cache_user:
async with async_db_session() as db:
current_user = await get_current_user(db, user_id)
user = GetUserInfoWithRelationDetail(**select_as_dict(current_user))
user = GetUserInfoWithRelationDetail.model_validate(current_user)
await redis_client.setex(
f'{settings.JWT_USER_REDIS_PREFIX}:{user_id}',
settings.TOKEN_EXPIRE_SECONDS,
+13 -25
View File
@@ -1,8 +1,7 @@
from fastapi import Request
from sqlalchemy import ColumnElement, and_, or_
from sqlalchemy.ext.asyncio import AsyncSession
from backend.app.admin.crud.crud_data_scope import data_scope_dao
from backend.app.admin.schema.user import GetUserInfoWithRelationDetail
from backend.common.context import ctx
from backend.common.enums import RoleDataRuleExpressionType, RoleDataRuleOperatorType
from backend.common.exception import errors
@@ -42,54 +41,43 @@ class RequestPermission:
ctx.permission = self.value
async def filter_data_permission(db: AsyncSession, request: Request) -> ColumnElement[bool]: # noqa: C901
def filter_data_permission(request_user: GetUserInfoWithRelationDetail) -> ColumnElement[bool]: # noqa: C901
"""
过滤数据权限控制用户可见数据范围
使用场景
- 控制用户能看到哪些数据
:param db: 数据库会话
:param request: FastAPI 请求对象
:param request_user: 请求用户
:return:
"""
# 是否过滤数据权限
if request.user.is_superuser:
if request_user.is_superuser:
return or_(1 == 1)
for role in request.user.roles:
for role in request_user.roles:
if not role.is_filter_scopes:
return or_(1 == 1)
# 获取数据范围
data_scope_ids = set()
for role in request.user.roles:
# 获取数据规则
data_rules = set()
for role in request_user.roles:
for scope in role.scopes:
if scope.status:
data_scope_ids.add(scope.id)
data_rules.update(scope.rules)
# 无规则用户不做过滤
if not list(data_scope_ids):
if not list(data_rules):
return or_(1 == 1)
# 获取数据范围规则
unique_data_rules = {}
for data_scope_id in list(data_scope_ids):
data_scope_with_relation = await data_scope_dao.get_with_relation(db, data_scope_id)
for rule in data_scope_with_relation.rules:
unique_data_rules[rule.id] = rule
# 转换为列表
data_rule_list = list(unique_data_rules.values())
where_and_list = []
where_or_list = []
for data_rule in data_rule_list:
for data_rule in list(data_rules):
# 验证规则模型
rule_model = data_rule.model
if rule_model not in settings.DATA_PERMISSION_MODELS:
raise errors.NotFoundError(msg='数据规则模型不存在')
raise errors.NotFoundError(msg='数据规则可用模型不存在')
model_ins = dynamic_import_data_model(settings.DATA_PERMISSION_MODELS[rule_model])
# 验证规则列
@@ -98,7 +86,7 @@ async def filter_data_permission(db: AsyncSession, request: Request) -> ColumnEl
]
column = data_rule.column
if column not in model_columns:
raise errors.NotFoundError(msg='数据规则模型列不存在')
raise errors.NotFoundError(msg='数据规则可用模型列不存在')
# 构建过滤条件
column_obj = getattr(model_ins, column)
+37 -6
View File
@@ -52,6 +52,15 @@ class Settings(BaseSettings):
# Redis
REDIS_TIMEOUT: int = 5
# .env Snowflake
SNOWFLAKE_DATACENTER_ID: int | None = None
SNOWFLAKE_WORKER_ID: int | None = None
# Snowflake
SNOWFLAKE_REDIS_PREFIX: str = 'fba:snowflake'
SNOWFLAKE_HEARTBEAT_INTERVAL_SECONDS: int = 30
SNOWFLAKE_NODE_TTL_SECONDS: int = 60
# .env Token
TOKEN_SECRET_KEY: str # 密钥 secrets.token_urlsafe(32)
@@ -70,6 +79,23 @@ class Settings(BaseSettings):
rf'^{FASTAPI_API_V1_PATH}/monitors/(redis|server)$',
]
# 用户安全
USER_LOCK_REDIS_PREFIX: str = 'fba:user:lock'
USER_LOCK_THRESHOLD: int = 5 # 用户密码错误锁定阈值,0 表示禁用锁定
USER_LOCK_SECONDS: int = 60 * 5 # 5 分钟
USER_PASSWORD_EXPIRY_DAYS: int = 365 # 用户密码有效期,0 表示永不过期
USER_PASSWORD_REMINDER_DAYS: int = 7 # 用户密码到期提醒,0 表示不提醒
USER_PASSWORD_HISTORY_CHECK_COUNT: int = 3
USER_PASSWORD_MIN_LENGTH: int = 6
USER_PASSWORD_MAX_LENGTH: int = 32
USER_PASSWORD_REQUIRE_SPECIAL_CHAR: bool = False
# 登录
LOGIN_CAPTCHA_ENABLED: bool = True
LOGIN_CAPTCHA_REDIS_PREFIX: str = 'fba:login:captcha'
LOGIN_CAPTCHA_EXPIRE_SECONDS: int = 60 * 5 # 5 分钟
LOGIN_FAILURE_PREFIX: str = 'fba:login:failure'
# JWT
JWT_USER_REDIS_PREFIX: str = 'fba:user'
@@ -84,13 +110,9 @@ class Settings(BaseSettings):
COOKIE_REFRESH_TOKEN_KEY: str = 'fba_refresh_token'
COOKIE_REFRESH_TOKEN_EXPIRE_SECONDS: int = 60 * 60 * 24 * 7 # 7 天
# 验证码
CAPTCHA_LOGIN_REDIS_PREFIX: str = 'fba:login:captcha'
CAPTCHA_LOGIN_EXPIRE_SECONDS: int = 60 * 5 # 3 分钟
# 数据权限
DATA_PERMISSION_MODELS: dict[str, str] = { # 允许进行数据过滤的 SQLA 模型,它必须以模块字符串的方式定义
'部门': 'backend.app.admin.model.Dept',
'Dept': 'backend.app.admin.model.Dept',
}
DATA_PERMISSION_COLUMN_EXCLUDE: list[str] = [ # 排除允许进行数据过滤的 SQLA 模型列
'id',
@@ -173,6 +195,7 @@ class Settings(BaseSettings):
'/openapi',
f'{FASTAPI_API_V1_PATH}/auth/login/swagger',
f'{FASTAPI_API_V1_PATH}/oauth2/github/callback',
f'{FASTAPI_API_V1_PATH}/oauth2/google/callback',
f'{FASTAPI_API_V1_PATH}/oauth2/linux-do/callback',
]
OPERA_LOG_ENCRYPT_TYPE: int = 1 # 0: AES (性能损耗); 1: md5; 2: ItsDangerous; 3: 不加密, others: 替换为 ******
@@ -188,6 +211,7 @@ class Settings(BaseSettings):
# Plugin 配置
PLUGIN_PIP_CHINA: bool = True
PLUGIN_PIP_INDEX_URL: str = 'https://mirrors.aliyun.com/pypi/simple/'
PLUGIN_PIP_MAX_RETRY: int = 3
PLUGIN_REDIS_PREFIX: str = 'fba:plugin'
# I18n 配置
@@ -208,6 +232,7 @@ class Settings(BaseSettings):
# 基础配置
CELERY_BROKER: Literal['rabbitmq', 'redis'] = 'redis'
CELERY_RABBITMQ_VHOST: str = ''
CELERY_REDIS_PREFIX: str = 'fba:celery'
CELERY_TASK_MAX_RETRIES: int = 5
@@ -228,7 +253,13 @@ class Settings(BaseSettings):
OAUTH2_LINUX_DO_CLIENT_SECRET: str
# 基础配置
OAUTH2_FRONTEND_REDIRECT_URI: str = 'http://localhost:5173/oauth2/callback'
OAUTH2_STATE_REDIS_PREFIX: str = 'fba:oauth2:state'
OAUTH2_STATE_EXPIRE_SECONDS: int = 60 * 3 # 3 分钟
OAUTH2_GITHUB_REDIRECT_URI: str = 'http://127.0.0.1:8000/api/v1/oauth2/github/callback'
OAUTH2_GOOGLE_REDIRECT_URI: str = 'http://127.0.0.1:8000/api/v1/oauth2/google/callback'
OAUTH2_LINUX_DO_REDIRECT_URI: str = 'http://127.0.0.1:8000/api/v1/oauth2/linux-do/callback'
OAUTH2_FRONTEND_LOGIN_REDIRECT_URI: str = 'http://localhost:5173/oauth2/callback'
OAUTH2_FRONTEND_BINDING_REDIRECT_URI: str = 'http://localhost:5173/profile'
##################################################
# [ Plugin ] email
+7
View File
@@ -34,6 +34,7 @@ from backend.utils.demo_site import demo_site
from backend.utils.health_check import ensure_unique_route_names, http_limit_callback
from backend.utils.openapi import simplify_operation_ids
from backend.utils.serializers import MsgSpecJSONResponse
from backend.utils.snowflake import snowflake
@asynccontextmanager
@@ -57,11 +58,17 @@ async def register_init(app: FastAPI) -> AsyncGenerator[None, None]:
http_callback=http_limit_callback,
)
# 初始化 snowflake 节点
await snowflake.init()
# 创建操作日志任务
create_task(OperaLogMiddleware.consumer())
yield
# 释放 snowflake 节点
await snowflake.shutdown()
# 关闭 redis 连接
await redis_client.aclose()
+26 -14
View File
@@ -38,26 +38,38 @@ class RedisCli(Redis):
log.error('❌ 数据库 redis 连接异常 {}', e)
sys.exit()
async def delete_prefix(self, prefix: str, exclude: str | list[str] | None = None) -> None:
async def delete_prefix(self, prefix: str, exclude: str | list[str] | None = None, batch_size: int = 1000) -> None:
"""
删除指定前缀的所有 key
:param prefix: 前缀
:param exclude: 排除的 key
:param prefix: 要删除的键前缀
:param exclude: 排除的键或键列表
:param batch_size: 批量删除的大小避免一次性删除过多键导致 Redis 阻塞
:return:
"""
keys = []
exclude_set = set(exclude) if isinstance(exclude, list) else {exclude} if isinstance(exclude, str) else set()
batch_keys = []
async for key in self.scan_iter(match=f'{prefix}*'):
if isinstance(exclude, str):
if key != exclude:
keys.append(key)
elif isinstance(exclude, list):
if key not in exclude:
keys.append(key)
else:
keys.append(key)
if keys:
await self.delete(*keys)
if key not in exclude_set:
batch_keys.append(key)
if len(batch_keys) >= batch_size:
await self.delete(*batch_keys)
batch_keys.clear()
if batch_keys:
await self.delete(*batch_keys)
async def get_prefix(self, prefix: str, count: int = 100) -> list[str]:
"""
获取指定前缀的所有 key
:param prefix: 要搜索的键前缀
:param count: 每次扫描批次的数量值越大扫描速度越快但会占用更多服务器资源
:return:
"""
return [key async for key in self.scan_iter(match=f'{prefix}*', count=count)]
# 创建 redis 客户端单例
+1
View File
@@ -2,6 +2,7 @@
"error": {
"captcha": {
"error": "Captcha error",
"invalid": "Captcha is invalid, please try again",
"expired": "Captcha has expired, please try again"
},
"language_not_found": "Current language pack is not initialized or does not exist"
+1
View File
@@ -1,6 +1,7 @@
error:
captcha:
error: 验证码错误
invalid: 验证码无效,请重新获取
expired: 验证码已过期,请重新获取
language_not_found: 当前语言包未初始化或不存在
pydantic:
-8
View File
@@ -32,12 +32,4 @@ class AccessMiddleware(BaseHTTPMiddleware):
response = await call_next(request)
if request.method != 'OPTIONS':
log.debug('<-- 请求结束')
log.info(
f'{request.client.host: <15} | {request.method: <8} | {response.status_code: <6} | '
f'{path} | {(time.perf_counter() - perf_time) * 1000:.3f}ms',
)
return response
-2
View File
@@ -1,5 +1,4 @@
from collections.abc import Callable
from functools import lru_cache
from fastapi import Request, Response
from starlette.middleware.base import BaseHTTPMiddleware
@@ -7,7 +6,6 @@ from starlette.middleware.base import BaseHTTPMiddleware
from backend.common.i18n import i18n
@lru_cache
def get_current_language(request: Request) -> str | None:
"""
获取当前请求的语言偏好
+5 -2
View File
@@ -51,7 +51,7 @@ class OperaLogMiddleware(BaseHTTPMiddleware):
error = None
try:
response = await call_next(request)
elapsed = (time.perf_counter() - ctx.perf_time) * 1000
elapsed = round((time.perf_counter() - ctx.perf_time) * 1000, 3)
for e in [
'__request_http_exception__',
'__request_validation_exception__',
@@ -65,7 +65,7 @@ class OperaLogMiddleware(BaseHTTPMiddleware):
log.error(f'请求异常: {msg}')
break
except Exception as e:
elapsed = (time.perf_counter() - ctx.perf_time) * 1000
elapsed = round((time.perf_counter() - ctx.perf_time) * 1000, 3)
code = getattr(e, 'code', StandardResponseCode.HTTP_500) # 兼容 SQLAlchemy 异常用法
msg = getattr(e, 'msg', str(e)) # 不建议使用 traceback 模块获取错误信息,会暴漏代码信息
status = StatusType.disable
@@ -86,6 +86,9 @@ class OperaLogMiddleware(BaseHTTPMiddleware):
log.debug(f'接口摘要:[{summary}]')
log.debug(f'请求地址:[{ctx.ip}]')
log.debug(f'请求参数:{args}')
log.info(f'{request.client.host: <15} | {request.method: <8} | {code!s: <6} | {path} | {elapsed:.3f}ms')
if request.method != 'OPTIONS':
log.debug('<-- 请求结束')
# 日志创建
opera_log_in = CreateOperaLogParam(
+3 -3
View File
@@ -2,11 +2,11 @@ from fastapi import APIRouter
from backend.core.conf import settings
from backend.plugin.code_generator.api.v1.business import router as business_router
from backend.plugin.code_generator.api.v1.code import router as gen_router
from backend.plugin.code_generator.api.v1.column import router as column_router
from backend.plugin.code_generator.api.v1.gen import router as gen_router
v1 = APIRouter(prefix=f'{settings.FASTAPI_API_V1_PATH}/generates', tags=['代码生成'])
v1 = APIRouter(prefix=f'{settings.FASTAPI_API_V1_PATH}/code-generation', tags=['代码生成'])
v1.include_router(business_router, prefix='/businesses')
v1.include_router(column_router, prefix='/columns')
v1.include_router(gen_router, prefix='/codes')
v1.include_router(gen_router, prefix='/generations')
@@ -37,7 +37,7 @@ async def import_table(db: CurrentSessionTransaction, obj: ImportParam) -> Respo
return response_base.success()
@router.get('/{pk}/previews', summary='代码生成预览', dependencies=[DependsJwtAuth])
@router.get('/{pk}/preview', summary='代码生成预览', dependencies=[DependsJwtAuth])
async def preview_code(
db: CurrentSession, pk: Annotated[int, Path(description='业务 ID')]
) -> ResponseSchemaModel[dict[str, bytes]]:
@@ -54,7 +54,7 @@ async def get_generate_paths(
@router.post(
'/{pk}/generation',
'/{pk}',
summary='代码生成',
description='文件磁盘写入,请谨慎操作',
dependencies=[
@@ -52,7 +52,7 @@ class CRUDGenBusiness(CRUDPlus[GenBusiness]):
if table_name is not None:
filters['table_name__like'] = f'%{table_name}%'
return await self.select_order('id', 'desc', load_strategies={'gen_column': 'noload'}, **filters)
return await self.select_order('id', 'desc', **filters)
async def create(self, db: AsyncSession, obj: CreateGenBusinessParam) -> None:
"""
+17 -27
View File
@@ -1,16 +1,8 @@
from __future__ import annotations
import sqlalchemy as sa
from typing import TYPE_CHECKING
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy import String
from sqlalchemy.dialects.mysql import LONGTEXT
from sqlalchemy.dialects.postgresql import TEXT
from sqlalchemy.orm import Mapped, mapped_column, relationship
from backend.common.model import Base, id_key
if TYPE_CHECKING:
from backend.plugin.code_generator.model import GenColumn
from backend.common.model import Base, UniversalText, id_key
class GenBusiness(Base):
@@ -19,21 +11,19 @@ class GenBusiness(Base):
__tablename__ = 'gen_business'
id: Mapped[id_key] = mapped_column(init=False)
app_name: Mapped[str] = mapped_column(String(50), comment='应用名称(英文)')
table_name: Mapped[str] = mapped_column(String(255), unique=True, comment='表名称(英文)')
doc_comment: Mapped[str] = mapped_column(String(255), comment='文档注释(用于函数/参数文档)')
table_comment: Mapped[str | None] = mapped_column(String(255), default=None, comment='表描述')
app_name: Mapped[str] = mapped_column(sa.String(64), comment='应用名称(英文)')
table_name: Mapped[str] = mapped_column(sa.String(256), unique=True, comment='表名称(英文)')
doc_comment: Mapped[str] = mapped_column(sa.String(256), comment='文档注释(用于函数/参数文档)')
table_comment: Mapped[str | None] = mapped_column(sa.String(256), default=None, comment='表描述')
# relate_model_fk: Mapped[int | None] = mapped_column(default=None, comment='关联表外键')
class_name: Mapped[str | None] = mapped_column(String(50), default=None, comment='基础类名(默认为英文表名称)')
schema_name: Mapped[str | None] = mapped_column(String(50), default=None, comment='Schema 名称 (默认为英文表名称)')
filename: Mapped[str | None] = mapped_column(String(50), default=None, comment='基础文件名(默认为英文表名称')
default_datetime_column: Mapped[bool] = mapped_column(default=True, comment='是否存在默认时间列')
api_version: Mapped[str] = mapped_column(String(20), default='v1', comment='代码生成 api 版本,默认为 v1')
gen_path: Mapped[str | None] = mapped_column(String(255), default=None, comment='代码生成路径(默认为 app 根路径)')
remark: Mapped[str | None] = mapped_column(
LONGTEXT().with_variant(TEXT, 'postgresql'),
default=None,
comment='备注',
class_name: Mapped[str | None] = mapped_column(sa.String(64), default=None, comment='基础类名(默认为英文表名称)')
schema_name: Mapped[str | None] = mapped_column(
sa.String(64), default=None, comment='Schema 名称 (默认为英文表名称)'
)
# 代码生成业务模型列一对多
gen_column: Mapped[list[GenColumn]] = relationship(init=False, back_populates='gen_business')
filename: Mapped[str | None] = mapped_column(sa.String(64), default=None, comment='基础文件名(默认为英文表名称)')
default_datetime_column: Mapped[bool] = mapped_column(default=True, comment='是否存在默认时间列')
api_version: Mapped[str] = mapped_column(sa.String(32), default='v1', comment='代码生成 api 版本,默认为 v1')
gen_path: Mapped[str | None] = mapped_column(
sa.String(256), default=None, comment='代码生成路径(默认为 app 根路径)'
)
remark: Mapped[str | None] = mapped_column(UniversalText, default=None, comment='备注')
+10 -28
View File
@@ -1,16 +1,8 @@
from __future__ import annotations
import sqlalchemy as sa
from typing import TYPE_CHECKING
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy import BigInteger, ForeignKey, String
from sqlalchemy.dialects.mysql import LONGTEXT
from sqlalchemy.dialects.postgresql import TEXT
from sqlalchemy.orm import Mapped, mapped_column, relationship
from backend.common.model import DataClassBase, id_key
if TYPE_CHECKING:
from backend.plugin.code_generator.model import GenBusiness
from backend.common.model import DataClassBase, UniversalText, id_key
class GenColumn(DataClassBase):
@@ -19,25 +11,15 @@ class GenColumn(DataClassBase):
__tablename__ = 'gen_column'
id: Mapped[id_key] = mapped_column(init=False)
name: Mapped[str] = mapped_column(String(50), comment='列名称')
comment: Mapped[str | None] = mapped_column(String(255), default=None, comment='列描述')
type: Mapped[str] = mapped_column(String(20), default='String', comment='SQLA 模型列类型')
pd_type: Mapped[str] = mapped_column(String(20), default='str', comment='列类型对应的 pydantic 类型')
default: Mapped[str | None] = mapped_column(
LONGTEXT().with_variant(TEXT, 'postgresql'),
default=None,
comment='列默认值',
)
name: Mapped[str] = mapped_column(sa.String(64), comment='列名称')
comment: Mapped[str | None] = mapped_column(sa.String(256), default=None, comment='列描述')
type: Mapped[str] = mapped_column(sa.String(32), default='String', comment='SQLA 模型列类型')
pd_type: Mapped[str] = mapped_column(sa.String(32), default='str', comment='列类型对应的 pydantic 类型')
default: Mapped[str | None] = mapped_column(UniversalText, default=None, comment='列默认值')
sort: Mapped[int | None] = mapped_column(default=1, comment='列排序')
length: Mapped[int] = mapped_column(default=0, comment='列长度')
is_pk: Mapped[bool] = mapped_column(default=False, comment='是否主键')
is_nullable: Mapped[bool] = mapped_column(default=False, comment='是否可为空')
# 代码生成业务模型列一对多
gen_business_id: Mapped[int] = mapped_column(
BigInteger,
ForeignKey('gen_business.id', ondelete='CASCADE'),
default=0,
comment='代码生成业务ID',
)
gen_business: Mapped[GenBusiness | None] = relationship(init=False, back_populates='gen_column')
# 逻辑外键
gen_business_id: Mapped[int] = mapped_column(sa.BigInteger, default=0, comment='代码生成业务ID')
+1 -1
View File
@@ -1,6 +1,6 @@
[plugin]
summary = '代码生成'
version = '0.0.5'
version = '0.0.7'
description = '生成通用业务代码'
author = 'wu-clan'
@@ -3,8 +3,9 @@ from collections.abc import Sequence
from sqlalchemy.ext.asyncio import AsyncSession
from backend.common.exception import errors
from backend.core.conf import settings
from backend.plugin.code_generator.crud.crud_column import gen_column_dao
from backend.plugin.code_generator.enums import GenMySQLColumnType
from backend.plugin.code_generator.enums import GenMySQLColumnType, GenPostgreSQLColumnType
from backend.plugin.code_generator.model import GenColumn
from backend.plugin.code_generator.schema.column import CreateGenColumnParam, UpdateGenColumnParam
from backend.plugin.code_generator.utils.type_conversion import sql_type_to_pydantic
@@ -30,8 +31,11 @@ class GenColumnService:
@staticmethod
async def get_types() -> list[str]:
"""获取所有 MySQL 列类型"""
"""获取所有列类型"""
if settings.DATABASE_TYPE == 'mysql':
types = GenMySQLColumnType.get_member_keys()
else:
types = GenPostgreSQLColumnType.get_member_keys()
types.sort()
return types
@@ -15,7 +15,6 @@ from backend.common.security.jwt import DependsJwtAuth
from backend.common.security.permission import RequestPermission
from backend.common.security.rbac import DependsRBAC
from backend.database.db import CurrentSession, CurrentSessionTransaction
from backend.database.db import CurrentSession
router = APIRouter()
@@ -1,7 +1,10 @@
from functools import lru_cache
from backend.core.conf import settings
from backend.plugin.code_generator.enums import GenMySQLColumnType, GenPostgreSQLColumnType
@lru_cache(maxsize=128)
def sql_type_to_sqlalchemy(typing: str) -> str:
"""
SQL 类型转换为 SQLAlchemy 类型
@@ -18,6 +21,7 @@ def sql_type_to_sqlalchemy(typing: str) -> str:
return 'String'
@lru_cache(maxsize=128)
def sql_type_to_pydantic(typing: str) -> str:
"""
SQL 类型转换为 Pydantic 类型
+9
View File
@@ -0,0 +1,9 @@
from backend.common.enums import StrEnum
class ConfigType(StrEnum):
"""配置类型"""
email = 'EMAIL'
user_security = 'USER_SECURITY'
login = 'LOGIN'
+9 -18
View File
@@ -1,9 +1,8 @@
from sqlalchemy import Boolean, String
from sqlalchemy.dialects.mysql import LONGTEXT
from sqlalchemy.dialects.postgresql import INTEGER, TEXT
import sqlalchemy as sa
from sqlalchemy.orm import Mapped, mapped_column
from backend.common.model import Base, id_key
from backend.common.model import Base, UniversalText, id_key
class Config(Base):
@@ -12,17 +11,9 @@ class Config(Base):
__tablename__ = 'sys_config'
id: Mapped[id_key] = mapped_column(init=False)
name: Mapped[str] = mapped_column(String(20), comment='名称')
type: Mapped[str | None] = mapped_column(String(20), server_default=None, comment='类型')
key: Mapped[str] = mapped_column(String(50), unique=True, comment='键名')
value: Mapped[str] = mapped_column(LONGTEXT().with_variant(TEXT, 'postgresql'), comment='键值')
is_frontend: Mapped[bool] = mapped_column(
Boolean().with_variant(INTEGER, 'postgresql'),
default=False,
comment='是否前端',
)
remark: Mapped[str | None] = mapped_column(
LONGTEXT().with_variant(TEXT, 'postgresql'),
default=None,
comment='备注',
)
name: Mapped[str] = mapped_column(sa.String(32), comment='名称')
type: Mapped[str | None] = mapped_column(sa.String(32), server_default=None, comment='类型')
key: Mapped[str] = mapped_column(sa.String(64), unique=True, comment='键名')
value: Mapped[str] = mapped_column(UniversalText, comment='键值')
is_frontend: Mapped[bool] = mapped_column(default=False, comment='是否前端')
remark: Mapped[str | None] = mapped_column(UniversalText, default=None, comment='备注')
+17 -6
View File
@@ -1,8 +1,19 @@
insert into sys_config (id, name, type, `key`, value, is_frontend, remark, created_time, updated_time)
values
(1, '状态', 'EMAIL', 'EMAIL_STATUS', '1', 0, null, now(), null),
(2, '服务器地址', 'EMAIL', 'EMAIL_HOST', 'smtp.qq.com', 0, null, now(), null),
(3, '服务器端口', 'EMAIL', 'EMAIL_PORT', '465', 0, null, now(), null),
(4, '邮箱账号', 'EMAIL', 'EMAIL_USERNAME', 'fba@qq.com', 0, null, now(), null),
(5, '邮箱密码', 'EMAIL', 'EMAIL_PASSWORD', '', 0, null, now(), null),
(6, 'SSL 加密', 'EMAIL', 'EMAIL_SSL', '1', 0, null, now(), null);
(1, '状态', 'EMAIL', 'EMAIL_STATUS', '1', false, null, now(), null),
(2, '服务器地址', 'EMAIL', 'EMAIL_HOST', 'smtp.qq.com', false, null, now(), null),
(3, '服务器端口', 'EMAIL', 'EMAIL_PORT', '465', false, null, now(), null),
(4, '邮箱账号', 'EMAIL', 'EMAIL_USERNAME', 'fba@qq.com', false, null, now(), null),
(5, '邮箱密码', 'EMAIL', 'EMAIL_PASSWORD', '', false, null, now(), null),
(6, 'SSL 加密', 'EMAIL', 'EMAIL_SSL', 'true', false, null, now(), null),
(7, '状态', 'USER_SECURITY', 'USER_SECURITY_CONFIG_STATUS', '1', false, null, now(), null),
(8, '密码错误锁定阈值', 'USER_SECURITY', 'USER_LOCK_THRESHOLD', '5', false, '0 表示禁用锁定', now(), null),
(9, '密码错误锁定时长(秒)', 'USER_SECURITY', 'USER_LOCK_SECONDS', '300', false, null, now(), null),
(10, '密码有效期(天)', 'USER_SECURITY', 'USER_PASSWORD_EXPIRY_DAYS', '365', false, '0 表示永不过期', now(), null),
(11, '密码到期提醒(天)', 'USER_SECURITY', 'USER_PASSWORD_REMINDER_DAYS', '7', false, '0 表示不提醒', now(), null),
(12, '密码历史检查次数', 'USER_SECURITY', 'USER_PASSWORD_HISTORY_CHECK_COUNT', '3', false, null, now(), null),
(13, '密码最小长度', 'USER_SECURITY', 'USER_PASSWORD_MIN_LENGTH', '6', false, null, now(), null),
(14, '密码最大长度', 'USER_SECURITY', 'USER_PASSWORD_MAX_LENGTH', '32', false, null, now(), null),
(15, '密码必须包含特殊字符', 'USER_SECURITY', 'USER_PASSWORD_REQUIRE_SPECIAL_CHAR', 'false', false, null, now(), null),
(16, '状态', 'LOGIN', 'LOGIN_CONFIG_STATUS', '1', false, null, now(), null),
(17, '验证码开关', 'LOGIN', 'LOGIN_CAPTCHA_ENABLED', 'true', false, null, now(), null);
@@ -1,8 +1,19 @@
insert into sys_config (id, name, type, `key`, value, is_frontend, remark, created_time, updated_time)
values
(2069061886627938304, '状态', 'EMAIL', 'EMAIL_STATUS', '1', 0, null, now(), null),
(2069061886627938305, '服务器地址', 'EMAIL', 'EMAIL_HOST', 'smtp.qq.com', 0, null, now(), null),
(2069061886627938306, '服务器端口', 'EMAIL', 'EMAIL_PORT', '465', 0, null, now(), null),
(2069061886627938307, '邮箱账号', 'EMAIL', 'EMAIL_USERNAME', 'fba@qq.com', 0, null, now(), null),
(2069061886627938308, '邮箱密码', 'EMAIL', 'EMAIL_PASSWORD', '', 0, null, now(), null),
(2069061886627938309, 'SSL 加密', 'EMAIL', 'EMAIL_SSL', '1', 0, null, now(), null);
(2069061886627938304, '状态', 'EMAIL', 'EMAIL_STATUS', '1', false, null, now(), null),
(2069061886627938305, '服务器地址', 'EMAIL', 'EMAIL_HOST', 'smtp.qq.com', false, null, now(), null),
(2069061886627938306, '服务器端口', 'EMAIL', 'EMAIL_PORT', '465', false, null, now(), null),
(2069061886627938307, '邮箱账号', 'EMAIL', 'EMAIL_USERNAME', 'fba@qq.com', false, null, now(), null),
(2069061886627938308, '邮箱密码', 'EMAIL', 'EMAIL_PASSWORD', '', false, null, now(), null),
(2069061886627938309, 'SSL 加密', 'EMAIL', 'EMAIL_SSL', 'true', false, null, now(), null),
(2069061886627938310, '状态', 'USER_SECURITY', 'USER_SECURITY_CONFIG_STATUS', '1', false, null, now(), null),
(2069061886627938311, '密码错误锁定阈值', 'USER_SECURITY', 'USER_LOCK_THRESHOLD', '5', false, '0 表示禁用锁定', now(), null),
(2069061886627938312, '密码错误锁定时长(秒)', 'USER_SECURITY', 'USER_LOCK_SECONDS', '300', false, null, now(), null),
(2069061886627938313, '密码有效期(天)', 'USER_SECURITY', 'USER_PASSWORD_EXPIRY_DAYS', '365', false, '0 表示永不过期', now(), null),
(2069061886627938314, '密码到期提醒(天)', 'USER_SECURITY', 'USER_PASSWORD_REMINDER_DAYS', '7', false, '0 表示不提醒', now(), null),
(2069061886627938315, '密码历史检查次数', 'USER_SECURITY', 'USER_PASSWORD_HISTORY_CHECK_COUNT', '3', false, null, now(), null),
(2069061886627938316, '密码最小长度', 'USER_SECURITY', 'USER_PASSWORD_MIN_LENGTH', '6', false, null, now(), null),
(2069061886627938317, '密码最大长度', 'USER_SECURITY', 'USER_PASSWORD_MAX_LENGTH', '32', false, null, now(), null),
(2069061886627938318, '密码必须包含特殊字符', 'USER_SECURITY', 'USER_PASSWORD_REQUIRE_SPECIAL_CHAR', 'false', false, null, now(), null),
(2069061886627938319, '状态', 'LOGIN', 'LOGIN_CONFIG_STATUS', '1', false, null, now(), null),
(2069061886627938320, '验证码开关', 'LOGIN', 'LOGIN_CAPTCHA_ENABLED', 'true', false, null, now(), null);
+17 -7
View File
@@ -1,11 +1,21 @@
insert into sys_config (id, name, type, "key", value, is_frontend, remark, created_time, updated_time)
values
(1, '状态', 'EMAIL', 'EMAIL_STATUS', '1', 0, null, now(), null),
(2, '服务器地址', 'EMAIL', 'EMAIL_HOST', 'smtp.qq.com', 0, null, now(), null),
(3, '服务器端口', 'EMAIL', 'EMAIL_PORT', '465', 0, null, now(), null),
(4, '邮箱账号', 'EMAIL', 'EMAIL_USERNAME', 'fba@qq.com', 0, null, now(), null),
(5, '邮箱密码', 'EMAIL', 'EMAIL_PASSWORD', '', 0, null, now(), null),
(6, 'SSL 加密', 'EMAIL', 'EMAIL_SSL', '1', 0, null, now(), null);
(1, '状态', 'EMAIL', 'EMAIL_STATUS', '1', false, null, now(), null),
(2, '服务器地址', 'EMAIL', 'EMAIL_HOST', 'smtp.qq.com', false, null, now(), null),
(3, '服务器端口', 'EMAIL', 'EMAIL_PORT', '465', false, null, now(), null),
(4, '邮箱账号', 'EMAIL', 'EMAIL_USERNAME', 'fba@qq.com', false, null, now(), null),
(5, '邮箱密码', 'EMAIL', 'EMAIL_PASSWORD', '', false, null, now(), null),
(6, 'SSL 加密', 'EMAIL', 'EMAIL_SSL', 'true', false, null, now(), null),
(7, '状态', 'USER_SECURITY', 'USER_SECURITY_CONFIG_STATUS', '1', false, null, now(), null),
(8, '密码错误锁定阈值', 'USER_SECURITY', 'USER_LOCK_THRESHOLD', '5', false, '0 表示禁用锁定', now(), null),
(9, '密码错误锁定时长(秒)', 'USER_SECURITY', 'USER_LOCK_SECONDS', '300', false, null, now(), null),
(10, '密码有效期(天)', 'USER_SECURITY', 'USER_PASSWORD_EXPIRY_DAYS', '365', false, '0 表示永不过期', now(), null),
(11, '密码到期提醒(天)', 'USER_SECURITY', 'USER_PASSWORD_REMINDER_DAYS', '7', false, '0 表示不提醒', now(), null),
(12, '密码历史检查次数', 'USER_SECURITY', 'USER_PASSWORD_HISTORY_CHECK_COUNT', '3', false, null, now(), null),
(13, '密码最小长度', 'USER_SECURITY', 'USER_PASSWORD_MIN_LENGTH', '6', false, null, now(), null),
(14, '密码最大长度', 'USER_SECURITY', 'USER_PASSWORD_MAX_LENGTH', '32', false, null, now(), null),
(15, '密码必须包含特殊字符', 'USER_SECURITY', 'USER_PASSWORD_REQUIRE_SPECIAL_CHAR', 'false', false, null, now(), null),
(16, '状态', 'LOGIN', 'LOGIN_CONFIG_STATUS', '1', false, null, now(), null),
(17, '验证码开关', 'LOGIN', 'LOGIN_CAPTCHA_ENABLED', 'true', false, null, now(), null);
-- reset auto-increment values for each table based on max id
select setval(pg_get_serial_sequence('sys_config', 'id'),coalesce(max(id), 0) + 1, true) from sys_config;
@@ -1,8 +1,19 @@
insert into sys_config (id, name, type, "key", value, is_frontend, remark, created_time, updated_time)
values
(2069061886627938304, '状态', 'EMAIL', 'EMAIL_STATUS', '1', 0, null, now(), null),
(2069061886627938305, '服务器地址', 'EMAIL', 'EMAIL_HOST', 'smtp.qq.com', 0, null, now(), null),
(2069061886627938306, '服务器端口', 'EMAIL', 'EMAIL_PORT', '465', 0, null, now(), null),
(2069061886627938307, '邮箱账号', 'EMAIL', 'EMAIL_USERNAME', 'fba@qq.com', 0, null, now(), null),
(2069061886627938308, '邮箱密码', 'EMAIL', 'EMAIL_PASSWORD', '', 0, null, now(), null),
(2069061886627938309, 'SSL 加密', 'EMAIL', 'EMAIL_SSL', '1', 0, null, now(), null);
(2069061886627938304, '状态', 'EMAIL', 'EMAIL_STATUS', '1', false, null, now(), null),
(2069061886627938305, '服务器地址', 'EMAIL', 'EMAIL_HOST', 'smtp.qq.com', false, null, now(), null),
(2069061886627938306, '服务器端口', 'EMAIL', 'EMAIL_PORT', '465', false, null, now(), null),
(2069061886627938307, '邮箱账号', 'EMAIL', 'EMAIL_USERNAME', 'fba@qq.com', false, null, now(), null),
(2069061886627938308, '邮箱密码', 'EMAIL', 'EMAIL_PASSWORD', '', false, null, now(), null),
(2069061886627938309, 'SSL 加密', 'EMAIL', 'EMAIL_SSL', 'true', false, null, now(), null),
(2069061886627938310, '状态', 'USER_SECURITY', 'USER_SECURITY_CONFIG_STATUS', '1', false, null, now(), null),
(2069061886627938311, '密码错误锁定阈值', 'USER_SECURITY', 'USER_LOCK_THRESHOLD', '5', false, '0 表示禁用锁定', now(), null),
(2069061886627938312, '密码错误锁定时长(秒)', 'USER_SECURITY', 'USER_LOCK_SECONDS', '300', false, null, now(), null),
(2069061886627938313, '密码有效期(天)', 'USER_SECURITY', 'USER_PASSWORD_EXPIRY_DAYS', '365', false, '0 表示永不过期', now(), null),
(2069061886627938314, '密码到期提醒(天)', 'USER_SECURITY', 'USER_PASSWORD_REMINDER_DAYS', '7', false, '0 表示不提醒', now(), null),
(2069061886627938315, '密码历史检查次数', 'USER_SECURITY', 'USER_PASSWORD_HISTORY_CHECK_COUNT', '3', false, null, now(), null),
(2069061886627938316, '密码最小长度', 'USER_SECURITY', 'USER_PASSWORD_MIN_LENGTH', '6', false, null, now(), null),
(2069061886627938317, '密码最大长度', 'USER_SECURITY', 'USER_PASSWORD_MAX_LENGTH', '32', false, null, now(), null),
(2069061886627938318, '密码必须包含特殊字符', 'USER_SECURITY', 'USER_PASSWORD_REQUIRE_SPECIAL_CHAR', 'false', false, null, now(), null),
(2069061886627938319, '状态', 'LOGIN', 'LOGIN_CONFIG_STATUS', '1', false, null, now(), null),
(2069061886627938320, '验证码开关', 'LOGIN', 'LOGIN_CAPTCHA_ENABLED', 'true', false, null, now(), null);
+7 -8
View File
@@ -19,7 +19,7 @@ class CRUDDictData(CRUDPlus[DictData]):
:param pk: 字典数据 ID
:return:
"""
return await self.select_model(db, pk, load_strategies={'type': 'noload'})
return await self.select_model(db, pk)
async def get_by_type_code(self, db: AsyncSession, type_code: str) -> Sequence[DictData]:
"""
@@ -34,7 +34,6 @@ class CRUDDictData(CRUDPlus[DictData]):
sort_columns='sort',
sort_orders='desc',
type_code=type_code,
load_strategies={'type': 'noload'},
)
async def get_all(self, db: AsyncSession) -> Sequence[DictData]:
@@ -44,7 +43,7 @@ class CRUDDictData(CRUDPlus[DictData]):
:param db: 数据库会话
:return:
"""
return await self.select_models(db, load_strategies={'type': 'noload'})
return await self.select_models(db)
async def get_select(
self,
@@ -77,7 +76,7 @@ class CRUDDictData(CRUDPlus[DictData]):
if type_id is not None:
filters['type_id'] = type_id
return await self.select_order('id', 'desc', load_strategies={'type': 'noload'}, **filters)
return await self.select_order('id', 'desc', **filters)
async def get_by_label_and_type_code(self, db: AsyncSession, label: str, type_code: str) -> DictData | None:
"""
@@ -128,15 +127,15 @@ class CRUDDictData(CRUDPlus[DictData]):
"""
return await self.delete_model_by_column(db, allow_multiple=True, id__in=pks)
async def get_with_relation(self, db: AsyncSession, pk: int) -> DictData | None:
async def delete_by_type_id(self, db: AsyncSession, type_ids: list[int]) -> int:
"""
获取字典数据及关联数据
通过类型 ID 删除字典数据
:param db: 数据库会话
:param pk: 字典数据 ID
:param type_ids: 字典类型 ID 列表
:return:
"""
return await self.select_model(db, pk, load_strategies=['type'])
return await self.delete_model_by_column(db, allow_multiple=True, type_id__in=type_ids)
dict_data_dao: CRUDDictData = CRUDDictData(DictData)
+5 -3
View File
@@ -4,6 +4,7 @@ from sqlalchemy import Select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy_crud_plus import CRUDPlus
from backend.plugin.dict.crud.crud_dict_data import dict_data_dao
from backend.plugin.dict.model import DictType
from backend.plugin.dict.schema.dict_type import CreateDictTypeParam, UpdateDictTypeParam
@@ -28,9 +29,9 @@ class CRUDDictType(CRUDPlus[DictType]):
:param db: 数据库会话
:return:
"""
return await self.select_models(db, load_strategies={'datas': 'noload'})
return await self.select_models(db)
async def get_select(self, *, name: str | None, code: str | None) -> Select:
async def get_select(self, name: str | None, code: str | None) -> Select:
"""
获取字典类型列表查询表达式
@@ -45,7 +46,7 @@ class CRUDDictType(CRUDPlus[DictType]):
if code is not None:
filters['code__like'] = f'%{code}%'
return await self.select_order('id', 'desc', load_strategies={'datas': 'noload'}, **filters)
return await self.select_order('id', 'desc', **filters)
async def get_by_code(self, db: AsyncSession, code: str) -> DictType | None:
"""
@@ -86,6 +87,7 @@ class CRUDDictType(CRUDPlus[DictType]):
:param pks: 字典类型 ID 列表
:return:
"""
await dict_data_dao.delete_by_type_id(db, pks)
return await self.delete_model_by_column(db, allow_multiple=True, id__in=pks)
+10 -27
View File
@@ -1,16 +1,8 @@
from __future__ import annotations
import sqlalchemy as sa
from typing import TYPE_CHECKING
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy import ForeignKey, String
from sqlalchemy.dialects.mysql import LONGTEXT
from sqlalchemy.dialects.postgresql import TEXT
from sqlalchemy.orm import Mapped, mapped_column, relationship
from backend.common.model import Base, id_key
if TYPE_CHECKING:
from backend.plugin.dict.model import DictType
from backend.common.model import Base, UniversalText, id_key
class DictData(Base):
@@ -19,22 +11,13 @@ class DictData(Base):
__tablename__ = 'sys_dict_data'
id: Mapped[id_key] = mapped_column(init=False)
type_code: Mapped[str] = mapped_column(String(32), comment='对应的字典类型编码')
label: Mapped[str] = mapped_column(String(32), comment='字典标签')
value: Mapped[str] = mapped_column(String(32), comment='字典值')
color: Mapped[str | None] = mapped_column(String(32), default=None, comment='标签颜色')
type_code: Mapped[str] = mapped_column(sa.String(32), comment='对应的字典类型编码')
label: Mapped[str] = mapped_column(sa.String(32), comment='字典标签')
value: Mapped[str] = mapped_column(sa.String(32), comment='字典值')
color: Mapped[str | None] = mapped_column(sa.String(32), default=None, comment='标签颜色')
sort: Mapped[int] = mapped_column(default=0, comment='排序')
status: Mapped[int] = mapped_column(default=1, comment='状态(0停用 1正常)')
remark: Mapped[str | None] = mapped_column(
LONGTEXT().with_variant(TEXT, 'postgresql'),
default=None,
comment='备注',
)
remark: Mapped[str | None] = mapped_column(UniversalText, default=None, comment='备注')
# 字典类型一对多
type_id: Mapped[int] = mapped_column(
ForeignKey('sys_dict_type.id', ondelete='CASCADE'),
default=0,
comment='字典类型关联ID',
)
type: Mapped[DictType] = relationship(init=False, back_populates='datas')
# 逻辑外键
type_id: Mapped[int] = mapped_column(sa.BigInteger, default=0, comment='字典类型关联ID')
+6 -21
View File
@@ -1,16 +1,8 @@
from __future__ import annotations
import sqlalchemy as sa
from typing import TYPE_CHECKING
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy import String
from sqlalchemy.dialects.mysql import LONGTEXT
from sqlalchemy.dialects.postgresql import TEXT
from sqlalchemy.orm import Mapped, mapped_column, relationship
from backend.common.model import Base, id_key
if TYPE_CHECKING:
from backend.plugin.dict.model import DictData
from backend.common.model import Base, UniversalText, id_key
class DictType(Base):
@@ -19,13 +11,6 @@ class DictType(Base):
__tablename__ = 'sys_dict_type'
id: Mapped[id_key] = mapped_column(init=False)
name: Mapped[str] = mapped_column(String(32), comment='字典类型名称')
code: Mapped[str] = mapped_column(String(32), unique=True, comment='字典类型编码')
remark: Mapped[str | None] = mapped_column(
LONGTEXT().with_variant(TEXT, 'postgresql'),
default=None,
comment='备注',
)
# 字典类型一对多
datas: Mapped[list[DictData]] = relationship(init=False, back_populates='type')
name: Mapped[str] = mapped_column(sa.String(32), comment='字典类型名称')
code: Mapped[str] = mapped_column(sa.String(32), unique=True, comment='字典类型编码')
remark: Mapped[str | None] = mapped_column(UniversalText, default=None, comment='备注')
+1 -1
View File
@@ -1,6 +1,6 @@
[plugin]
summary = '数据字典'
version = '0.0.7'
version = '0.0.8'
description = '通常用于约束前端工程数据展示'
author = 'wu-clan'
@@ -52,6 +52,5 @@ values
(35, 'sys_plugin_type', '压缩包', '0', 'gold', 1, 1, '插件类型-压缩包', 12, now(), null),
(36, 'sys_plugin_type', 'GIT', '1', 'processing', 2, 1, '插件类型-GIT', 12, now(), null);
-- reset auto-increment values for each table based on max id
select setval(pg_get_serial_sequence('sys_dict_type', 'id'),coalesce(max(id), 0) + 1, true) from sys_dict_type;
select setval(pg_get_serial_sequence('sys_dict_data', 'id'),coalesce(max(id), 0) + 1, true) from sys_dict_data;
+9 -49
View File
@@ -4,17 +4,12 @@ from email.mime.text import MIMEText
from aiosmtplib import SMTP
from anyio import open_file
from jinja2 import Template
from sqlalchemy import inspect
from sqlalchemy.ext.asyncio import AsyncConnection, AsyncSession
from sqlalchemy.ext.asyncio import AsyncSession
from backend.common.enums import StatusType
from backend.common.exception import errors
from backend.common.log import log
from backend.core.conf import settings
from backend.core.path_conf import PLUGIN_DIR
from backend.database.db import async_engine
from backend.plugin.config.crud.crud_config import config_dao
from backend.utils.serializers import select_list_serialize
from backend.utils.dynamic_config import load_email_config
from backend.utils.timezone import timezone
@@ -62,52 +57,17 @@ async def send_email(
:param template: 邮件内容模板
:return:
"""
# 本地配置
email_host = settings.EMAIL_HOST
email_port = settings.EMAIL_PORT
email_ssl = settings.EMAIL_SSL
email_username = settings.EMAIL_USERNAME
email_password = settings.EMAIL_PASSWORD
# 动态配置
dynamic_config = None
def get_config_table(conn: AsyncConnection) -> bool:
inspector = inspect(conn)
return inspector.has_table('sys_config', schema=None)
async with async_engine.begin() as coon:
exists = await coon.run_sync(get_config_table)
if exists:
dynamic_config = await config_dao.get_all(db, 'EMAIL')
if dynamic_config:
status_key = 'EMAIL_STATUS'
host_key = 'EMAIL_HOST'
port_key = 'EMAIL_PORT'
ssl_key = 'EMAIL_SSL'
username_key = 'EMAIL_USERNAME'
password_key = 'EMAIL_PASSWORD'
configs = {d['key']: d['value'] for d in select_list_serialize(dynamic_config)}
if configs.get(status_key):
if len(dynamic_config) < 6:
raise errors.NotFoundError(msg='缺少邮件动态配置,请检查系统参数配置-邮件配置')
email_host = configs.get(host_key)
email_port = int(configs.get(port_key, 0))
email_ssl = configs.get(ssl_key, '') == str(StatusType.enable.value)
email_username = configs.get(username_key)
email_password = configs.get(password_key)
await load_email_config(db)
try:
message = await render_message(subject, email_username, content, template)
message = await render_message(subject, settings.EMAIL_USERNAME, content, template)
smtp_client = SMTP(
hostname=email_host,
port=email_port,
use_tls=email_ssl,
hostname=settings.EMAIL_HOST,
port=settings.EMAIL_PORT,
use_tls=settings.EMAIL_SSL,
)
async with smtp_client:
await smtp_client.login(email_username, email_password)
await smtp_client.sendmail(email_username, recipients, message)
await smtp_client.login(settings.EMAIL_USERNAME, settings.EMAIL_PASSWORD)
await smtp_client.sendmail(settings.EMAIL_USERNAME, recipients, message)
except Exception as e:
log.error(f'电子邮件发送失败:{e}')
+5 -5
View File
@@ -1,8 +1,8 @@
from sqlalchemy import TEXT, String
from sqlalchemy.dialects.mysql import LONGTEXT
import sqlalchemy as sa
from sqlalchemy.orm import Mapped, mapped_column
from backend.common.model import Base, id_key
from backend.common.model import Base, UniversalText, id_key
class Notice(Base):
@@ -11,7 +11,7 @@ class Notice(Base):
__tablename__ = 'sys_notice'
id: Mapped[id_key] = mapped_column(init=False)
title: Mapped[str] = mapped_column(String(50), comment='标题')
title: Mapped[str] = mapped_column(sa.String(64), comment='标题')
type: Mapped[int] = mapped_column(comment='类型(0:通知、1:公告)')
status: Mapped[int] = mapped_column(comment='状态(0:隐藏、1:显示)')
content: Mapped[str] = mapped_column(LONGTEXT().with_variant(TEXT, 'postgresql'), comment='内容')
content: Mapped[str] = mapped_column(UniversalText, comment='内容')
+2
View File
@@ -4,9 +4,11 @@ from backend.core.conf import settings
from backend.plugin.oauth2.api.v1.github import router as github_router
from backend.plugin.oauth2.api.v1.google import router as google_router
from backend.plugin.oauth2.api.v1.linux_do import router as linux_do_router
from backend.plugin.oauth2.api.v1.user_social import router as user_social_router
v1 = APIRouter(prefix=f'{settings.FASTAPI_API_V1_PATH}/oauth2')
v1.include_router(user_social_router, tags=['OAuth2'])
v1.include_router(github_router, prefix='/github', tags=['Github OAuth2'])
v1.include_router(google_router, prefix='/google', tags=['Google OAuth2'])
v1.include_router(linux_do_router, prefix='/linux-do', tags=['LinuxDo OAuth2'])

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