Skip to content

Commit

Permalink
fix: 删除用户组后清理角色信息,助手工具删除时判断权限校验
Browse files Browse the repository at this point in the history
  • Loading branch information
zgqgit committed Jun 28, 2024
1 parent 2c68513 commit ef06c0d
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 10 deletions.
1 change: 1 addition & 0 deletions src/backend/bisheng/api/v1/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -395,6 +395,7 @@ async def create_role(*,
create_role_hook(request, login_user, db_role)
return resp_200(db_role)
except Exception:
logger.exception('add role error')
raise HTTPException(status_code=500, detail='添加失败,检查是否重复添加')


Expand Down
21 changes: 11 additions & 10 deletions src/backend/bisheng/database/models/role.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,17 @@

from bisheng.database.base import session_getter
from bisheng.database.models.base import SQLModelSerializable
from sqlalchemy import Column, DateTime, text, func, delete, and_
from sqlalchemy import Column, DateTime, text, func, delete, and_, UniqueConstraint
from sqlmodel import Field, select

from bisheng.database.models.role_access import RoleAccess

# 默认普通用户角色的ID
DefaultRole = 2
# 超级管理员角色ID
AdminRole = 1


class RoleBase(SQLModelSerializable):
role_name: str = Field(index=False, description='前端展示名称', unique=True)
role_name: str = Field(index=False, description='前端展示名称')
group_id: Optional[int] = Field(index=True)
remark: Optional[str] = Field(index=False)
create_time: Optional[datetime] = Field(sa_column=Column(
Expand All @@ -28,6 +26,7 @@ class RoleBase(SQLModelSerializable):


class Role(RoleBase, table=True):
__table_args__ = (UniqueConstraint('group_id', 'role_name', name='group_role_name_uniq'),)
id: Optional[int] = Field(default=None, primary_key=True)


Expand Down Expand Up @@ -100,13 +99,15 @@ def get_role_by_id(cls, role_id: int) -> Role:
@classmethod
def delete_role_by_group_id(cls, group_id: int):
"""
删除分组下所有的角色
删除分组下所有的角色,清理用户对应的角色
"""
from bisheng.database.models.user_role import UserRole
with session_getter() as session:
all_access = select(RoleAccess, Role).join(
Role, and_(RoleAccess.role_id == Role.id,
Role.group_id == group_id)).group_by(RoleAccess.id)
all_access = session.exec(all_access)
session.exec(delete(RoleAccess).where(RoleAccess.id.in_([one.id for one in all_access])))
# 清理对应的用户
all_user = select(UserRole, Role).join(
Role, and_(UserRole.role_id == Role.id,
Role.group_id == group_id)).group_by(UserRole.id)
all_user = session.exec(all_user).all()
session.exec(delete(UserRole).where(UserRole.id.in_([one.id for one in all_user])))
session.exec(delete(Role).where(Role.group_id == group_id))
session.commit()

0 comments on commit ef06c0d

Please sign in to comment.