Example #1
0
    def create_user(self, *args, **kwargs):
        """Create user with given details and return its id"""
        disableCSRFProtection()
        # FIXME: we are alrady using robotframework = 3.0
        # XXX: Because kwargs are only supported with robotframework >= 2.8.3,
        # we must parse them here to support robotframework < 2.8.3.
        for arg in [x for x in args if '=' in x]:
            name, value = arg.split('=', 1)
            kwargs[name] = value

        assert len(args), u"username must be provided."
        username = args[0]

        roles = []
        properties = kwargs
        for arg in [x for x in args[1:] if '=' not in x]:
            roles.append(arg)

        if 'email' not in properties:
            properties['email'] = '*****@*****.**' % username

        portal = getSite()
        registration = getToolByName(portal, 'portal_registration')
        registry = getUtility(IRegistry)
        settings = registry.forInterface(ISecuritySchema, prefix='plone')
        use_email_as_username = getattr(settings, 'use_email_as_login', None)
        user_id = use_email_as_username and properties['email'] or username
        password = properties.pop('password', username)

        roles.extend(properties.pop('roles', []))
        if not roles:
            roles.append('Member')
        properties['username'] = user_id
        registration.addMember(
            user_id, password, roles, properties=properties)
Example #2
0
    def create_user(self, *args, **kwargs):
        """Create user with given details and return its id"""
        disableCSRFProtection()
        # FIXME: we are alrady using robotframework = 3.0
        # XXX: Because kwargs are only supported with robotframework >= 2.8.3,
        # we must parse them here to support robotframework < 2.8.3.
        for arg in [x for x in args if '=' in x]:
            name, value = arg.split('=', 1)
            kwargs[name] = value

        assert len(args), u"username must be provided."
        username = args[0]

        roles = []
        properties = kwargs
        for arg in [x for x in args[1:] if '=' not in x]:
            roles.append(arg)

        if 'email' not in properties:
            properties['email'] = '*****@*****.**' % username

        portal = getSite()
        registration = getToolByName(portal, 'portal_registration')
        registry = getUtility(IRegistry)
        settings = registry.forInterface(ISecuritySchema, prefix='plone')
        use_email_as_username = getattr(settings, 'use_email_as_login', None)
        user_id = use_email_as_username and properties['email'] or username
        password = properties.pop('password', username)

        roles.extend(properties.pop('roles', []))
        if not roles:
            roles.append('Member')
        properties['username'] = user_id
        registration.addMember(user_id, password, roles, properties=properties)
Example #3
0
 def set_default_language(self, language=None):
     """Change portal default language"""
     disableCSRFProtection()
     if language is None:
         language = os.environ.get('LANGUAGE') or 'en'
     registry = getUtility(IRegistry)
     settings = registry.forInterface(ILanguageSchema, prefix='plone')
     settings.default_language = language
Example #4
0
 def set_default_language(self, language=None):
     """Change portal default language"""
     disableCSRFProtection()
     if language is None:
         language = os.environ.get('LANGUAGE') or 'en'
     registry = getUtility(IRegistry)
     settings = registry.forInterface(ILanguageSchema, prefix='plone')
     settings.default_language = language
Example #5
0
 def set_default_language(self, language=None):
     """Change portal default language"""
     disableCSRFProtection()
     portal = getSite()
     portal_languages = getToolByName(portal, 'portal_languages')
     if language is None:
         language = os.environ.get('LANGUAGE') or 'en'
     setattr(portal, 'language', language)
     portal_languages.setDefaultLanguage(language)
 def set_default_language(self, language=None):
     """Change portal default language"""
     disableCSRFProtection()
     portal = getSite()
     portal_languages = getToolByName(portal, 'portal_languages')
     if language is None:
         language = os.environ.get('LANGUAGE') or 'en'
     setattr(portal, 'language', language)
     portal_languages.setDefaultLanguage(language)
    def disable_autologin(self):
        """Clear DomainAuthHelper's map to effectively 'logout' user
        after 'autologin_as'. Example of use::

            Disable autologin

        """
        if 'robot_login' in self.acl_users.objectIds():
            disableCSRFProtection()
            self.acl_users.robot_login._domain_map.clear()
