def _update_user(user_by_name: IUser, user_by_email: IUser, user_info: dict, groups: IResource, registry: Registry): if user_by_name is not None and user_by_email is not None and user_by_name != user_by_email: msg = ( "Trying to update user but name or email already used for anoth" "er user.\nUpdate: {} ({}). Existing users: {} ({}) and {} ({})." ) raise ValueError( msg.format( user_info["name"], user_info["email"], user_by_name.name, user_by_name.email, user_by_email.name, user_by_email.email, ) ) user = user_by_name or user_by_email if user_by_name is None: userbasic_sheet = get_sheet(user, sheets.principal.IUserBasic) userbasic_sheet.set({"name": user_info["name"]}) if user_by_email is None: userextended_sheet = get_sheet(user, sheets.principal.IUserExtended) userextended_sheet.set({"email": user_info["email"]}) groups_names = user_info.get("groups", []) user_groups = _get_groups(groups_names, groups) permissions_sheet = get_sheet(user, sheets.principal.IPermissions) roles_names = user_info.get("roles", []) permissions_sheet.set({"roles": roles_names, "groups": user_groups}) badges_names = user_info.get("badges", []) _update_badges_assignments(user, badges_names, registry)
def _make_mercator_resource(context, location_appstruct={}, finance_appstruct={}): from adhocracy_core.interfaces import IResource from adhocracy_mercator.sheets.mercator import IMercatorSubResources from adhocracy_mercator.sheets.mercator import ILocation from adhocracy_mercator.sheets.mercator import IFinance from adhocracy_core.utils import get_sheet resource = testing.DummyResource( __provides__=[IResource, IMercatorSubResources]) context['res'] = resource sub_resources_sheet = get_sheet(resource, IMercatorSubResources) if location_appstruct: location_resource = testing.DummyResource( __provides__=[IResource, ILocation]) location_sheet = get_sheet(location_resource, ILocation) location_sheet.set(location_appstruct) context['location'] = location_resource sub_resources_sheet.set({'location': location_resource}) if finance_appstruct: finance_resource = testing.DummyResource( __provides__=[IResource, IFinance]) finance_sheet = get_sheet(finance_resource, IFinance) finance_sheet.set(finance_appstruct) context['finance'] = finance_resource sub_resources_sheet.set({'finance': finance_resource}) return resource
def _make_mercator_resource(context, location_appstruct={}, finance_appstruct={}): from adhocracy_core.interfaces import IResource from adhocracy_mercator.sheets.mercator import IMercatorSubResources from adhocracy_mercator.sheets.mercator import ILocation from adhocracy_mercator.sheets.mercator import IFinance from adhocracy_core.utils import get_sheet resource = testing.DummyResource(__provides__=[IResource, IMercatorSubResources]) context['res'] = resource sub_resources_sheet = get_sheet(resource, IMercatorSubResources) if location_appstruct: location_resource = testing.DummyResource(__provides__=[IResource, ILocation]) location_sheet = get_sheet(location_resource, ILocation) location_sheet.set(location_appstruct) context['location'] = location_resource sub_resources_sheet.set({'location': location_resource}) if finance_appstruct: finance_resource = testing.DummyResource(__provides__=[IResource, IFinance]) finance_sheet = get_sheet(finance_resource, IFinance) finance_sheet.set(finance_appstruct) context['finance'] = finance_resource sub_resources_sheet.set({'finance': finance_resource}) return resource
def _update_user(user_by_name: IUser, user_by_email: IUser, user_info: dict, groups: IResource, registry: Registry): if user_by_name is not None\ and user_by_email is not None\ and user_by_name != user_by_email: msg = 'Trying to update user but name or email already used for anoth'\ 'er user.\nUpdate: {} ({}). Existing users: {} ({}) and {} ({}).' raise ValueError( msg.format(user_info['name'], user_info['email'], user_by_name.name, user_by_name.email, user_by_email.name, user_by_email.email)) user = user_by_name or user_by_email if user_by_name is None: userbasic_sheet = get_sheet(user, sheets.principal.IUserBasic) userbasic_sheet.set({'name': user_info['name']}) if user_by_email is None: userextended_sheet = get_sheet(user, sheets.principal.IUserExtended) userextended_sheet.set({'email': user_info['email']}) groups_names = user_info.get('groups', []) user_groups = _get_groups(groups_names, groups) permissions_sheet = get_sheet(user, sheets.principal.IPermissions) roles_names = user_info.get('roles', []) permissions_sheet.set({'roles': roles_names, 'groups': user_groups}) badges_names = user_info.get('badges', []) _update_badges_assignments(user, badges_names, registry)
def _update_user(user_by_name: IUser, user_by_email: IUser, user_info: dict, groups: IResource): if user_by_name is not None\ and user_by_email is not None\ and user_by_name != user_by_email: msg = 'Trying to update user but name or email already used for anoth'\ 'er user.\nUpdate: {} ({}). Existing users: {} ({}) and {} ({}).' raise ValueError(msg.format(user_info['name'], user_info['email'], user_by_name.name, user_by_name.email, user_by_email.name, user_by_email.email)) user = user_by_name or user_by_email if user_by_name is None: userbasic_sheet = get_sheet(user, sheets.principal.IUserBasic) userbasic_sheet.set({'name': user_info['name']}) if user_by_email is None: userextended_sheet = get_sheet(user, sheets.principal.IUserExtended) userextended_sheet.set({'email': user_info['email']}) user_groups = _get_groups(user_info['groups'], groups) permissions_sheet = get_sheet(user, sheets.principal.IPermissions) permissions_sheet.set({'roles': user_info['roles'], 'groups': user_groups})
def test_get_sheet_sheet_not_registered(context, registry_with_content): from adhocracy_core.interfaces import ISheet from adhocracy_core.exceptions import RuntimeConfigurationError from adhocracy_core.utils import get_sheet registry_with_content.content.get_sheet.side_effect =\ RuntimeConfigurationError with raises(RuntimeConfigurationError): get_sheet(context, ISheet)
def _get_all_process_settings(proposal_version): process = find_interface(proposal_version, resources.bplan.IProcess) process_settings = get_sheet(process, sheets.bplan.IProcessSettings).get() process_private_settings = get_sheet( process, sheets.bplan.IProcessPrivateSettings).get() all_process_settings = process_settings.copy() all_process_settings.update(process_private_settings) return all_process_settings
def _migrate_field_values(registry: Registry, resource: IResource, isheet: IInterface, isheet_old: IInterface, fields_mapping=[(str, str)]): sheet = get_sheet(resource, isheet, registry=registry) old_sheet = get_sheet(resource, isheet_old, registry=registry) appstruct = {} for field, old_field in fields_mapping: old_appstruct = old_sheet.get() if old_field in old_appstruct: logger.info('Migrate value for field {0}'.format(field)) appstruct[field] = old_appstruct[old_field] old_sheet.delete_field_values([old_field]) sheet.set(appstruct)
def _make_mercator2_resource(context, location_appstruct={}, financial_planning_appstruct={}): from adhocracy_core.interfaces import IResource from adhocracy_mercator.sheets.mercator2 import ILocation from adhocracy_mercator.sheets.mercator2 import IFinancialPlanning from adhocracy_core.utils import get_sheet resource = testing.DummyResource(__provides__=[IResource, ILocation, IFinancialPlanning]) context["res"] = resource location_sheet = get_sheet(resource, ILocation) location_sheet.set(location_appstruct) financial_planning_sheet = get_sheet(resource, IFinancialPlanning) financial_planning_sheet.set(financial_planning_appstruct) return resource
def test_includeme_register_has_asset_pool_sheet(config): from adhocracy_core.sheets.asset import IHasAssetPool from adhocracy_core.utils import get_sheet config.include('adhocracy_core.content') config.include('adhocracy_core.sheets.asset') context = testing.DummyResource(__provides__=IHasAssetPool) assert get_sheet(context, IHasAssetPool)
def test_includeme_register_asset_metadata_sheet(config, registry): from adhocracy_core.sheets.asset import IAssetMetadata from adhocracy_core.utils import get_sheet config.include('adhocracy_core.content') config.include('adhocracy_core.sheets.asset') context = testing.DummyResource(__provides__=IAssetMetadata) assert get_sheet(context, IAssetMetadata)
def test_create_extendendname_sheet(config): from adhocracy_core.utils import get_sheet from adhocracy_sample.sheets.sample_sheets import IExtendedName context = testing.DummyResource(__provides__=IExtendedName) inst = get_sheet(context, IExtendedName) appstruct = inst.get() assert 'description_x' in appstruct
def validate_path(node, value): if value is None: return _raise_if_no_password_reset(node, value) metadata = get_sheet(value, IMetadata).get() _raise_if_outdated(node, value, metadata['creation_date']) request.validated['user'] = metadata['creator']
def test_includeme_register_userbasic_sheet(config): from adhocracy_core.sheets.principal import IUserBasic from adhocracy_core.utils import get_sheet config.include('adhocracy_core.content') config.include('adhocracy_core.sheets.principal') context = testing.DummyResource(__provides__=IUserBasic) assert get_sheet(context, IUserBasic)
def notify_new_itemversion_created(context, registry, options): """Notify referencing Resources after creating a new ItemVersion. Args: context (IItemversion): the newly created resource registry (pyramid registry): option (dict): `root_versions`: List with root resources. Will be passed along to resources that reference old versions so they can decide whether they should update themselfes. `creator`: User resource that passed to the creation events. Returns: None """ new_version = context root_versions = options.get('root_versions', []) creator = options.get('creator', None) is_batchmode = options.get('is_batchmode', False) old_versions = [] versionable = get_sheet(context, IVersionable, registry=registry) follows = versionable.get()['follows'] for old_version in follows: old_versions.append(old_version) _notify_itemversion_has_new_version(old_version, new_version, registry, creator) _notify_referencing_resources_about_new_version(old_version, new_version, root_versions, registry, creator, is_batchmode)
def test_includeme_register_permissions_sheet(config): from adhocracy_core.sheets.principal import IPermissions from adhocracy_core.utils import get_sheet config.include('adhocracy_core.content') config.include('adhocracy_core.sheets.principal') context = testing.DummyResource(__provides__=IPermissions) assert get_sheet(context, IPermissions)
def test_update_badges(self, context, registry, log): from adhocracy_core import sheets self._tempfd, filename = mkstemp() with open(filename, 'w') as f: f.write(json.dumps([ {'name': 'Alice', 'email': '*****@*****.**', 'initial-password': '******', 'roles': ['contributor'], 'groups': ['gods'], 'badges': ['Moderator', 'Beginner']}, ])) locator = self._get_user_locator(context, registry) self.call_fut(context, registry, filename) with open(filename, 'w') as f: f.write(json.dumps([ {'name': 'Alice', 'email': '*****@*****.**', 'badges': ['Expert']}])) self.call_fut(context, registry, filename) alice = locator.get_user_by_login('Alice') assignments = find_service(alice, 'badge_assignments').values() assert len(assignments) == 1 assignment = assignments[0] assignment_sheet = get_sheet(assignment, sheets.badge.IBadgeAssignment) badge = context['principals']['badges']['expert'] assert assignment_sheet.get() == {'object': alice, 'badge': badge, 'subject': alice}
def test_includeme_register_password_sheet(config): from adhocracy_core.sheets.principal import IPasswordAuthentication from adhocracy_core.utils import get_sheet config.include('adhocracy_core.content') config.include('adhocracy_core.sheets.principal') context = testing.DummyResource(__provides__=IPasswordAuthentication) assert get_sheet(context, IPasswordAuthentication)
def get_most_rated_proposals(root: IResource, min_rate: int) -> [IMercatorProposalVersion]: """Return child proposals of `root` with rating higher then `min_rate`.""" pool = get_sheet(root, IPool) params = {'depth': 3, 'interfaces': IMercatorProposalVersion, 'reverse': True, 'indexes': {'tag': 'LAST'}, 'group_by': 'rates', 'resolve': True, } results = pool.get(params) proposals = results['elements'] aggregates = results['group_by'] # remove proposals with rate < min_rate. # TODO extend query parameters to allow comparators, like # 'rate': '>=3' for rate, aggregated_proposals in aggregates.items(): if int(rate) < min_rate: for p in aggregated_proposals: try: proposals.remove(p) except ValueError: pass return proposals
def test_includeme_register_versionable_sheet(config): from adhocracy_core.utils import get_sheet from adhocracy_core.sheets.versions import IVersionable config.include('adhocracy_core.content') config.include('adhocracy_core.sheets.versions') context = testing.DummyResource(__provides__=IVersionable) assert get_sheet(context, IVersionable)
def test_includeme_register_comment_sheet(config): from adhocracy_core.sheets.comment import IComment from adhocracy_core.utils import get_sheet config.include('adhocracy_core.content') config.include('adhocracy_core.sheets.comment') context = testing.DummyResource(__provides__=IComment) assert get_sheet(context, IComment)
def test_create_and_add_group(self, registry, principals): from . import principal from adhocracy_core.utils import get_sheet from adhocracy_core import sheets appstructs = { sheets.name.IName.__identifier__: { 'name': 'Group1' }, sheets.principal.IGroup.__identifier__: { 'roles': ['reader'] } } group = registry.content.create(principal.IGroup.__identifier__, parent=principals['groups'], appstructs=appstructs) appstructs = { sheets.principal.IPermissions.__identifier__: { 'groups': [group] } } user = registry.content.create(principal.IUser.__identifier__, parent=principals['users'], appstructs=appstructs) user.activate() group_sheet = get_sheet(group, sheets.principal.IGroup) assert principals['groups']['Group1'] is group assert group_sheet.get()['users'] == [user] assert group_sheet.get()['roles'] == ['reader']
def test_create_namedummy_sheet(config): from adhocracy_core.utils import get_sheet from adhocracy_core.sheets.name import IName from adhocracy_sample.sheets.sample_sheets import DummyNameSheet context = testing.DummyResource(__provides__=IName) inst = get_sheet(context, IName) assert isinstance(inst, DummyNameSheet)
def get_most_rated_proposals(root: IResource, min_rate: int) -> [IMercatorProposalVersion]: """Return child proposals of `root` with rating higher then `min_rate`.""" pool = get_sheet(root, IPool) params = { 'depth': 3, 'interfaces': IMercatorProposalVersion, 'reverse': True, 'indexes': { 'tag': 'LAST' }, 'group_by': 'rates', 'resolve': True, } results = pool.get(params) proposals = results['elements'] aggregates = results['group_by'] # remove proposals with rate < min_rate. # TODO extend query parameters to allow comparators, like # 'rate': '>=3' for rate, aggregated_proposals in aggregates.items(): if int(rate) < min_rate: for p in aggregated_proposals: try: proposals.remove(p) except ValueError: pass return proposals
def test_includeme_register_group_sheet(config): from adhocracy_core.sheets.principal import IGroup from adhocracy_core.utils import get_sheet config.include('adhocracy_core.content') config.include('adhocracy_core.sheets.principal') context = testing.DummyResource(__provides__=IGroup) inst = get_sheet(context, IGroup) assert inst.meta.isheet is IGroup
def test_includeme_register_name_sheet(config): from adhocracy_core.sheets.name import IName from adhocracy_core.utils import get_sheet config.include('adhocracy_core.content') config.include('adhocracy_core.sheets.name') context = testing.DummyResource(__provides__=IName) inst = get_sheet(context, IName) assert inst.meta.isheet is IName
def autoupdate_tag_has_new_version(event): """Auto update last but not first tag if a reference has new version.""" name = event.object.__name__ if name and 'FIRST' in name: return sheet = get_sheet(event.object, event.isheet, event.registry) appstruct = _get_updated_appstruct(event, sheet) sheet.set(appstruct)
def test_includeme_register_description_sheet(config): from adhocracy_core.sheets.description import IDescription from adhocracy_core.utils import get_sheet config.include('adhocracy_core.content') config.include('adhocracy_core.sheets.description') context = testing.DummyResource(__provides__=IDescription) inst = get_sheet(context, IDescription) assert inst.meta.isheet is IDescription
def validator(node, value): child_node_value = node.get_value(value, child_node.name) referenced = normalize_to_tuple(child_node_value) for resource in referenced: sheet = get_sheet(resource, isheet, registry=registry) post_pool_type = _get_post_pool_type(sheet.schema) post_pool = _get_post_pool(resource, post_pool_type) _validate_post_pool(node, (context,), post_pool)
def lower_case_users_emails(root): # pragma: no cover """Lower case users email.""" users = find_service(root, 'principals', 'users') for user in users.values(): if not IUserExtended.providedBy(user): return sheet = get_sheet(user, IUserExtended) sheet.set({'email': user.email.lower()})
def index_tag(resource, default) -> [str]: """Return value for the tag index.""" item = find_interface(resource, IItem) if item is None: # ease testing return tags_sheet = get_sheet(item, ITags) tagnames = [f for f, v in tags_sheet.get().items() if v is resource] return tagnames if tagnames else default
def autoupdate_non_versionable_has_new_version(event): """Auto update non versionable resources if a reference has new version.""" if not _is_in_root_version_subtree(event): return sheet = get_sheet(event.object, event.isheet, event.registry) if not sheet.meta.editable: return appstruct = _get_updated_appstruct(event, sheet) sheet.set(appstruct)
def validate_and_complete_asset(context: IAsset, registry: Registry, options: dict = {}): """Complete the initialization of an asset and ensure that it's valid.""" data_sheet = get_sheet(context, IAssetData, registry=registry) data_appstruct = data_sheet.get() metadata_isheet = get_matching_isheet(context, IAssetMetadata) metadata_sheet = get_sheet(context, metadata_isheet, registry=registry) metadata_appstruct = metadata_sheet.get() file = data_appstruct['data'] if not file: return # to facilitate testing _validate_mime_type(file, metadata_appstruct, metadata_sheet) _store_size_and_filename_as_metadata(file, metadata_appstruct, metadata_sheet, registry=registry) _add_downloads_as_children(context, metadata_sheet, registry)
def reset_password(self, password): """ Set `password` for creator user and delete itself.""" user = get_sheet_field(self, IMetadata, 'creator') password_sheet = get_sheet( user, adhocracy_core.sheets.principal.IPasswordAuthentication) password_sheet.set({'password': password}, send_event=False) if not user.active: # pragma: no cover user.activate() del self.__parent__[self.__name__]
def _delete_badges_assignments(user: IUser) -> None: assignments = find_service(user, 'badge_assignments') to_delete = [] for assignment in assignments.values(): appstruct = get_sheet(assignment, sheets.badge.IBadgeAssignment).get() if appstruct['subject'] == user and appstruct['object'] == user: to_delete.append(assignment.__name__) for assignment_name in to_delete: assignments.remove(assignment_name)
def test_includeme_register_title_sheet(config): from adhocracy_core.sheets.title import ITitle from adhocracy_core.utils import get_sheet config.include("adhocracy_core.content") config.include("adhocracy_core.sheets.title") context = testing.DummyResource(__provides__=ITitle) inst = get_sheet(context, ITitle) assert inst.meta.isheet is ITitle
def validate_and_complete_asset(context: IAsset, registry: Registry, options: dict={}): """Complete the initialization of an asset and ensure that it's valid.""" data_sheet = get_sheet(context, IAssetData, registry=registry) data_appstruct = data_sheet.get() metadata_isheet = get_matching_isheet(context, IAssetMetadata) metadata_sheet = get_sheet(context, metadata_isheet, registry=registry) metadata_appstruct = metadata_sheet.get() file = data_appstruct['data'] if not file: return # to facilitate testing _validate_mime_type(file, metadata_appstruct, metadata_sheet) _store_size_and_filename_as_metadata(file, metadata_appstruct, metadata_sheet, registry=registry) _add_downloads_as_children(context, metadata_sheet, registry)
def test_includeme_register_tag_sheet(config): from adhocracy_core.sheets.tags import ITag from adhocracy_core.utils import get_sheet config.include('adhocracy_core.content') config.include('adhocracy_core.events') config.include('adhocracy_core.graph') config.include('adhocracy_core.catalog') config.include('adhocracy_core.sheets.tags') context = testing.DummyResource(__provides__=ITag) assert get_sheet(context, ITag)
def autoupdate_versionable_has_new_version(event): """Auto updated versionable resource if a reference has new version. :raises AutoUpdateNoForkAllowedError: if a fork is created but not allowed """ if not _is_in_root_version_subtree(event): return sheet = get_sheet(event.object, event.isheet, event.registry) if not sheet.meta.editable: return appstruct = _get_updated_appstruct(event, sheet) new_version = _get_last_version_created_in_transaction(event) if new_version is None: if _new_version_needed_and_not_forking(event): _create_new_version(event, appstruct) else: new_version_sheet = get_sheet(new_version, event.isheet, event.registry) new_version_sheet.set(appstruct)
def get_groups(self, userid: str) -> [IGroup]: """Get :term:`group`s for term:`userid` or return None.""" user = self.get_user_by_userid(userid) if user is None: return user_sheet = get_sheet(user, adhocracy_core.sheets.principal.IPermissions, registry=self.request.registry) groups = user_sheet.get()['groups'] return groups