async def check_content_moved(event): request = event.request try: get_current_container() except ContainerNotFound: return storage = utils.get_storage() if storage is None: return tail, _, view = '/'.join(event.tail).partition('/@') if view: view = '@' + view path = os.path.join( get_content_path(request.resource), tail) query = Query.from_(aliases_table).select( aliases_table.zoid ).where( (aliases_table.path == sqlq(path)) | (aliases_table.path == sqlq(path) + '/' + sqlq(view)) ) async with storage.pool.acquire() as conn: results = await conn.fetch(str(query)) if len(results) > 0: ob = await get_object_by_oid(results[0]['zoid']) url = get_object_url(ob) if view: url += '/' + view raise HTTPMovedPermanently(url)
async def history(context, request): bhr = await get_behavior(context, ICMSBehavior) container = get_current_container() result = [] context_url = getMultiAdapter((context, request), IAbsoluteURL)() container_url = getMultiAdapter((container, request), IAbsoluteURL)() for ident, hist_data in enumerate(bhr.history): actor = hist_data.get("actor", "") type_ = hist_data.get("type", "") title = hist_data.get("title", "") value = { "@id": f"{context_url}/@history/{ident}", "action": title, "comments": hist_data.get("comments", ""), "time": hist_data.get("time", ""), "transition_title": title, "type": type_, "actor": { "@id": f"{container_url}/@users/{actor}", "fullname": actor, "id": actor, "username": actor } } data = hist_data.get("data", {}) if type_ == 'versioning': value['may_revert']: False value['version']: ident elif type_ == "workflow": value['state_title'] = data.get('review_state') value['review_state'] = data.get('review_state') result.append(value) return result
def serialize(self): result = super(DefaultChoiceSchemaFieldSerializer, self).serialize() if self.field.vocabularyName is not None: container = get_current_container() result["vocabulary"] = { "@id": f"{get_object_url(container, self.request)}/@vocabularies/{self.field.vocabularyName}" } vocabulary_registry = getVocabularyRegistry() try: vocab = vocabulary_registry.get(None, self.field.vocabularyName) result["enum"] = vocab.keys() except AttributeError: pass result["type"] = "string" else: if isinstance(self.field.vocabulary, SimpleVocabulary): result["choices"] = [ (x.token, x.value) for x in self.field.vocabulary._terms ] result["enum"] = self.field.vocabulary.by_token.keys() result["enumNames"] = self.field.vocabulary.by_value.keys() elif ISource.providedBy(self.field.vocabulary): result["choices"] = self.field.vocabulary.values result["enum"] = self.field.vocabulary.keys() result["enumNames"] = [v for k, v in self.field.vocabulary.values] return result
async def get_user(self, token): """Returns the current user associated with the token and None if user could not be found. """ try: container = get_current_container() users = await container.async_get("users") except (AttributeError, KeyError, ContainerNotFound): return user_id = token.get("id", "") if not user_id: # No user id in the token return if not await users.async_contains(user_id): # User id does not correspond to any existing user folder return user = await users.async_get(user_id) if user.disabled: # User is disabled return return user
async def get_user(self, token: typing.Dict) -> typing.Optional[IPrincipal]: """Returns the current user associated with the token and None if user could not be found. """ try: container = get_current_container() users = await container.async_get("users") except (AttributeError, KeyError, ContainerNotFound): return None user_id = token.get("id", "") if not user_id: # No user id in the token return None if not await users.async_contains(user_id): # User id does not correspond to any existing user folder return None user = await users.async_get(user_id) if user.disabled: # User is disabled return None # Load groups into cache for ident in user.groups: try: user._groups_cache[ident] = await navigate_to(container, f"groups/{ident}") except KeyError: continue return user
async def run(token_data, payload): # Payload : { # 'new_password': '******', # } container = get_current_container() user_folders = await container.async_get("users") data = {} valid_data = ["username", "email", "name", "password", "properties"] for key in valid_data: if key in token_data: data[key] = token_data[key] user = await create_content_in_container( user_folders, "User", token_data.get("username", token_data.get("id")), creators=(token_data.get("username", token_data.get("id")),), check_security=False, **data, ) user.user_roles = ["guillotina.Member"] await notify(ObjectAddedEvent(user)) jwt_token, data = authenticate_user(user.id, timeout=app_settings["jwt"]["token_expiration"]) await notify(UserLogin(user, jwt_token)) return {"exp": data["exp"], "token": jwt_token}
async def resolve_search(_, info, *, query): container = get_current_container() utility = get_utility(ICatalogUtility) result = await utility.search(container, query) for obj in result["items"]: type_name = obj.pop("type_name") obj["__typename"] = type_name return result["items"]
async def user_created(user, event): user.password = hash_password(user.password) # user has access to his own object by default container = get_current_container() roleperm = IPrincipalRoleManager(container) roleperm.assign_role_to_principal('guillotina.Owner', user.id) await notify(NewUserAdded(user))
async def update_groups(group, event): container = get_current_container() users = group.users for user in users: try: context = await navigate_to(container, f"users/{user}") except KeyError: raise PreconditionFailed(container, "inexistent user") if group.id not in context.user_groups: context.user_groups.append(user) context.register()
async def get_user(self, token): try: container = get_current_container() users = await container.async_get('users') except (AttributeError, KeyError, ContainerNotFound): return user_ids = await users.async_keys() if token.get('id', '') in user_ids: user = await users.async_get(token.get('id', '')) if not user.disabled: return user
async def on_update_groups(group: Group, event: ObjectModifiedEvent) -> None: # Keep group.users and user.user_groups in sync container = get_current_container() users = group.users or [] for user_id in users: try: # Get the user user = await navigate_to(container, f"users/{user_id}") except KeyError: raise HTTPPreconditionFailed(content={"reason": f"inexistent user: {user_id}"}) # Add group to user groups field if group.id not in user.user_groups: user.user_groups.append(group.id) user.register()
async def get_new_notification(context, request): results = [] container = get_current_container() ''' from the request we need 3 param: ::param: user_Id ::param: application_name ::param: notification_type ''' multi_params = request.query_string user_Id = 0 application_name = '' notification_type = 'SIMPLE' for parametro in multi_params.split('&'): ricercato = parametro.split('=') if ricercato[0] == 'notification_type': if ricercato[1] == 'EMAIL': notification_type = 'EMAIL' else: notification_type = 'SIMPLE' elif ricercato[0] == 'application_name': application_name = ricercato[1] elif ricercato[0] == 'userId' or ricercato[0] == 'email': user_Id = ricercato[1] #only the notific. with status = NOT_NOTIFIED async for item in container.async_values(): if 'Notification' == getattr(item, "type_name"): if getattr(item, "notification_type") == notification_type and getattr( item, "application_name") == application_name and getattr( item, "recipientId") == user_Id and getattr( item, "status") == "NOT_NOTIFY": summary = await getMultiAdapter( (item, request), IResourceSerializeToJsonSummary)() results.append(summary) #sort the results list results = sorted(results, key=lambda conv: conv['creation_date']) return results
async def get_user(self, token: typing.Dict) -> typing.Optional[IPrincipal]: try: container = get_current_container() users = await container.async_get("users") except (AttributeError, KeyError, ContainerNotFound): return None catalog = query_utility(ICatalogUtility) if not isinstance(catalog, PGSearchUtility): raise NoCatalogException() txn = get_transaction() if txn is None: raise TransactionNotFound() conn = await txn.get_connection() # The catalog doesn't work because we are still # not authenticated sql = f""" SELECT id FROM {txn.storage.objects_table_name} WHERE json->>'type_name' = 'User' AND parent_id != 'DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD' AND json->>'container_id' = $1::varchar AND lower(json->>'user_email') = lower($2::varchar) """ async with txn.lock: row = await conn.fetchrow(sql, container.id, token.get("id")) if not row: return None user = await users.async_get(row["id"]) if user.disabled: # User is disabled return None # Load groups into cache for ident in user.groups: try: user._groups_cache[ident] = await navigate_to( container, f"groups/{ident}") except KeyError: continue return user
async def reindex(self, obj): index_manager = find_index_manager(obj) if index_manager is None: container = get_current_container() index_manager = get_adapter(container, IIndexManager) self.work_index_name = await index_manager.get_index_name() await notify(IndexProgress(self.context, 0, self.processed)) await self.process_object(obj) await self.flush() if len(self.sub_indexes) > 0: # could cause sub indexes to need to be run through as well. for ob in self.sub_indexes: im = get_adapter(ob, IIndexManager) reindexer = Reindexer( self.utility, ob, response=self.response, force=self.force, log_details=self.log_details, memory_tracking=self.memory_tracking, bulk_size=self.bulk_size, full=self.full, reindex_security=self.reindex_security, mapping_only=self.mapping_only, index_manager=im, request=self.request, ) reindexer.processed = self.processed reindexer.work_index_name = await im.get_index_name() await reindexer.process_folder(ob) await reindexer.flush() self.processed = reindexer.processed await notify( IndexProgress( self.context, self.processed, self.processed, completed=True, request=self.request, ) )
async def _update_users(group_id, users_added, users_removed): container = get_current_container() for user_id in users_added: try: user: User = await navigate_to(container, f"users/{user_id}") except KeyError: raise HTTPPreconditionFailed( content={"reason": f"inexistent user: {user_id}"}) if group_id not in user.groups: user.user_groups.append(group_id) user.register() for user_id in users_removed: try: user: User = await navigate_to(container, f"users/{user_id}") except KeyError: raise HTTPPreconditionFailed( content={"reason": f"inexistent user: {user_id}"}) if group_id in user.groups: user.user_groups.remove(group_id) user.register()
async def _update_groups(user_id, groups_added, groups_removed): container = get_current_container() for group_id in groups_added: try: group: Group = await navigate_to(container, f"groups/{group_id}") except KeyError: raise HTTPPreconditionFailed( content={"reason": f"inexistent group: {group_id}"}) if user_id not in group.users: group.users.append(user_id) group.register() for group_id in groups_removed: try: group: Group = await navigate_to(container, f"groups/{group_id}") except KeyError: raise HTTPPreconditionFailed( content={"reason": f"inexistent group: {group_id}"}) if user_id in group.users: group.users.remove(user_id) group.register()
async def grantinfo(context, request): payload = await request.json() inherit = payload.get("inherit", None) inheritManager = IInheritPermissionManager(context) if inherit is True: for permission in PERMISSIONS_TO_FORBIT_ONINHERIT: inheritManager.allow_inheritance(permission) elif inherit is False: for permission in PERMISSIONS_TO_FORBIT_ONINHERIT: inheritManager.deny_inheritance(permission) entries = payload.get("entries", []) try: container = get_current_container() users = await container.async_get("users") groups = await container.async_get("groups") except (AttributeError, KeyError, ContainerNotFound): return None prinrole = IPrincipalRoleManager(context) for entry in entries: valid = False if entry["type"] == "group" and await groups.async_contains(entry["id"] ): valid = True if entry["type"] == "user" and await users.async_contains(entry["id"]): valid = True if valid: for role, permission in entry["roles"].items(): if permission == "Allow": prinrole.assign_role_to_principal(entry["id"], role) elif permission == "Deny": prinrole.remove_role_from_principal(entry["id"], role) elif permission is None: prinrole.unset_role_for_principal(entry["id"], role) elif permission == "AllowSingle": prinrole.assign_role_to_principal_no_inherit( entry["id"], role)
async def get_user(self, token): if token.get('type') not in ('bearer', 'wstoken', 'cookie'): return if '.' not in token.get('token', ''): # quick way to check if actually might be jwt return cache_key = self.get_user_cache_key(token['token']) try: return LOCAL_CACHE[cache_key] except KeyError: pass validated_jwt = token['decoded'] if ('client' not in validated_jwt or 'client_args' not in validated_jwt): return try: client = utils.get_client(validated_jwt['client'], **validated_jwt['client_args']) user, user_data = await client.user_info() except Exception: logger.warning(f'Error getting user data for {token}', exc_info=True) return user = OAuthUser(user_id=user.id, properties=user_data) try: container = get_current_container() except ContainerNotFound: container = None if container is not None: user.apply_scope(validated_jwt, container.id) LOCAL_CACHE[cache_key] = user return user
async def get_notifications(context, request): results = [] container = get_current_container() multi_params = request.query_string user_Id = 0 application_name = '' notification_type = 'SIMPLE' for parametro in multi_params.split('&'): ricercato = parametro.split('=') if ricercato[0] == 'notification_type': if ricercato[1] == 'EMAIL': notification_type = 'EMAIL' else: notification_type = 'SIMPLE' elif ricercato[0] == 'application_name': application_name = ricercato[1] elif ricercato[0] == 'userId' or ricercato[0] == 'email': user_Id = ricercato[1] #all the notific. related to a userId/email async for item in container.async_values(): if 'Notification' == getattr(item, "type_name"): if getattr(item, "not_type") == notification_type and getattr( item, "application_name") == application_name and getattr( item, "recipientId") == user_Id: summary = await getMultiAdapter( (item, request), IResourceSerializeToJsonSummary)() results.append(summary) #usato per ordinare i risultati in uscita results = sorted(results, key=lambda conv: conv['creation_date']) return results
async def render(self, name, **options): if name is None: raise AttributeError("Template None is not a valid name") if name in self.cache: func = partial(self.cache[name].render, **options) return await self._loop.run_in_executor(self.executor, func) else: template = None if name.startswith("/"): container = get_current_container() try: template_obj = await navigate_to(container, name) except KeyError: template_obj = None if template_obj is not None and IJinjaTemplate.providedBy( template_obj): template_string: str = template_obj.template template = Environment( loader=BaseLoader()).from_string(template_string) else: raise KeyError(f"Wrong traversal template object {name}") else: for env in self.envs: try: template = env.get_template(name) except TemplateNotFound: pass if template is not None: break if template is None: raise KeyError(f"Invalid template id {name}") else: self.cache[name] = template func = partial(template.render, **options) return await self._loop.run_in_executor(self.executor, func)
async def get_object_by_path(path): container = get_current_container() return await navigate_to(container, path)
async def grantinfo(context, request): """ principals -> roles """ search = request.query.get("search") if search is not None: search = search.lower() result = {"available_roles": [], "entries": []} # Inherit inheritMap = IInheritPermissionMap(context) permissions = inheritMap.get_locked_permissions() if len(permissions) > 0: blocked_permissions = permissions result["inherit"] = False else: result["inherit"] = True # Roles roles = local_roles() valid_roles = [ role for role in roles if role in app_settings.get("available_roles", []) ] for role in valid_roles: role_obj = get_utility(IRole, name=role) result["available_roles"].append({ "id": role, "title": role_obj.title, "description": role_obj.description }) prinrole = IPrincipalRoleMap(context) settings = [ setting for setting in prinrole.get_principals_and_roles() if setting[0] in valid_roles ] valid_settings = {} default_roles = {role: None for role in valid_roles} try: container = get_current_container() users = await container.async_get("users") groups = await container.async_get("groups") except (AttributeError, KeyError, ContainerNotFound): return None for data in settings: if data[1] not in valid_settings: user = await users.async_get(data[1]) if user: valid_settings[data[1]] = { "id": data[1], "disabled": user.disabled, "login": None, "roles": deepcopy(default_roles), "title": user.name, "type": "user", "origin": "dbusers", } else: group = await groups.async_get(data[1]) if group: valid_settings[data[1]] = { "id": data[1], "disabled": group.disabled, "login": None, "roles": deepcopy(default_roles), "title": group.name, "type": "group", "origin": "dbusers", } else: valid_settings[data[1]] = { "id": data[1], "disabled": False, "login": None, "roles": deepcopy(default_roles), "title": data[1], "type": "user", "origin": "system", } valid_settings[data[1]]["roles"].update({data[0]: data[2]}) result["entries"] = list(valid_settings.values()) if search is not None: catalog = query_utility(ICatalogUtility) query_result = await catalog.search(container, {"type_name": ["User", "Group"]}) for obj in query_result["items"]: ident = obj.get("id", "") if search in ident.lower() and ident not in valid_settings: result["entries"].append({ "id": ident, "disabled": False, "login": None, "roles": deepcopy(default_roles), "title": obj.get("title", ""), "type": obj.get("type_name").lower(), }) return result
def __init__( self, utility, context, response=noop_response, force=False, log_details=False, memory_tracking=False, request=None, bulk_size=40, full=False, reindex_security=False, mapping_only=False, index_manager=None, children_only=False, lookup_index=False, cache=True, ): self.utility = utility self.context = context self.response = response self.force = force self.full = full self.log_details = log_details self.memory_tracking = memory_tracking self.bulk_size = bulk_size self.reindex_security = reindex_security self.children_only = children_only self.lookup_index = lookup_index if mapping_only and full: raise Exception("Can not do a full reindex and a mapping only migration") self.mapping_only = mapping_only self.txn = get_current_transaction() if not cache: # make sure that we don't cache requests... self.txn._cache = DummyCache(self.txn) self.request = request self.container = get_current_container() self.conn = utility.get_connection() if index_manager is None: self.index_manager = get_adapter(self.container, IIndexManager) else: self.index_manager = index_manager self.user = get_authenticated_user() self.policy = get_security_policy(self.user) self.indexer = Indexer() self.batch = {} self.indexed = 0 self.processed = 0 self.missing = [] self.orphaned = [] self.existing = [] self.errors = [] self.mapping_diff = {} self.start_time = self.index_start_time = time.time() self.reindex_futures = [] self.status = "started" self.active_task_id = None self.copied_docs = 0 self.work_index_name = None self.sub_indexes = []