Example #8
0
 def fire_transition(self, content, action):
     """Fire workflow action for content"""
     disableCSRFProtection()
     # It should be ok to use unrestricted-methods, because workflow
     # transition guard should proctect unprivileged transition:
     pc = getToolByName(self, 'portal_catalog')
     results = pc.unrestrictedSearchResults(UID=content)
     obj = results[0]._unrestrictedGetObject()
     wftool = getToolByName(obj, 'portal_workflow')
     wftool.doActionFor(obj, action)
    def disable_autologin(self):
        """Clear DomainAuthHelper's map to effectively 'logout' user
        after 'autologin_as'. Example of use::

            Disable autologin

        """
        if 'robot_login' in self.acl_users.objectIds():
            disableCSRFProtection()
            self.acl_users.robot_login._domain_map.clear()
 def the_mail_setup_configured(self):
     disableCSRFProtection()
     registry = queryUtility(IRegistry)
     if registry is None:
         return
     mail_settings = registry.forInterface(IMailSchema, prefix='plone')
     if mail_settings is None:
         return
     mail_settings.smtp_host = u'localhost'
     mail_settings.email_from_address = '*****@*****.**'
 def fire_transition(self, content, action):
     """Fire workflow action for content"""
     disableCSRFProtection()
     # It should be ok to use unrestricted-methods, because workflow
     # transition guard should proctect unprivileged transition:
     pc = getToolByName(self, 'portal_catalog')
     results = pc.unrestrictedSearchResults(UID=content)
     obj = results[0]._unrestrictedGetObject()
     wftool = getToolByName(obj, 'portal_workflow')
     wftool.doActionFor(obj, action)
 def the_self_registration_enabled(self):
     disableCSRFProtection()
     registry = queryUtility(IRegistry)
     if registry is None:
         return
     security_settings = registry.forInterface(
         ISecuritySchema, prefix='plone')
     if security_settings is None:
         return
     security_settings.enable_self_reg = True
 def the_self_registration_enabled(self):
     disableCSRFProtection()
     registry = queryUtility(IRegistry)
     if registry is None:
         return
     security_settings = registry.forInterface(ISecuritySchema,
                                               prefix='plone')
     if security_settings is None:
         return
     security_settings.enable_self_reg = True
 def the_mail_setup_configured(self):
     disableCSRFProtection()
     registry = queryUtility(IRegistry)
     if registry is None:
         return
     mail_settings = registry.forInterface(IMailSchema, prefix='plone')
     if mail_settings is None:
         return
     mail_settings.smtp_host = 'localhost'
     mail_settings.email_from_address = '*****@*****.**'
 def set_autologin_username(self, username):
     """Update autologin mapping with the given username
     """
     disableCSRFProtection()
     if 'robot_login' not in self.acl_users.objectIds():
         raise Exception(u"Autologin is not enabled")
     if len(self.acl_users.robot_login._domain_map) == 0:
         raise Exception(u"Autologin is not enabled")
     domain_map_key = self.acl_users.robot_login._domain_map.keys()[0]
     domain_map = self.acl_users.robot_login._domain_map[domain_map_key]
     domain_map[0]['username'] = username
     self.acl_users.robot_login._domain_map[domain_map_key] = domain_map
 def set_autologin_username(self, username):
     """Update autologin mapping with the given username
     """
     disableCSRFProtection()
     if 'robot_login' not in self.acl_users.objectIds():
         raise Exception(u"Autologin is not enabled")
     if len(self.acl_users.robot_login._domain_map) == 0:
         raise Exception(u"Autologin is not enabled")
     domain_map_key = list(self.acl_users.robot_login._domain_map.keys())[0]
     domain_map = self.acl_users.robot_login._domain_map[domain_map_key]
     domain_map[0]['username'] = username
     self.acl_users.robot_login._domain_map[domain_map_key] = domain_map
