Optimize role menu authorization logic (#221)

This commit is contained in:
Wu Clan
2023-09-26 18:13:08 +08:00
committed by GitHub
parent de9b10a867
commit 44844698ae
2 changed files with 20 additions and 14 deletions
+15 -9
View File
@@ -55,16 +55,20 @@ class RBAC:
data_scope = any(role.data_scope == 1 for role in user_roles)
if data_scope:
return
method = request.method
if settings.MENU_PERMISSION:
# 菜单权限校验
path_auth = request.url.path.replace(f'{settings.API_V1_STR}', '').replace('/', ':')
# TODO: 改用流行方案,自定义接口权限字段标识
path_auth = path.split(f'{settings.API_V1_STR}/')[-1].replace('/', ':') + f':{method}'
menu_perms = []
forbid_menu_perms = []
for role in user_roles:
for menu in role.menus:
menu_perms.append(menu.perms) if menu.status == StatusType.enable else forbid_menu_perms.append(
menu.perms
)
if role.menus:
for menu in role.menus:
if menu.status == StatusType.enable:
menu_perms.append(menu.perms)
else:
forbid_menu_perms.append(menu.perms)
if path_auth in set(settings.MENU_EXCLUDE):
return
if path_auth in set([perm for perms_str in forbid_menu_perms for perm in perms_str.split(',')]):
@@ -73,10 +77,12 @@ class RBAC:
raise AuthorizationError
else:
# casbin 权限校验
method = request.method
forbid_menu_path = [
menu.path for role in user_roles for menu in role.menus if menu.status == StatusType.disable
]
forbid_menu_path = []
for role in user_roles:
if role.menus:
for menu in role.menus:
if menu.status == StatusType.disable:
forbid_menu_path.append(menu.path)
if path.split('/')[-1] in forbid_menu_path:
raise AuthorizationError(msg='菜单已禁用,授权失败')
if (method, path) in settings.CASBIN_EXCLUDE:
+5 -5
View File
@@ -129,11 +129,11 @@ class Settings(BaseSettings):
# Menu
MENU_PERMISSION: bool = False # 危险行为,开启此功能, Casbin 鉴权将失效,并将使用角色菜单鉴权 (默认关闭)
MENU_EXCLUDE: list[str] = [
'auth:swagger_login',
'auth:login',
'auth:logout',
'auth:register',
'auth:captcha',
'auth:swagger_login:post',
'auth:login:post',
'auth:logout:post',
'auth:register:post',
'auth:captcha:get',
]
# Opera log