def prep_db(db): data_L1 = Resource(name="L1") data_L2 = Resource(name="L2") create = Operation(name="create") retrieve = Operation(name="retrieve") update = Operation(name="update") delete = Operation(name="delete") pm_c = Permission(operation=create, resource=data_L1) pm_r = Permission(operation=retrieve, resource=data_L1) pm_u = Permission(operation=update, resource=data_L1) pm_d = Permission(operation=delete, resource=data_L1) pm_c_l2 = Permission(operation=create, resource=data_L2) general = Role(name="general", permission=[pm_r, pm_c_l2]) manager = Role(name="manager", permission=[pm_c, pm_r, pm_u]) admin = Role(name="admin", permission=[pm_c_l2, pm_c, pm_d, pm_u, pm_r]) adam = User(name="Adam", password="******", roles=[general]) andy = User(name="Andy", password="******", roles=[manager]) amy = User(name="Amy", password="******", roles=[admin]) db.sess.add_all([ adam, andy, amy, general, manager, data_L1, data_L2, create, retrieve, update, delete, pm_c, pm_r, pm_u, pm_d, pm_c_l2, admin ]) db.sess.commit()
def test_object_complex_filter(): r = Role( name='view', module_name='rbac.roles', class_name='ObjectRole', init_params={ 'app_name': 'cm', 'model': 'Action', 'filter': { 'name': 'start', 'prototype__type': 'cluster', 'prototype__name': 'Kafka', 'prototype__bundle__name': 'Hadoop', }, }, ) r.save() b1 = Bundle(name='Hadoop', version='1.0') b1.save() p1 = Prototype(bundle=b1, type='cluster', name='Kafka', version='1.0') p1.save() a1 = Action(prototype=p1, name='start') a1.save() a2 = Action(prototype=p1, name='stop') a2.save() assert [a1] == list(r.filter())
def post(self, request): res = dict(result=False) if 'id' in request.POST and request.POST['id']: role = get_object_or_404(Role, pk=request.POST.get('id')) else: role = Role() if request.POST.get('title'): role.title = request.POST.get('title') role.save() res['result'] = True return HttpResponse(json.dumps(res), content_type='application/json')
def prepare_hidden_roles(bundle: Bundle): """Prepares hidden roles""" hidden_roles = {} for act in Action.objects.filter(prototype__bundle=bundle): name_prefix = f'{act.prototype.type} action:'.title() name = f'{name_prefix} {act.display_name}' model = get_model_by_type(act.prototype.type) if act.prototype.type == 'component': serv_name = f'service_{act.prototype.parent.name}_' else: serv_name = '' role_name = ( f'{bundle.name}_{bundle.version}_{bundle.edition}_{serv_name}' f'{act.prototype.type}_{act.prototype.display_name}_{act.name}') role = Role( name=role_name, display_name=role_name, description= (f'run action {act.name} of {act.prototype.type} {act.prototype.display_name}' ), bundle=bundle, type=RoleTypes.hidden, module_name='rbac.roles', class_name='ActionRole', init_params={ 'action_id': act.id, 'app_name': 'cm', 'model': model.__name__, 'filter': { 'prototype__name': act.prototype.name, 'prototype__type': act.prototype.type, 'prototype__bundle_id': bundle.id, }, }, parametrized_by_type=[act.prototype.type], ) role.save() if bundle.category: role.category.add(bundle.category) ct = ContentType.objects.get_for_model(model) perm, _ = Permission.objects.get_or_create( content_type=ct, codename=f'run_action_{act.display_name}', name=f'Can run {act.display_name} actions', ) role.permissions.add(perm) if name not in hidden_roles: hidden_roles[name] = { 'parametrized_by_type': act.prototype.type, 'children': [] } hidden_roles[name]['children'].append(role) return hidden_roles
def roleDetailView(request): if request.method == 'GET': ret = dict() if 'id' in request.GET and request.GET['id']: ret = dict(role=get_object_or_404(Role, pk=request.GET.get('id'))) return render(request, 'system/rbac/role_detail.html', ret) else: res = dict(result=False) if 'id' in request.POST and request.POST['id']: role = get_object_or_404(Role, pk=request.POST.get('id')) else: role = Role() if request.POST.get('title'): role.title = request.POST.get('title') role.save() res['result'] = True return HttpResponse(json.dumps(res), content_type='application/json')
def role_update(role: Role, partial, **kwargs) -> Role: """Updating Role object""" child = kwargs.pop('child', []) parametrized_by = check_role_child(child, partial) kwargs['parametrized_by_type'] = parametrized_by kwargs.pop('name', None) for key, value in kwargs.items(): setattr(role, key, value) try: role.save() except IntegrityError as exc: raise AdwpEx('ROLE_UPDATE_ERROR', msg=f'Role update failed with error {exc}') from exc if child: update_m2m_field(role.child, child) for policy in role.policy_set.all(): policy.apply() return role
def apply(self, policy: Policy, role: Role, user: User, group: Group, param_obj=None): """Apply Role to User and/or Group""" for obj in policy.get_objects(param_obj): for perm in role.get_permissions(): if user is not None: uop = UserObjectPermission.objects.assign_perm(perm, user, obj) policy.user_object_perm.add(uop) if group is not None: gop = GroupObjectPermission.objects.assign_perm(perm, group, obj) policy.group_object_perm.add(gop)
def apply(self, policy: Policy, role: Role, user: User, group: Group, param_obj=None): """Apply Role to User and/or Group""" for perm in role.get_permissions(): if group is not None: group.permissions.add(perm) pp = PolicyPermission(policy=policy, group=group, permission=perm) pp.save() policy.model_perm.add(pp) if user is not None: user.user_permissions.add(perm) pp = PolicyPermission(policy=policy, user=user, permission=perm) pp.save() policy.model_perm.add(pp)
def test_object_filter(): r = Role( name='view', module_name='rbac.roles', class_name='ObjectRole', init_params={ 'app_name': 'cm', 'model': 'Bundle', 'filter': { 'name': 'Hadoop' }, }, ) r.save() b1 = Bundle(name='Hadoop', version='1.0') b1.save() b2 = Bundle(name='Zookeper', version='1.0') b2.save() b3 = Bundle(name='Hadoop', version='2.0') b3.save() assert [b1, b3] == list(r.filter())
def test_object_filter_error(): r1 = Role( name='view', display_name='view', module_name='rbac.roles', class_name='ObjectRole', init_params={ 'app_name': 'cm', 'model': 'qwe' }, ) r1.save() with pytest.raises(AdwpEx) as e: r1.filter() assert e.value.error_code == 'ROLE_FILTER_ERROR' r2 = Role( name='add', display_name='add', module_name='rbac.roles', class_name='ObjectRole', init_params={ 'app_name': 'qwe', 'model': 'qwe' }, ) r2.save() with pytest.raises(AdwpEx) as e: r2.filter() assert e.value.error_code == 'ROLE_FILTER_ERROR'
def test_role_class(): r = Role(module_name='qwe') with pytest.raises(AdwpEx) as e: r.get_role_obj() assert e.value.error_code == 'ROLE_MODULE_ERROR' r = Role(module_name='rbac', class_name='qwe') with pytest.raises(AdwpEx) as e: r.get_role_obj() assert e.value.error_code == 'ROLE_CLASS_ERROR' r = Role(module_name='rbac.roles', class_name='ModelRole') obj = r.get_role_obj() assert isinstance(obj, ModelRole)
] for d in perlistdict: p = Permission() p.title = d[1][0] p.url = d[1][1] p.name = d[1][2] if d[0]: p.menu = Menu.objects.get(title = d[0]) p.save() # 角色 初始化 -- 3个角色(CEO、主管、普通用户) # CEO -- 具有所有权限 r = Role() r.title = 'CEO' r.save() r = Role.objects.get(title = 'CEO') r.permissions.add(Permission.objects.get(title = '首页'),\ Permission.objects.get(title = '帮助文档'),\ Permission.objects.get(title = '上传文件'),\ Permission.objects.get(title = '下载文件'),\ Permission.objects.get(title = '采购列表'),\ Permission.objects.get(title = '添加采购'),\ Permission.objects.get(title = '删除采购'),\ Permission.objects.get(title = '修改采购'),\ Permission.objects.get(title = '批量采购导入'),\ Permission.objects.get(title = '下载采购模板'),\
def upgrade_role(role: dict, data: dict) -> Role: """Upgrade single role""" perm_list = get_role_permissions(role, data['roles']) try: new_role = Role.objects.get(name=role['name']) new_role.permissions.clear() except Role.DoesNotExist: new_role = Role(name=role['name']) new_role.save() new_role.module_name = role['module_name'] new_role.class_name = role['class_name'] if 'init_params' in role: new_role.init_params = role['init_params'] if 'description' in role: new_role.description = role['description'] if 'display_name' in role: new_role.display_name = role['display_name'] else: new_role.display_name = role['name'] if 'parametrized_by' in role: new_role.parametrized_by_type = role['parametrized_by'] if 'type' in role: new_role.type = role['type'] for perm in perm_list: new_role.permissions.add(perm) for category_value in role.get('category', []): category = ProductCategory.objects.get(value=category_value) new_role.category.add(category) new_role.any_category = role.get('any_category', False) new_role.save() return new_role