From 0d1f05d307cf7abdb10670361400554d8fc0cde7 Mon Sep 17 00:00:00 2001 From: Wu Clan Date: Tue, 17 Jun 2025 15:30:35 +0800 Subject: [PATCH] Fix some error class import (#672) --- backend/app/task/service/task_service.py | 5 ++--- backend/common/security/jwt.py | 28 ++++++++++++------------ backend/common/security/permission.py | 3 +-- backend/common/security/rbac.py | 11 +++++----- backend/plugin/errors.py | 10 --------- backend/plugin/tools.py | 13 ++++++++--- 6 files changed, 32 insertions(+), 38 deletions(-) delete mode 100644 backend/plugin/errors.py diff --git a/backend/app/task/service/task_service.py b/backend/app/task/service/task_service.py index 5aeebfc4..984cfc94 100644 --- a/backend/app/task/service/task_service.py +++ b/backend/app/task/service/task_service.py @@ -7,7 +7,6 @@ from starlette.concurrency import run_in_threadpool from backend.app.task.celery import celery_app from backend.app.task.schema.task import RunParam, TaskResult from backend.common.exception import errors -from backend.common.exception.errors import NotFoundError class TaskService: @@ -31,7 +30,7 @@ class TaskService: try: result = AsyncResult(id=tid, app=celery_app) except NotRegistered: - raise NotFoundError(msg='任务不存在') + raise errors.NotFoundError(msg='任务不存在') return TaskResult( result=result.result, traceback=result.traceback, @@ -55,7 +54,7 @@ class TaskService: try: result = AsyncResult(id=tid, app=celery_app) except NotRegistered: - raise NotFoundError(msg='任务不存在') + raise errors.NotFoundError(msg='任务不存在') result.revoke(terminate=True) @staticmethod diff --git a/backend/common/security/jwt.py b/backend/common/security/jwt.py index 17869808..20e64e13 100644 --- a/backend/common/security/jwt.py +++ b/backend/common/security/jwt.py @@ -18,7 +18,7 @@ from sqlalchemy.ext.asyncio import AsyncSession 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.errors import AuthorizationError, TokenError +from backend.common.exception import errors from backend.core.conf import settings from backend.database.db import async_db_session from backend.database.redis import redis_client @@ -80,11 +80,11 @@ def jwt_decode(token: str) -> TokenPayload: user_id = payload.get('sub') expire_time = payload.get('exp') if not user_id: - raise TokenError(msg='Token 无效') + raise errors.TokenError(msg='Token 无效') except ExpiredSignatureError: - raise TokenError(msg='Token 已过期') + raise errors.TokenError(msg='Token 已过期') except (JWTError, Exception): - raise TokenError(msg='Token 无效') + raise errors.TokenError(msg='Token 无效') return TokenPayload(id=int(user_id), session_uuid=session_uuid, expire_time=expire_time) @@ -160,7 +160,7 @@ async def create_new_token(user_id: str, refresh_token: str, multi_login: bool, """ redis_refresh_token = await redis_client.get(f'{settings.TOKEN_REFRESH_REDIS_PREFIX}:{user_id}:{refresh_token}') if not redis_refresh_token or redis_refresh_token != refresh_token: - raise TokenError(msg='Refresh Token 已过期,请重新登录') + raise errors.TokenError(msg='Refresh Token 已过期,请重新登录') new_access_token = await create_access_token(user_id, multi_login, **kwargs) return NewToken( new_access_token=new_access_token.access_token, @@ -191,7 +191,7 @@ def get_token(request: Request) -> str: authorization = request.headers.get('Authorization') scheme, token = get_authorization_scheme_param(authorization) if not authorization or scheme.lower() != 'bearer': - raise TokenError(msg='Token 无效') + raise errors.TokenError(msg='Token 无效') return token @@ -207,18 +207,18 @@ async def get_current_user(db: AsyncSession, pk: int) -> User: user = await user_dao.get_with_relation(db, user_id=pk) if not user: - raise TokenError(msg='Token 无效') + raise errors.TokenError(msg='Token 无效') if not user.status: - raise AuthorizationError(msg='用户已被锁定,请联系系统管理员') + raise errors.AuthorizationError(msg='用户已被锁定,请联系系统管理员') if user.dept_id: if not user.dept.status: - raise AuthorizationError(msg='用户所属部门已被锁定,请联系系统管理员') + raise errors.AuthorizationError(msg='用户所属部门已被锁定,请联系系统管理员') if user.dept.del_flag: - raise AuthorizationError(msg='用户所属部门已被删除,请联系系统管理员') + raise errors.AuthorizationError(msg='用户所属部门已被删除,请联系系统管理员') if user.roles: role_status = [role.status for role in user.roles] if all(status == 0 for status in role_status): - raise AuthorizationError(msg='用户所属角色已被锁定,请联系系统管理员') + raise errors.AuthorizationError(msg='用户所属角色已被锁定,请联系系统管理员') return user @@ -231,7 +231,7 @@ def superuser_verify(request: Request) -> bool: """ superuser = request.user.is_superuser if not superuser or not request.user.is_staff: - raise AuthorizationError + raise errors.AuthorizationError return superuser @@ -246,10 +246,10 @@ async def jwt_authentication(token: str) -> GetUserInfoWithRelationDetail: user_id = token_payload.id redis_token = await redis_client.get(f'{settings.TOKEN_REDIS_PREFIX}:{user_id}:{token_payload.session_uuid}') if not redis_token: - raise TokenError(msg='Token 已过期') + raise errors.TokenError(msg='Token 已过期') if token != redis_token: - raise TokenError(msg='Token 已失效') + raise errors.TokenError(msg='Token 已失效') cache_user = await redis_client.get(f'{settings.JWT_USER_REDIS_PREFIX}:{user_id}') if not cache_user: diff --git a/backend/common/security/permission.py b/backend/common/security/permission.py index 62c3efa7..66f4d39b 100644 --- a/backend/common/security/permission.py +++ b/backend/common/security/permission.py @@ -8,7 +8,6 @@ from sqlalchemy.ext.asyncio import AsyncSession from backend.app.admin.crud.crud_data_scope import data_scope_dao from backend.common.enums import RoleDataRuleExpressionType, RoleDataRuleOperatorType from backend.common.exception import errors -from backend.common.exception.errors import ServerError from backend.core.conf import settings from backend.utils.import_parse import dynamic_import_data_model @@ -40,7 +39,7 @@ class RequestPermission: """ if settings.RBAC_ROLE_MENU_MODE: if not isinstance(self.value, str): - raise ServerError + raise errors.ServerError # 附加权限标识到请求状态 request.state.permission = self.value diff --git a/backend/common/security/rbac.py b/backend/common/security/rbac.py index 8024e0de..f2ac3618 100644 --- a/backend/common/security/rbac.py +++ b/backend/common/security/rbac.py @@ -4,7 +4,6 @@ from fastapi import Depends, Request from backend.common.enums import MethodType, StatusType from backend.common.exception import errors -from backend.common.exception.errors import AuthorizationError, TokenError from backend.common.log import log from backend.common.security.jwt import DependsJwtAuth from backend.core.conf import settings @@ -27,7 +26,7 @@ async def rbac_verify(request: Request, _token: str = DependsJwtAuth) -> None: # JWT 授权状态强制校验 if not request.auth.scopes: - raise TokenError + raise errors.TokenError # 超级管理员免校验 if request.user.is_superuser: @@ -36,17 +35,17 @@ async def rbac_verify(request: Request, _token: str = DependsJwtAuth) -> None: # 检测用户角色 user_roles = request.user.roles if not user_roles or all(status == 0 for status in user_roles): - raise AuthorizationError(msg='用户未分配角色,请联系系统管理员') + raise errors.AuthorizationError(msg='用户未分配角色,请联系系统管理员') # 检测用户所属角色菜单 if not any(len(role.menus) > 0 for role in user_roles): - raise AuthorizationError(msg='用户未分配菜单,请联系系统管理员') + raise errors.AuthorizationError(msg='用户未分配菜单,请联系系统管理员') # 检测后台管理操作权限 method = request.method if method != MethodType.GET or method != MethodType.OPTIONS: if not request.user.is_staff: - raise AuthorizationError(msg='用户已被禁止后台管理操作,请联系系统管理员') + raise errors.AuthorizationError(msg='用户已被禁止后台管理操作,请联系系统管理员') # RBAC 鉴权 if settings.RBAC_ROLE_MENU_MODE: @@ -72,7 +71,7 @@ async def rbac_verify(request: Request, _token: str = DependsJwtAuth) -> None: if menu.perms and menu.status == StatusType.enable: allow_perms.extend(menu.perms.split(',')) if path_auth_perm not in allow_perms: - raise AuthorizationError + raise errors.AuthorizationError else: try: casbin_rbac = import_module_cached('backend.plugin.casbin_rbac.rbac') diff --git a/backend/plugin/errors.py b/backend/plugin/errors.py deleted file mode 100644 index 213b243a..00000000 --- a/backend/plugin/errors.py +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- - - -class PluginConfigError(Exception): - """插件信息错误""" - - -class PluginInjectError(Exception): - """插件注入错误""" diff --git a/backend/plugin/tools.py b/backend/plugin/tools.py index 9ce31458..6e20b837 100644 --- a/backend/plugin/tools.py +++ b/backend/plugin/tools.py @@ -16,16 +16,23 @@ from fastapi import APIRouter, Depends, Request from starlette.concurrency import run_in_threadpool from backend.common.enums import StatusType -from backend.common.exception.errors import ForbiddenError +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.redis import RedisCli, redis_client -from backend.plugin.errors import PluginConfigError, PluginInjectError from backend.utils._await import run_await from backend.utils.import_parse import import_module_cached +class PluginConfigError(Exception): + """插件信息错误""" + + +class PluginInjectError(Exception): + """插件注入错误""" + + @lru_cache def get_plugins() -> list[str]: """获取插件列表""" @@ -324,4 +331,4 @@ class PluginStatusChecker: log.error(f'插件 {self.plugin} 状态未初始化或丢失,需重启服务自动修复') raise PluginInjectError(f'插件 {self.plugin} 状态未初始化或丢失,请联系系统管理员') if not int(plugin_status.get(self.plugin)): - raise ForbiddenError(msg=f'插件 {self.plugin} 未启用,请联系系统管理员') + raise errors.ForbiddenError(msg=f'插件 {self.plugin} 未启用,请联系系统管理员')