Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions backend/app/task/service/task_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
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:
Expand All @@ -31,7 +30,7 @@ def get_detail(*, tid: str) -> TaskResult:
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,
Expand All @@ -55,7 +54,7 @@ def revoke(*, tid: str) -> None:
try:
result = AsyncResult(id=tid, app=celery_app)
except NotRegistered:
raise NotFoundError(msg='任务不存在')
raise errors.NotFoundError(msg='任务不存在')
result.revoke(terminate=True)

@staticmethod
Expand Down
28 changes: 14 additions & 14 deletions backend/common/security/jwt.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
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
Expand Down Expand Up @@ -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)


Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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


Expand All @@ -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


Expand All @@ -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


Expand All @@ -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:
Expand Down
3 changes: 1 addition & 2 deletions backend/common/security/permission.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
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

Expand Down Expand Up @@ -40,7 +39,7 @@ async def __call__(self, request: Request) -> None:
"""
if settings.RBAC_ROLE_MENU_MODE:
if not isinstance(self.value, str):
raise ServerError
raise errors.ServerError
# 附加权限标识到请求状态
request.state.permission = self.value

Expand Down
11 changes: 5 additions & 6 deletions backend/common/security/rbac.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

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
Expand All @@ -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:
Expand All @@ -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:
Expand All @@ -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')
Expand Down
10 changes: 0 additions & 10 deletions backend/plugin/errors.py

This file was deleted.

13 changes: 10 additions & 3 deletions backend/plugin/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,23 @@
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]:
"""获取插件列表"""
Expand Down Expand Up @@ -324,4 +331,4 @@ async def __call__(self, request: Request) -> None:
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} 未启用,请联系系统管理员')