def permission_store(): form = PermissionCreateForm(request.form) if form.validate(): permission = Permission() permission.create(data=form.data) return Success(message="操作成功!") return Fail(message=form.first_error)
def test_update_permission_ok_response( self, mock_permission_repo_get, mock_role_controller_request_params, mock_permission_repo_find_first, mock_role_repo_update, ): """Test update_permission when permission already updated.""" # Arrange with self.app.app_context(): mock_role_controller_request_params.return_value = (1, "name", "keyword") mock_permission = Permission( id=1, created_at=datetime.now(), updated_at=datetime.now(), role_id=1, name="Mock permission", keyword="mock", ) mock_permission_repo_get.return_value = mock_permission mock_permission_repo_find_first.return_value = None mock_role_repo_update.return_value = self.mock_role role_controler = RoleController(self.request_context) # Act result = role_controler.update_permission(1) # Assert assert result.status_code == 200 assert result.get_json()["msg"] == "OK"
def test_get_all_permissions_ok_response( self, mock_permission_repo_get_unpaginated ): """Test get_all_permissions OK response.""" # Arrange with self.app.app_context(): mock_permission = Permission( id=1, created_at=datetime.now(), updated_at=datetime.now(), role_id=1, name="Mock permission", keyword="mock", ) mock_permission_repo_get_unpaginated.return_value = [ mock_permission, ] role_controler = RoleController(self.request_context) # Act result = role_controler.get_all_permissions() # Assert assert result.status_code == 200 assert result.get_json()["msg"] == "OK"
def test_create_role_permission_ok_response( self, mock_role_repo_get, mock_permission_repo_get_unpaginated, mock_role_controller_request_params, mock_permission_repo_new_permission): '''Test create_role_permission OK response. ''' # Arrange with self.app.app_context(): mock_permission = Permission(id=1, created_at=datetime.now(), updated_at=datetime.now(), role_id=1, name='Mock permission', keyword='mock') mock_role_repo_get.return_value = self.mock_role mock_permission_repo_get_unpaginated.return_value = None mock_role_controller_request_params.return_value = (1, 'name', 'keyword') mock_permission_repo_new_permission.return_value = mock_permission role_controller = RoleController(self.request_context) # Act result = role_controller.create_role_permission() # Assert assert result.status_code == 201 assert result.get_json()['msg'] == 'OK'
def test_update_permission_ok_response(self, mock_permission_repo_get, mock_role_controller_request_params, mock_permission_repo_find_first, mock_role_repo_update): '''Test update_permission when permission already updated. ''' # Arrange with self.app.app_context(): mock_role_controller_request_params.return_value = (1, 'name', 'keyword') mock_permission = Permission(id=1, created_at=datetime.now(), updated_at=datetime.now(), role_id=1, name='Mock permission', keyword='mock') mock_permission_repo_get.return_value = mock_permission mock_permission_repo_find_first.return_value = None mock_role_repo_update.return_value = self.mock_role role_controler = RoleController(self.request_context) # Act result = role_controler.update_permission(1) # Assert assert result.status_code == 200 assert result.get_json()['msg'] == 'OK'
def test_create_role_permission_ok_response( self, mock_role_repo_get, mock_permission_repo_get_unpaginated, mock_role_controller_request_params, mock_permission_repo_new_permission, ): """Test create_role_permission OK response.""" # Arrange with self.app.app_context(): mock_permission = Permission( id=1, created_at=datetime.now(), updated_at=datetime.now(), role_id=1, name="Mock permission", keyword="mock", ) mock_role_repo_get.return_value = self.mock_role mock_permission_repo_get_unpaginated.return_value = None mock_role_controller_request_params.return_value = (1, "name", "keyword") mock_permission_repo_new_permission.return_value = mock_permission role_controller = RoleController(self.request_context) # Act result = role_controller.create_role_permission() # Assert assert result.status_code == 201 assert result.get_json()["msg"] == "OK"
def test_get_single_permission_ok_response(self, mock_permission_repo_filter_by): '''Test get_single_permission OK response. ''' # Arrange with self.app.app_context(): mock_permission = Permission(id=1, created_at=datetime.now(), updated_at=datetime.now(), role_id=1, name='Mock permission', keyword='mock') mock_permission_item = MagicMock() mock_permission_item.items.return_value = mock_permission mock_permission_repo_filter_by.return_value = mock_permission_item role_controler = RoleController(self.request_context) # Act result = role_controler.get_single_permission(1, 1) # Assert assert result.status_code == 200 assert result.get_json()['msg'] == 'OK'
def update(self, **kwargs): for k, v in kwargs.items(): if hasattr(self, k): setattr(self, k, v) elif hasattr(self.profile, k): if k == 'gold': v += getattr(self.profile, k) setattr(self.profile, k, v) if self.profile.gold >= Level['gold']['topic_creation']: self.role |= Permission.get_by_role('topic_creation').bit if self.profile.gold >= Level['gold']['vote']: self.role |= Permission.get_by_role('vote').bit try: db_session.add(self) db_session.commit() except (DataError, IntegrityError, ProgrammingError): db_session.rollback() raise
def permission_update(id): edit_one_field = request.form.get('edit_one_field', None) if not edit_one_field: form = PermissionEditForm(formdata=request.form, id=id) else: form = PermissionEditOneKeyForm(formdata=request.form, id=id) if not form.validate(): return Fail(message=form.first_error) permission = Permission.get_by_id(id=id) permission.update(form.data, edit_one_field) return Success(message="操作成功!")
def menu(role_id=0): """菜单""" menu = [] if role_id > 0: # 获取用户权限列表 rp_list = RolePermission.query.filter( RolePermission.role_id == role_id).all() rp_id_list = [rp.permission_id for rp in rp_list] permission_list = Permission.query.filter(Permission.parent_id == 0).\ filter(Permission.permission_id.in_(rp_id_list)).\ order_by(Permission.sort_order.desc()).all() # 如果是超级管理员,就显示所有菜单 if role_id == 1: permission_list = Permission.query.filter(Permission.parent_id == 0).\ order_by(Permission.sort_order.desc()).all() for permission in permission_list: # # 如果找不到端点就continue掉 # if not permission.endpoint: # continue permission_child_list = Permission.get_child_list( permission.permission_id) child_list = [] for child in permission_child_list: # 如果找不到端点就continue掉 if not child.endpoint: continue # 如果permission_id没有在获取用户权限id列表就continue掉 if role_id != 1 and child.permission_id not in rp_id_list: continue child_dict = {} child_dict['name'] = u'%s' % child.endpoint_name child_dict['endpoint'] = child.endpoint child_list.append(child_dict) base_menu_dict = { 'name': u'%s' % permission.endpoint_name, 'endpoint': u'%s' % permission.endpoint, 'params': {}, 'icon': u'%s' % permission.endpoint_icon, 'child': child_list } menu.append(base_menu_dict) return menu
def update_permissions(form): oper = { 'c': 'can_create', 'r': 'can_read', 'u': 'can_update', 'd': 'can_delete', } for role in Role.query.all(): for service in Service.query.all(): field = role.name + '-' + service.name perm = Permission.query.filter_by(role=role, service=service).first() if not perm: perm = Permission(role=role, service=service) for v, attr in oper.iteritems(): if v in form.getlist(field): setattr(perm, oper[v], True) else: setattr(perm, oper[v], False) save_to_db(perm, 'Permission saved')
def test_get_role_permissions_ok_response( self, mock_permission_repo_get_unpaginated): '''Test get_role_permissions OK response. ''' # Arrange mock_permission = Permission(id=1, created_at=datetime.now(), updated_at=datetime.now(), role_id=1, name='Mock permission', keyword='mock') mock_permission_repo_get_unpaginated.return_value = [ mock_permission, ] role_controller = RoleController(self.request_context) # Act result = role_controller.get_role_permissions(1) # Assert assert result.status_code == 200 assert result.get_json()['msg'] == 'OK'
def test_delete_role_permission_ok_response(self, mock_role_repo_update, mock_permission_repo_get): '''Test delete_role_permission OK response. ''' # Arrange with self.app.app_context(): mock_permission = Permission(id=1, created_at=datetime.now(), updated_at=datetime.now(), role_id=1, name='Mock permission', keyword='mock') mock_permission_repo_get.return_value = mock_permission mock_role_repo_update.return_value = self.mock_role role_controler = RoleController(self.request_context) # Act result = role_controler.delete_role_permission(1) # Assert assert result.status_code == 200 assert result.get_json()['msg'] == 'permission deleted'
def permission_sort_modify(): """权限列表排序""" permission_id = toint(request.args.get('permission_id', '0')) new_sort = toint(request.args.get('new_sort', '0')) new_sort = new_sort if new_sort > 0 else -1 if new_sort < 0: return u'只能输入大于0的数字' if new_sort > 10000000: return u'数字不能过大' if permission_id <= 0: return u'参数出错' p = Permission.get(permission_id) if p: p.update(sort_order=new_sort, commit=True) return u'ok'
def test_create_role_permission_when_permission_already_exists( self, mock_permission_repo_get_unpaginated, mock_role_controller_request_params): '''Test create_role_permission when permission already exists. ''' # Arrange with self.app.app_context(): mock_permission = Permission(id=1, created_at=datetime.now(), updated_at=datetime.now(), role_id=1, name='Mock permission', keyword='mock') mock_role_controller_request_params.return_value = (1, 'name', 'keyword') mock_permission_repo_get_unpaginated.return_value = mock_permission role_controler = RoleController(self.request_context) # Act result = role_controler.create_role_permission() # Assert assert result.status_code == 400 assert result.get_json()['msg'] == 'This permission already exists'
def test_create_role_permission_when_permission_already_exists( self, mock_permission_repo_get_unpaginated, mock_role_controller_request_params ): """Test create_role_permission when permission already exists.""" # Arrange with self.app.app_context(): mock_permission = Permission( id=1, created_at=datetime.now(), updated_at=datetime.now(), role_id=1, name="Mock permission", keyword="mock", ) mock_role_controller_request_params.return_value = (1, "name", "keyword") mock_permission_repo_get_unpaginated.return_value = mock_permission role_controler = RoleController(self.request_context) # Act result = role_controler.create_role_permission() # Assert assert result.status_code == 400 assert result.get_json()["msg"] == "This permission already exists"
def permission_edit(id): permission = Permission.get_by_id(id) menus = Menu.get_all(is_group=True) return render_template('admin/permission/edit.html', permission=permission, menus=menus)
def has_permission(self, role): per = Permission.get_by_role(role) if not per: return None r = self.query.filter((self.role&per.bit)>0) return r.first()
def permission_lists(): total, result = Permission.get_limit_all() return LayuiResponse(data=result, count=total)
def menu_save(): """保存菜单""" g.title = u'保存菜单' g.page_type = '' errmsg = {} form = request.form permission_id = toint(form.get('permission_id', '0')) endpoint = form.get('endpoint', '').strip() endpoint_name = form.get('endpoint_name', '').strip() endpoint_icon = form.get('endpoint_icon', '').strip() menu_type = toint(form.get('menu_type', '0')) sort_order = toint(form.get('sort_order', '0')) new_endpoint_list = form.get('endpoint_list', '').strip() #新端点列表 # 必填项检查 if menu_type == 0: required_param_list = [ 'endpoint', 'endpoint_name', 'endpoint_icon', 'menu_type', 'sort_order' ] else: required_param_list = [ 'endpoint', 'endpoint_name', 'menu_type', 'sort_order', 'endpoint_list' ] for param in required_param_list: val = form.get(param, '') val = val.strip() if not val: errmsg[param] = u'必填项' if errmsg: g.errmsg = errmsg log_debug('errmsg:%s' % g.errmsg) return render_template('sys/menu_add.html.j2', f=form) if permission_id <= 0: permission_info = Permission.create(endpoint_list=endpoint) # 判断新增端点是否已经存在 if menu_type == 0: e_q = Permission.query.filter( Permission.endpoint == endpoint).filter( Permission.parent_id == 0) else: e_q = Permission.query.filter( Permission.endpoint == endpoint).filter( Permission.parent_id > 0) e = e_q.first() if e: errmsg['endpoint'] = u'新增端点:%s已经存在' % endpoint # 判断新增端点名称是否存在 en = e_q.filter(Permission.endpoint_name == endpoint_name).first() if en: errmsg['endpoint_name'] = u'新增端点名称:%s已经存在' % endpoint_name if errmsg: g.errmsg = errmsg log_debug('errmsg:%s' % g.errmsg) return render_template('sys/menu_add.html.j2', f=form) else: permission_info = Permission.get(permission_id) if menu_type == 1: endpoint_list = db.session.query( Permission.endpoint).filter(Permission.parent_id == 0).all() endpoint_key_list = map(lambda e: e.endpoint.split('.')[0], endpoint_list) new_endpoint = endpoint.split('.') new_endpoint_key = new_endpoint[0] if new_endpoint_key not in endpoint_key_list: errmsg['endpoint'] = u'子菜单端点%s与主菜单不符合' % endpoint if errmsg: g.errmsg = errmsg log_debug('errmsg:%s' % g.errmsg) return render_template('sys/menu_add.html.j2', f=form) # 允许访问的端点列表处理 ne_list = new_endpoint_list.split(',') # 分割逗号后允许访问的端点列表 if endpoint not in ne_list: new_endpoint_list = endpoint + ',' + new_endpoint_list permission_info.update(endpoint_list=new_endpoint_list) for key in endpoint_key_list: if key != new_endpoint_key: continue p = Permission.query.filter( Permission.endpoint.like(u'%' + new_endpoint_key)).first() if not p: p = Permission.query.filter( Permission.endpoint.like(u'%' + new_endpoint_key + u'%')).first() if not p: errmsg['endpoint'] = u'找不到对应的主菜单' if errmsg: g.errmsg = errmsg log_debug('errmsg:%s' % g.errmsg) return render_template('sys/menu_add.html.j2', f=form) parent_id = p.permission_id parent_id = parent_id if menu_type == 1 else 0 permission_info.update(parent_id=parent_id, endpoint=endpoint, endpoint_name=endpoint_name, endpoint_icon=endpoint_icon, sort_order=sort_order, commit=True) return redirect(url_for('sys.menu_list'))
def create_permission(self, role_id, name, keyword): permission = Permission(role_id=role_id, name=name, keyword=keyword) permission.save() return permission
def update_permission(self, role): p = Permission.create(role) self.role |= p.bit db_session.add(self) db_session.commit()
def seed_permission(): permissions = ['VIEW_USERS', 'CREATE_USER'] for permission in permissions: permission = Permission(permission=permission) db.save_to_db(permission)
def permission_delete(ids): ids = ids.split('-') permissions = Permission.get_all_in_ids(ids=ids) for permission in permissions: permission.destroy() return Success(message="成功删除")
def setUp(self): self.edit_perm = Permission("Edit")
def new_permission(self, role_id, name, keyword): perm = Permission(role_id=role_id, name=name, keyword=keyword) perm.save() return perm
def user_has_perm(permission_name): current_user = User.get_by_id(session.get('user_id')) perm = Permission.get_by_name(permission_name) return current_user.has_permission(perm)