Example #17
0
 def delete_content(self, uid_or_path):
     """Delete content by uid or path"""
     disableCSRFProtection()
     portal = getSite()
     pc = getToolByName(portal, 'portal_catalog')
     uid_results =\
         pc.unrestrictedSearchResults(UID=uid_or_path)
     path_results = \
         pc.unrestrictedSearchResults(
             path={'query': uid_or_path.rstrip('/'), 'depth': 0})
     content =\
         (uid_results or path_results)[0]._unrestrictedGetObject()
     content.aq_parent.manage_delObjects([content.getId()])
 def delete_content(self, uid_or_path):
     """Delete content by uid or path"""
     disableCSRFProtection()
     portal = getSite()
     pc = getToolByName(portal, 'portal_catalog')
     uid_results =\
         pc.unrestrictedSearchResults(UID=uid_or_path)
     path_results = \
         pc.unrestrictedSearchResults(
             path={'query': uid_or_path.rstrip('/'), 'depth': 0})
     content =\
         (uid_results or path_results)[0]._unrestrictedGetObject()
     content.aq_parent.manage_delObjects([content.getId()])
 def set_field_language_independent(self, portal_type, field, value='1'):
     """Set the given field in the given portal type language independent
     or unset from being one
     """
     disableCSRFProtection()
     for schema in iterSchemataForType(portal_type):
         if field in schema:
             ob = schema[field]
             if ILanguageIndependentField.providedBy(ob):
                 if value.lower() not in ('true', 'on', 'yes', 'y', '1'):
                     noLongerProvides(schema[ob], ILanguageIndependentField)
             else:
                 if value.lower() in ('true', 'on', 'yes', 'y', '1'):
                     alsoProvides(ob, ILanguageIndependentField)
Example #20
0
 def set_field_language_independent(self, portal_type, field, value='1'):
     """Set the given field in the given portal type language independent
     or unset from being one
     """
     disableCSRFProtection()
     for schema in iterSchemataForType(portal_type):
         if field in schema:
             ob = schema[field]
             if ILanguageIndependentField.providedBy(ob):
                 if value.lower() not in ('true', 'on', 'yes', 'y', '1'):
                     noLongerProvides(schema[ob], ILanguageIndependentField)
             else:
                 if value.lower() in ('true', 'on', 'yes', 'y', '1'):
                     alsoProvides(ob, ILanguageIndependentField)
