def community_publisher(db, community): """Curator user.""" user = create_test_user('*****@*****.**') member = OARepoCommunity.get_role(community[1], 'member') publisher = OARepoCommunity.get_role(community[1], 'publisher') current_datastore.add_role_to_user(user, member) current_datastore.add_role_to_user(user, publisher) yield publisher
def run(): for res in tqdm( current_flask_taxonomies.list_taxonomy( 'institutions', return_descendants_count=True)): tax = res.TaxonomyTerm if tax.level > 0: continue with db.session.begin_nested(): primary_community = tax.slug.strip('/').rsplit('/', maxsplit=1)[-1] title = tax.extra_data.get('title', {}).get('cs') provider_type = tax.extra_data.get('type', ['neznámý'])[0] # TODO: fix this if len(primary_community) > 60 or not title: continue comm_data = { # "curation_policy": policy, "id": primary_community, "description": f'{provider_type} - {title}', # TODO: "logo": "data/community-logos/ecfunded.jpg" } try: comm = OARepoCommunity.create(comm_data, id_=primary_community, title=title, ctype='other') except IntegrityError: traceback.print_exc() except OARepoCommunityCreateError as e: traceback.print_exc() db.session.commit()
def list_actions(community=None): """List all available community actions.""" click.secho('Available actions:', fg='green') for action in current_oarepo_communities.allowed_actions: _action = action[len('community-'):] click.secho(f'- {_action}') community = OARepoCommunity.get_community(community) if community: click.secho('\nAvailable community roles:', fg='green') for role in {r.name.split(':')[-1] for r in community.roles}.union({'any', 'author'}): click.secho(f'- {role}') click.secho('\nAllowed community role actions:', fg='green') ars, sars = community.actions for ar in ars: for action, roles in ar.items(): click.secho(f'- {action[len("community-"):]}: ', nl=False, fg='yellow') click.secho(', '.join([r.need.value.split(':')[-1] for r in roles])) click.secho('\nAllowed system role actions:', fg='green') for ar in sars: for action, roles in ar.items(): click.secho(f'- {action[len("community-"):]}: ', nl=False, fg='yellow') click.secho(', '.join([r.need.value.split('-')[-1] for r in roles]))
def _validate_community(community): _community = None try: _community = OARepoCommunity.get_community(community) except sqlalchemy.orm.exc.NoResultFound: click.secho(f'Community {community} does not exist', fg='red') exit(3) return _community
def make_sample_community(db, comid): community = OARepoCommunity.create( {'title': f'{comid} Title', 'description': f'Community {comid} description'}, uuid.uuid4(), uuid.uuid4(), uuid.uuid4, id_=comid) db.session.commit() return community
def create(community_id, description, policy, title, ctype, logo_path): """Create a new community and associated community roles.""" topts = [t[0] for t in OAREPO_COMMUNITIES_TYPES] if ctype not in topts: click.secho(f'Invalid Community type {ctype}. Choices: {topts}', fg='red') exit(3) comm_data = { "curation_policy": policy, "id": community_id, "description": description, # TODO: "logo": "data/community-logos/ecfunded.jpg" } comm = None try: comm = OARepoCommunity.create( comm_data, id_=community_id, title=title, ctype=ctype ) except IntegrityError: click.secho(f'Community {community_id} already exists', fg='red') exit(4) except OARepoCommunityCreateError as e: click.secho(e, fg='red') exit(5) for role_name, actions in current_oarepo_communities.default_action_matrix.items(): role = OARepoCommunity.get_role(comm, role_name) if not role and role_name in ['author', 'any']: if role_name == 'author': role = community_record_owner else: role = any_user _allow_actions(community=comm, actions=[a[len('community-'):] for a in actions], role=role, system=True if isinstance(role, Need) else False) db.session.commit() click.secho(f'Created community: {comm} with roles {[r.name for r in comm.roles]}', fg='green')
def test_community_create(db): comm = OARepoCommunity.create( {'description': 'Community description'}, id_='comtest', title='Title', ) _check_community(comm) ar = ActionRoles.query.filter_by(argument=comm.id).all() assert len(ar) == 0
def community(db): """Community fixture.""" comid = 'comtest' community = OARepoCommunity.create( {'description': 'Community description'}, title='Title', id_=comid) db.session.commit() yield comid, community
def filter_facet_options(sender, index_name, index, view_kwargs, **kwargs): community_id = view_kwargs.get('community_id', None) if community_id: community = OARepoCommunity.get_community(community_id) excluded_facets = community.excluded_facets.get(index_name, None) if not excluded_facets: return index['aggs'] = {k: v for k, v in index['aggs'].items() if k in excluded_facets} index['filters'] = {k: v for k, v in index['filters'].items() if k in excluded_facets}
def test_create_object_factory(community, users, community_member, sample_records): logout_user() community[1].allow_action(OARepoCommunity.get_role(community[1], 'member'), COMMUNITY_CREATE) # AnonymousUser cannot assert not create_object_permission_impl(record=None, community_id=community[0]).can() # Member can create login_user(community_member) assert create_object_permission_impl(record=None, community_id=community[0]).can()
def community(app, db): comm_data = { # "curation_policy": policy, "id": 'nr', "description": f'Test NR community', # TODO: "logo": "data/community-logos/ecfunded.jpg" } return OARepoCommunity.create(comm_data, id_='nr', title='Test NR community', ctype='other')
def test_signals(base_app, db, signals): com = OARepoCommunity.create({}, id_='signals-community', title='Signals comm') assert 'before_community_insert' in signals assert 'after_community_insert' in signals assert len(signals.keys()) == 2 assert 'community' in signals['after_community_insert'].keys() assert signals['after_community_insert']['community'] == com assert 'community' in signals['before_community_insert'].keys() assert signals['before_community_insert']['community'] == com
def allow_actions(community, role, actions): """Allow actions to the given role.""" actions = _validate_actions(actions) community = OARepoCommunity.get_community(community) if role == 'any': # Allow actions for anonymous users _allow_actions(community, actions, any_user, system=True) elif role == 'author': # Allow actions for record owners _allow_actions(community, actions, community_record_owner, system=True) else: role = _validate_role(community, role) _allow_actions(community, actions, role)
def exclude(community, index_name, facets): """Exclude some facets on a given index for a given community.""" community = OARepoCommunity.get_community(community) _validate_facets(index_name=index_name, facets=facets) with db.session.begin_nested(): community.json.setdefault('excluded_facets', {}) community.json['excluded_facets'] = {index_name: facets} flag_modified(community, 'json') db.session.add(community) db.session.commit() click.secho(f'Excluded: {",".join(facets)} on index {index_name} for {community.title}', fg='green')
def test_permissions(permissions, community, sample_records): """Test community permissions.""" perms = {a: ParameterizedActionNeed(a, community[1].id) for a in current_oarepo_communities.allowed_actions} member = OARepoCommunity.get_role(community[1], 'member') curator = OARepoCommunity.get_role(community[1], 'curator') publisher = OARepoCommunity.get_role(community[1], 'publisher') # Test author community member can only request approval only in a concrete community. author_identity = get_identity(permissions['author']) assert permissions['author'].roles == [member] assert Permission(perms[COMMUNITY_REQUEST_APPROVAL]).allows(author_identity) assert not any( [Permission(perms[p]).allows(author_identity) for p in perms.keys() if p != COMMUNITY_REQUEST_APPROVAL]) assert not Permission(ParameterizedActionNeed(COMMUNITY_REQUEST_APPROVAL, 'B')).allows(author_identity) assert not any( [Permission(ParameterizedActionNeed(COMMUNITY_REQUEST_APPROVAL, 'B')).allows(author_identity) for p in perms.keys() if p != COMMUNITY_REQUEST_APPROVAL]) # Test community curator action permissions curator_identity = get_identity(permissions['curator']) assert set(permissions['curator'].roles) == {member, curator} assert Permission(perms[COMMUNITY_APPROVE]).allows(curator_identity) assert Permission(perms[COMMUNITY_REQUEST_CHANGES]).allows(curator_identity) assert not Permission(ParameterizedActionNeed(COMMUNITY_APPROVE, 'B')).allows(curator_identity) assert not any([Permission(perms[p]).allows(curator_identity) for p in perms.keys() if p not in [COMMUNITY_APPROVE, COMMUNITY_REQUEST_CHANGES, COMMUNITY_REVERT_APPROVE]]) # Test community publisher action permissions publisher_identity = get_identity(permissions['publisher']) assert set(permissions['publisher'].roles) == {member, publisher} assert Permission(perms[COMMUNITY_PUBLISH]).allows(publisher_identity) assert Permission(perms[COMMUNITY_UNPUBLISH]).allows(publisher_identity) assert not Permission(ParameterizedActionNeed(COMMUNITY_PUBLISH, 'B')).allows(publisher_identity) assert not any([Permission(perms[p]).allows(publisher_identity) for p in perms.keys() if p not in [COMMUNITY_PUBLISH, COMMUNITY_UNPUBLISH, COMMUNITY_REVERT_APPROVE]])
def deny_actions(community, role, actions): """Deny actions on the given role.""" actions = _validate_actions(actions) community = OARepoCommunity.get_community(community) if role == 'any': # Allow actions for anonymous users _deny_actions(community, actions, any_user, system=True) elif role == 'author': # Allow actions for record owners _deny_actions(community, actions, community_record_owner, system=True) else: role = _validate_role(community, role) _deny_actions(community, actions, role) db.session.commit()
def list_facets(community=None): """List all available community facets.""" community = OARepoCommunity.get_community(community) if community: click.secho(f'\nAvailable community {community.title} facets on indices:', fg='green') else: click.secho('\nAvailable facets on indices:', fg='green') for index_name, aggs in current_oarepo_communities.facets.items(): click.secho(f'\nIndex: {index_name}', fg='yellow') for agg in aggs: is_excluded = False if community: excluded_aggs = community.excluded_facets.get(index_name, []) if agg in excluded_aggs: is_excluded = True click.secho(f'{"x" if is_excluded else "-"} {agg}', fg=f'{"red" if is_excluded else ""}')
def community_detail(community_id): """Community list view.""" comm = OARepoCommunity.get_community(community_id) if comm: ars, sars = comm.actions actions = defaultdict(list) if community_member_permission_impl(None).can(): alist = ars + sars # Community member can list action permission matrix for act in alist: for action, roles in act.items(): actions[action] += [r.need.value for r in roles] return jsonify({ **comm.to_json(), 'links': community_links_factory(comm), **({ 'actions': actions } if actions else {}) }) json_abort(404, {"message": "community %s was not found" % community_id})
def test_cli_community_create(script_info, db): # Test community creation. result = CliRunner().invoke(cmd, [ 'create', 'cli-test-community', 'Test Community', '--description', 'community desc', '--ctype', 'wgroup' ], obj=script_info) assert 0 == result.exit_code comm = OARepoCommunity.get_community('cli-test-community') assert comm is not None assert comm.title == 'Test Community' assert comm.type == 'wgroup' assert comm.json['description'] == 'community desc' rols = Role.query.all() assert len(rols) == 3 assert set([r.name for r in rols]) == { 'community:cli-test-community:member', 'community:cli-test-community:curator', 'community:cli-test-community:publisher' }
def test_update_object_factory(community, users, community_member, community_curator, sample_records): logout_user() community[1].allow_action(OARepoCommunity.get_role(community[1], 'curator'), COMMUNITY_UPDATE) # AnonymousUser cannot update for state, rec in sample_records[community[0]][1].items(): perm = update_object_permission_impl assert not perm(record=rec.record).can() # Member cannot update login_user(community_member) for state, rec in sample_records[community[0]][1].items(): perm = update_object_permission_impl assert not perm(record=rec.record).can() # Curator can update filling or approving login_user(community_curator) for state, rec in sample_records[community[0]][1].items(): perm = update_object_permission_impl if state in {STATE_PENDING_APPROVAL, STATE_EDITING}: assert perm(record=rec.record).can() else: assert not perm(record=rec.record).can()
def test_get_community(community, community_ext_groups): comm = OARepoCommunity.get_community('comtest') assert comm is not None _check_community(comm)
def community_member(db, community): user = create_test_user('*****@*****.**') role = OARepoCommunity.get_role(community[1], 'member') current_datastore.add_role_to_user(user, role) user = User.query.get(user.id) yield user
def test_get_communities(community): comms = OARepoCommunity.get_communities(['comtest']) assert comms is not None assert len(comms) == 1 _check_community(comms[0])
def _validate_role(community, role): role = OARepoCommunity.get_role(community, role) if not role: click.secho(f'Role {role} does not exist', fg='red') exit(4) return role
def test_integrity(community): # Community id code cannot be reused with pytest.raises(FlushError): OARepoCommunity.create({}, id_=community[0], title=community[1].title)