Skip to content

Commit 4484469

Browse files
authored
Optimize role menu authorization logic (#221)
1 parent de9b10a commit 4484469

File tree

2 files changed

+20
-14
lines changed

2 files changed

+20
-14
lines changed

backend/app/common/rbac.py

+15-9
Original file line numberDiff line numberDiff line change
@@ -55,16 +55,20 @@ async def rbac_verify(self, request: Request, _: dict = DependsJwtAuth) -> None:
5555
data_scope = any(role.data_scope == 1 for role in user_roles)
5656
if data_scope:
5757
return
58+
method = request.method
5859
if settings.MENU_PERMISSION:
5960
# 菜单权限校验
60-
path_auth = request.url.path.replace(f'{settings.API_V1_STR}', '').replace('/', ':')
61+
# TODO: 改用流行方案,自定义接口权限字段标识
62+
path_auth = path.split(f'{settings.API_V1_STR}/')[-1].replace('/', ':') + f':{method}'
6163
menu_perms = []
6264
forbid_menu_perms = []
6365
for role in user_roles:
64-
for menu in role.menus:
65-
menu_perms.append(menu.perms) if menu.status == StatusType.enable else forbid_menu_perms.append(
66-
menu.perms
67-
)
66+
if role.menus:
67+
for menu in role.menus:
68+
if menu.status == StatusType.enable:
69+
menu_perms.append(menu.perms)
70+
else:
71+
forbid_menu_perms.append(menu.perms)
6872
if path_auth in set(settings.MENU_EXCLUDE):
6973
return
7074
if path_auth in set([perm for perms_str in forbid_menu_perms for perm in perms_str.split(',')]):
@@ -73,10 +77,12 @@ async def rbac_verify(self, request: Request, _: dict = DependsJwtAuth) -> None:
7377
raise AuthorizationError
7478
else:
7579
# casbin 权限校验
76-
method = request.method
77-
forbid_menu_path = [
78-
menu.path for role in user_roles for menu in role.menus if menu.status == StatusType.disable
79-
]
80+
forbid_menu_path = []
81+
for role in user_roles:
82+
if role.menus:
83+
for menu in role.menus:
84+
if menu.status == StatusType.disable:
85+
forbid_menu_path.append(menu.path)
8086
if path.split('/')[-1] in forbid_menu_path:
8187
raise AuthorizationError(msg='菜单已禁用,授权失败')
8288
if (method, path) in settings.CASBIN_EXCLUDE:

backend/app/core/conf.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -129,11 +129,11 @@ def validator_api_url(cls, values):
129129
# Menu
130130
MENU_PERMISSION: bool = False # 危险行为,开启此功能, Casbin 鉴权将失效,并将使用角色菜单鉴权 (默认关闭)
131131
MENU_EXCLUDE: list[str] = [
132-
'auth:swagger_login',
133-
'auth:login',
134-
'auth:logout',
135-
'auth:register',
136-
'auth:captcha',
132+
'auth:swagger_login:post',
133+
'auth:login:post',
134+
'auth:logout:post',
135+
'auth:register:post',
136+
'auth:captcha:get',
137137
]
138138

139139
# Opera log

0 commit comments

Comments
 (0)