Example #21
0
    def create_content_type(self, portal_type):
        """Create dummy content type with a single custom field"""
        disableCSRFProtection()
        fti = DexterityFTI(str(portal_type), title=portal_type)
        fti.behaviors = (
            'plone.app.dexterity.behaviors.metadata.IBasic',
            'plone.app.multilingual.dx.interfaces.IDexterityTranslatable')
        fti.model_source = u"""\
<model xmlns="http://namespaces.plone.org/supermodel/schema">
<schema>
<field name="custom" type="zope.schema.TextLine">
  <description />
  <required>False</required>
  <title>Custom field</title>
</field>
</schema>
</model>"""
        fti.global_allow = True
        self.portal_types._setObject(str(portal_type), fti)
    def create_translation(self, *args, **kwargs):
        """Create translation for an object with uid in the given
        target_language and return its UID

        Usage::

            Create translation  /plone/en/foo  ca  title=Translated
        """
        disableCSRFProtection()
        # Parse arguments:
        uid_or_path = args[0]
        target_language = args[1]

        # BBB: Support keywords arguments with robotframework < 2.8.3
        kwargs.update(dict([arg.split('=', 1) for arg in args[2:]]))

        # Look up translatable content
        pc = getToolByName(self, "portal_catalog")
        uid_results = pc.unrestrictedSearchResults(UID=uid_or_path)
        path_results = pc.unrestrictedSearchResults(
            path={
                'query': uid_or_path.rstrip('/'),
                'depth': 0
            })
        obj = (uid_results or path_results)[0]._unrestrictedGetObject()

        # Translate
        manager = ITranslationManager(obj)
        manager.add_translation(target_language)
        translation = manager.get_translation(target_language)

        # Update fields
        data = constructMessageFromSchemata(obj, iterSchemata(obj))
        for key, value in kwargs.items():
            del data[key]
            data[key] = Header(value, 'utf-8')
        del data['language']
        initializeObjectFromSchemata(translation, iterSchemata(obj), data)
        notify(ObjectModifiedEvent(translation))

        # Return uid for the translation
        return IUUID(translation)
    def enable_autologin_as(self, *args):
        """Add and configure DomainAuthHelper PAS-plugin to login
        all anonymous users from localhost as a special *Remote User* with
        one or more given roles. Examples of use::

            Enable autologin as  Manager
            Enable autologin as  Site Administrator
            Enable autologin as  Member  Contributor

        """
        disableCSRFProtection()
        if 'robot_login' in self.acl_users.objectIds():
            self.acl_users.robot_login._domain_map.clear()
        else:
            DomainAuthHelper.manage_addDomainAuthHelper(
                self.acl_users, 'robot_login')
            activatePluginInterfaces(self, 'robot_login')
        user = '******'.join(sorted(args))
        self.acl_users.robot_login.manage_addMapping(
            match_type='regex', match_string='.*', roles=args, username=user)
    def create_content_type(self, portal_type):
        """Create dummy content type with a single custom field"""
        disableCSRFProtection()
        fti = DexterityFTI(str(portal_type), title=portal_type)
        fti.behaviors = (
            'plone.app.dexterity.behaviors.metadata.IBasic',
            'plone.app.multilingual.dx.interfaces.IDexterityTranslatable'
        )
        fti.model_source = u"""\
<model xmlns="http://namespaces.plone.org/supermodel/schema">
<schema>
<field name="custom" type="zope.schema.TextLine">
  <description />
  <required>False</required>
  <title>Custom field</title>
</field>
</schema>
</model>"""
        fti.global_allow = True
        self.portal_types._setObject(str(portal_type), fti)
    def enable_autologin_as(self, *args):
        """Add and configure DomainAuthHelper PAS-plugin to login
        all anonymous users from localhost as a special *Remote User* with
        one or more given roles. Examples of use::

            Enable autologin as  Manager
            Enable autologin as  Site Administrator
            Enable autologin as  Member  Contributor

        """
        disableCSRFProtection()
        if 'robot_login' in self.acl_users.objectIds():
            self.acl_users.robot_login._domain_map.clear()
        else:
            DomainAuthHelper.manage_addDomainAuthHelper(
                self.acl_users, 'robot_login')
            activatePluginInterfaces(self, 'robot_login')
        user = '******'.join(sorted(args))
        self.acl_users.robot_login.manage_addMapping(match_type='regex',
                                                     match_string='.*',
                                                     roles=args,
                                                     username=user)
    def create_translation(self, *args, **kwargs):
        """Create translation for an object with uid in the given
        target_language and return its UID

        Usage::

            Create translation  /plone/en/foo  ca  title=Translated
        """
        disableCSRFProtection()
        # Parse arguments:
        uid_or_path = args[0]
        target_language = args[1]

        # BBB: Support keywords arguments with robotframework < 2.8.3
        kwargs.update(dict([arg.split('=', 1) for arg in args[2:]]))

        # Look up translatable content
        pc = getToolByName(self, "portal_catalog")
        uid_results = pc.unrestrictedSearchResults(UID=uid_or_path)
        path_results = pc.unrestrictedSearchResults(
            path={'query': uid_or_path.rstrip('/'), 'depth': 0})
        obj = (uid_results or path_results)[0]._unrestrictedGetObject()

        # Translate
        manager = ITranslationManager(obj)
        manager.add_translation(target_language)
        translation = manager.get_translation(target_language)

        # Update fields
        data = constructMessageFromSchemata(obj, iterSchemata(obj))
        for key, value in kwargs.items():
            del data[key]
            data[key] = Header(value, 'utf-8')
        del data['language']
        initializeObjectFromSchemata(translation, iterSchemata(obj), data)
        notify(ObjectModifiedEvent(translation))

        # Return uid for the translation
        return IUUID(translation)
Example #27
0
    def create_content(self, *args, **kwargs):
        """Create content and return its UID"""
        disableCSRFProtection()
        # XXX: Because kwargs are only supported with robotframework >= 2.8.3,
        # we must parse them here to support robotframework < 2.8.3.
        for arg in [x for x in args if '=' in x]:
            name, value = arg.split('=', 1)
            kwargs[name] = value

        assert 'type' in kwargs, u"Keyword arguments must include 'type'."
        portal_type = kwargs.get('type')
        portal = getSite()
        if 'container' in kwargs:
            pc = getToolByName(portal, 'portal_catalog')
            uid_or_path = kwargs.pop('container')
            uid_results =\
                pc.unrestrictedSearchResults(UID=uid_or_path)
            path_results = \
                pc.unrestrictedSearchResults(
                    path={'query': uid_or_path.rstrip('/'), 'depth': 0})
            container =\
                (uid_results or path_results)[0]._unrestrictedGetObject()
        else:
            container = portal

        # if we create 'file' and 'image' kwargs entries, they should not be
        # used to create the content but be set afterwards
        create_kwargs = {}
        create_kwargs.update(kwargs)

        if HAS_DEXTERITY:
            if portal_type in ('File', ) and 'file' not in kwargs:
                pdf_file = os.path.join(os.path.dirname(__file__), 'content',
                                        u'file.pdf')
                value = NamedBlobFile(data=open(pdf_file, 'r').read(),
                                      contentType='application/pdf',
                                      filename=u'file.pdf')
                kwargs['file'] = value

        if portal_type in ('Image', 'News Item') and 'image' not in kwargs:
            prefill_image_types(portal, kwargs)

        id_ = kwargs.pop('id', None)
        type_ = kwargs.pop('type')

        content = None
        if HAS_DEXTERITY:
            # The title attribute for Dexterity types needs to be unicode
            if 'title' in kwargs and isinstance(kwargs['title'], str):
                kwargs['title'] = kwargs['title'].decode('utf-8')
            from plone.dexterity.interfaces import IDexterityFTI
            from plone.dexterity.utils import createContentInContainer
            try:
                getUtility(IDexterityFTI, name=type_)
                content = createContentInContainer(container, type_,
                                                   **create_kwargs)
                if id_ is not None and content.id != id_:
                    container.manage_renameObject(content.id, id_)
            except ComponentLookupError:
                pass

        if HAS_DEXTERITY and content:
            # For dexterity-types, we need a second pass to fill all fields
            # using their widgets to get e.g. RichText-values created
            # correctly.
            fti = getUtility(IDexterityFTI, name=type_)
            schema = fti.lookupSchema()
            fields = {}
            for name in schema:
                fields[name] = schema[name]
            for schema in getAdditionalSchemata(portal_type=type_):
                for name in schema:
                    fields[name] = schema[name]
            for name, field in fields.items():
                widget = queryMultiAdapter((field, getRequest()), IFieldWidget)
                if widget and name in kwargs:
                    if not IFromUnicode.providedBy(field):
                        value = kwargs[name]
                    elif isinstance(kwargs[name], unicode):
                        value = kwargs[name]
                    else:
                        value = unicode(str(kwargs[name]),
                                        'utf-8',
                                        errors='ignore')
                    converter = IDataConverter(widget)
                    dm = queryMultiAdapter((content, field), IDataManager)
                    if dm:
                        dm.set(converter.toFieldValue(value))

        if content is None:
            if id_ is None:
                normalizer = queryUtility(IURLNormalizer)
                id_ = normalizer.normalize(kwargs['title'])

            # It must be Archetypes based content:
            content = container[container.invokeFactory(type_, id_, **kwargs)]
            content.processForm()

        return IUUID(content)
 def apply_profile(self, name):
     """Apply named profile"""
     disableCSRFProtection()
     from Products.CMFCore.utils import getToolByName
     portal_setup = getToolByName(self, 'portal_setup')
     portal_setup.runAllImportStepsFromProfile('profile-%s' % name)
Example #29
0
 def global_allow(self, type_, value=True):
     """Allow type to be added globally."""
     disableCSRFProtection()
     portal = getSite()
     types_tool = getToolByName(portal, "portal_types")
     types_tool[type_].global_allow = value
 def apply_profile(self, name):
     """Apply named profile"""
     disableCSRFProtection()
     from Products.CMFCore.utils import getToolByName
     portal_setup = getToolByName(self, 'portal_setup')
     portal_setup.runAllImportStepsFromProfile('profile-%s' % name)
    def create_content(self, *args, **kwargs):
        """Create content and return its UID"""
        disableCSRFProtection()
        # XXX: Because kwargs are only supported with robotframework >= 2.8.3,
        # we must parse them here to support robotframework < 2.8.3.
        for arg in [x for x in args if '=' in x]:
            name, value = arg.split('=', 1)
            kwargs[name] = value

        assert 'type' in kwargs, u"Keyword arguments must include 'type'."
        portal_type = kwargs.get('type')
        portal = getSite()
        if 'container' in kwargs:
            pc = getToolByName(portal, 'portal_catalog')
            uid_or_path = kwargs.pop('container')
            uid_results =\
                pc.unrestrictedSearchResults(UID=uid_or_path)
            path_results = \
                pc.unrestrictedSearchResults(
                    path={'query': uid_or_path.rstrip('/'), 'depth': 0})
            container =\
                (uid_results or path_results)[0]._unrestrictedGetObject()
        else:
            container = portal

        # if we create 'file' and 'image' kwargs entries, they should not be
        # used to create the content but be set afterwards
        create_kwargs = {}
        create_kwargs.update(kwargs)

        if HAS_DEXTERITY:
            if portal_type in ('File', ) and 'file' not in kwargs:
                pdf_file = os.path.join(
                    os.path.dirname(__file__), 'content', u'file.pdf')
                value = NamedBlobFile(
                    data=open(pdf_file, 'r').read(),
                    contentType='application/pdf',
                    filename=u'file.pdf'
                )
                kwargs['file'] = value

        if portal_type in ('Image', 'News Item') and 'image' not in kwargs:
            prefill_image_types(portal, kwargs)

        id_ = kwargs.pop('id', None)
        type_ = kwargs.pop('type')

        content = None
        if HAS_DEXTERITY:
            # The title attribute for Dexterity types needs to be unicode
            if 'title' in kwargs and isinstance(kwargs['title'], str):
                kwargs['title'] = kwargs['title'].decode('utf-8')
            from plone.dexterity.interfaces import IDexterityFTI
            from plone.dexterity.utils import createContentInContainer
            try:
                getUtility(IDexterityFTI, name=type_)
                content = createContentInContainer(
                    container, type_, **create_kwargs)
                if id_ is not None and content.id != id_:
                    container.manage_renameObject(content.id, id_)
            except ComponentLookupError:
                pass

        if HAS_DEXTERITY and content:
            # For dexterity-types, we need a second pass to fill all fields
            # using their widgets to get e.g. RichText-values created
            # correctly.
            fti = getUtility(IDexterityFTI, name=type_)
            schema = fti.lookupSchema()
            fields = {}
            for name in schema:
                fields[name] = schema[name]
            for schema in getAdditionalSchemata(portal_type=type_):
                for name in schema:
                    fields[name] = schema[name]
            for name, field in fields.items():
                widget = queryMultiAdapter((field, getRequest()), IFieldWidget)
                if widget and name in kwargs:
                    if not IFromUnicode.providedBy(field):
                        value = kwargs[name]
                    elif isinstance(kwargs[name], unicode):
                        value = kwargs[name]
                    else:
                        value = unicode(str(kwargs[name]), 'utf-8',
                                        errors='ignore')
                    converter = IDataConverter(widget)
                    dm = queryMultiAdapter((content, field), IDataManager)
                    if dm:
                        dm.set(converter.toFieldValue(value))

        if content is None:
            if id_ is None:
                normalizer = queryUtility(IURLNormalizer)
                id_ = normalizer.normalize(kwargs['title'])

            # It must be Archetypes based content:
            content = container[container.invokeFactory(type_, id_, **kwargs)]
            content.processForm()

        return IUUID(content)
 def global_allow(self, type_, value=True):
     """Allow type to be added globally."""
     disableCSRFProtection()
     portal = getSite()
     types_tool = getToolByName(portal, "portal_types")
     types_tool[type_].global_allow = value