Exemple #1
0
    # Search the Catalog for login and return a list of person objects
    # login can be a string or a list of strings
    # (no docstring to prevent publishing)
    if not login:
      return []
    if isinstance(login, list):
      login = tuple(login)
    elif not isinstance(login, tuple):
      login = str(login)
    try:
      return getUserByLogin(self.getPortalObject(), login, exact_match)
    except ConflictError:
      raise
    except:
      LOG('ERP5Security', PROBLEM, 'getUserByLogin failed', error=sys.exc_info())
      # Here we must raise an exception to prevent callers from caching
      # a result of a degraded situation.
      # The kind of exception does not matter as long as it's catched by
      # PAS and causes a lookup using another plugin or user folder.
      # As PAS does not define explicitely such exception, we must use
      # the _SWALLOWABLE_PLUGIN_EXCEPTIONS list.
      raise _SWALLOWABLE_PLUGIN_EXCEPTIONS[0]


classImplements( ERP5UserManager
               , IAuthenticationPlugin
               , IUserEnumerationPlugin
               )

InitializeClass(ERP5UserManager)
Exemple #2
0
    if REQUEST is None:
      REQUEST = get_request()
    if self.getWebSiteValue():
      site_url = self.getWebSiteValue().absolute_url()
    elif REQUEST and 'came_from' in REQUEST:
      site_url = REQUEST.came_from
    else:
      site_url = self.getPortalObject().absolute_url()
    try:
      register_user_login, expiration_date = self._password_request_dict[
        password_key]
    except KeyError:
      # XXX: incorrect grammar and not descriptive enough
      return error('Key not known. Please ask reset password.')
    if user_login is not None and register_user_login != user_login:
      # XXX: not descriptive enough
      return error("Bad login provided.")
    if DateTime() > expiration_date:
      # XXX: incorrect grammar
      return error("Date has expire.")
    del self._password_request_dict[password_key]
    persons = self.getPortalObject().acl_users.erp5_users.getUserByLogin(
      register_user_login)
    person = persons[0]
    person._forceSetPassword(password)
    person.reindexObject()
    return redirect(REQUEST, site_url,
                    translateString("Password changed."))

InitializeClass(PasswordTool)
Exemple #3
0
      return "Subscribed to Timer Service"
    return "TimerService not available"

  security.declareProtected(Permissions.ManageProperties, 'unsubscribe')
  def unsubscribe(self):
    """Unsubscribe from the global Timer Service"""
    service = getTimerService(self)
    if service:
      service.unsubscribe(self)
      return "Usubscribed from Timer Service"
    return "TimerService not available"

  security.declarePrivate('manage_beforeDelete')
  def manage_beforeDelete(self, *args, **kw):
    self.unsubscribe()
    super(TimerServiceMixin, self).manage_beforeDelete(*args, **kw)

  security.declarePrivate('manage_afterAdd')
  def manage_afterAdd(self, *args, **kw):
    self.subscribe()
    super(TimerServiceMixin, self).manage_afterAdd(*args, **kw)

  security.declarePublic('getCurrentNode')
  getCurrentNode = ActivityTool.getCurrentNode.im_func
  security.declarePublic('getServerAddress')
  getServerAddress = ActivityTool.getServerAddress.im_func

  _isValidNodeName = ActivityTool._isValidNodeName.im_func

InitializeClass(TimerServiceMixin)
Exemple #4
0
            # Prepare definition dict once only
            category_definition_dict = {}
            for c in self.getRoleCategoryList():
                bc, value = c.split('/', 1)
                category_definition_dict.setdefault(bc, []).append(value)

            # category_result is a list of dicts that represents the resolved
            # categories we create a category_value_dict from each of these
            # dicts aggregated with category_order and statically defined
            # categories
            for category_dict in category_result:
                category_value_dict = {'category_order': category_order_list}
                category_value_dict.update(category_dict)
                category_value_dict.update(category_definition_dict)
                group_id_list = group_id_generator(**category_value_dict)
                if group_id_list:
                    if isinstance(group_id_list, str):
                        # Single group is defined (this is usually for group membership)
                        # DEPRECATED due to cartesian product requirement
                        group_id_list = group_id_list,
                    # Multiple groups are defined (list of users
                    # or list of group IDs resulting from a cartesian product)
                    for group_id in group_id_list:
                        group_id_role_dict[group_id] = role_list

        return group_id_role_dict


InitializeClass(RoleInformation)
Exemple #5
0
    def setDescription(self, value):
        """
          Sets the description by invoking the Accessor
          based method rather than the one inherited from CMF.
          This is require to make sure that value is casted
      """
        self._setDescription(value)
        self.reindexObject()

    security.declareProtected(Permissions.ModifyPortalContent,
                              'XUpdateDocument')

    def XUpdateDocument(self, xupdate):
        """
          Update a document by providing an xupdate XML file
      """
        pass

    security.declareProtected(Permissions.ModifyPortalContent, 'fromXML')

    def fromXML(self, xml):
        """
          Replace the content of this object by providing an xml content
      """
        from erp5.component.module.ERP5Conduit import ERP5Conduit
        conduit = ERP5Conduit()
        conduit.addNode(object=self, xml=xml)


InitializeClass(XMLObject)
Exemple #6
0
    def getObject(module, name, reload=0):
        # Modified version that ignore errors as long as the module can be be
        # imported, which is enough to use a ZODB Extension as a brain.
        try:
            m = __import__('erp5.component.extension.%s' % module, globals(),
                           {}, 'erp5.component.extension')

            o = getattr(m, name, None)
            if o is None:
                raise ImportError(
                    "Cannot get %s from erp5.component.extension.%s" %
                    (name, module))

            return o
        except ImportError:
            return original_function(module, name, reload=reload)

    return getObject


# This get Object exists both in App.Extensions.getObject and Shared.DC.ZRDB.DA
# for some versions of Zope/Products.ZSQLMethods, so we try to patch both if
# they exist
import Shared.DC.ZRDB.DA
if hasattr(Shared.DC.ZRDB.DA, 'getObject'):
    Shared.DC.ZRDB.DA.getObject = getObjectMeta(Shared.DC.ZRDB.DA.getObject)

import App.Extensions
App.Extensions.getObject = getObjectMeta(App.Extensions.getObject)
InitializeClass(DA)
Exemple #7
0
    security.declarePublic('getReportTreeMode')

    def getReportTreeMode(self):
        return getattr(self, 'report_tree_mode', 0)

    security.declarePublic('getAnonymousSelectionKey')

    def getAnonymousSelectionKey(self):
        return md5(
            repr({k: v
                  for k, v in self.__dict__.iteritems()
                  if k != 'index'})).hexdigest()


InitializeClass(Selection)
allow_class(Selection)


class DomainSelection(Acquisition.Implicit, Traversable, Persistent):
    """
    A class to store a selection of domains which defines a report
    section. There are different ways to use DomainSelection in
    SQL methods. As a general principle, SQL methods are passed
    DomainSelection instances as a parameter.

    Example 1: (hand coded)

    The domain is accessed directly from the selection and a list of
    uids is gathered from the ZODB to feed the SQL request. This
    approach is only suitable for categories and relations. It is
Exemple #8
0
    security.declarePublic('searchAndActivate')

    def searchAndActivate(self, *args, **kw):
        """Restricted version of _searchAndActivate"""
        return self._searchAndActivate(restricted=True, *args, **kw)

    security.declareProtected(Permissions.ManagePortal, 'upgradeSchema')

    def upgradeSchema(self, sql_catalog_id=None, src__=0):
        catalog = self.getSQLCatalog(sql_catalog_id)
        connection_id = catalog.z_create_catalog.connection_id
        src = []
        for clear_method in catalog.sql_clear_catalog:
            clear_method = catalog[clear_method]
            try:
                r = clear_method._upgradeSchema(connection_id, src__=1)
            except ProgrammingError, e:
                if e[0] != NO_SUCH_TABLE:
                    raise
                r = clear_method(src__=1)
            if r:
                src.append(r)
        if src and not src__:
            query = self.getPortalObject()[connection_id]().query
            for r in src:
                query(r)
        return src


InitializeClass(CatalogTool)
Exemple #9
0
            context, rounding=rounding, movement_generator=movement_generator)

        # Apply Diff
        for movement in movement_diff.getDeletableMovementList():
            movement.getParentValue().deleteContent(movement.getId())
        for movement, kw in movement_diff.getUpdatableMovementList():
            movement.edit(**kw)
            for property_id in kw:
                movement.clearRecordedProperty(property_id)
        for movement in movement_diff.getNewMovementList():
            d = movement.__dict__
            assert movement.isTempObject()
            if '_original' in d:
                # slow but safe way (required for compensated movements)
                context.newContent(portal_type=self.movement_type,
                                   **_getPropertyAndCategoryList(movement))
                continue
            # fast way (we had to make sure such optimization
            # does not touch existing persistent data)
            del movement.__dict__
            movement = context.newContent(portal_type=self.movement_type)
            d.update(movement.__dict__)
            categories = d.pop('categories')
            movement.__dict__ = d
            # Force update of local indexes on linked objects
            # (important for 'delivery').
            movement._setCategoryList(categories)


InitializeClass(MovementCollectionUpdaterMixin)
Exemple #10
0
            # self.wfile.write(token.to_string())
        except OAuthError, err:
            self.send_oauth_error(err, REQUEST)
        return

    # protected resources
    if path.startswith(RESOURCE_URL):
        try:
            # verify the request has been oauth authorized
            consumer, token, params = self.verify_request(oauth_request)
            # send okay response
            # self.send_response(200, 'OK')
            # self.end_headers()
            # # return the extra parameters - just for something to return
            # self.wfile.write(str(params))
            return str(params)
        except OAuthError, err:
            self.send_oauth_error(err, REQUEST)
        return

  # alias method
  request_token_ready = call
  request_token = call
  authorize = call
  access_token = call
  photos = call
  authorizationVerified = call


InitializeClass(OAuthTool)
Exemple #11
0
            self._renameCellRange(*new_cell_range, **kwd)


class TempXMLMatrix(XMLMatrix):
    """Temporary XMLMatrix.

    If we need Base services (categories, edit, etc) in temporary objects
    we shoud used TempBase
  """
    isIndexable = ConstantGetter('isIndexable', value=False)

    def newCellContent(self, id):
        """
       Creates a new content in a cell.
    """
        new_temp_object = TempBase(id)
        self._setObject(id, new_temp_object)
        return self.get(id)

    def reindexObject(self, *args, **kw):
        pass

    def unindexObject(self, *args, **kw):
        pass

    def activate(self):
        return self


InitializeClass(XMLMatrix)
Exemple #12
0
        for c in child_value_list:
          if include_if_child:
            value_list.append(c)
          else:
            if len(c.objectIds(self.allowed_types))==0:
              value_list.append(c)

      if checked_permission is not None:
        checkPermission = self.portal_membership.checkPermission
        def permissionFilter(obj):
          return checkPermission(checked_permission, obj)
        value_list = filter(permissionFilter, value_list)

      return sortValueList(value_list, sort_on, sort_order, **kw)

    # Alias for compatibility
    security.declareProtected(Permissions.AccessContentsInformation,
                              'getBaseCategory')
    getBaseCategory = getBaseCategoryValue

    # Hardcode these getters as they are used when generating
    # accessors
    getReadPermission = BaseGetter('getReadPermission', 'read_permission',
                                   'string')

    getWritePermission = BaseGetter('getWritePermission', 'write_permission',
                                    'string')

InitializeClass( Category )
InitializeClass( BaseCategory )
Exemple #13
0
            else:
                source_code_line_list = []
                for line in f:
                    for (filesystem_module,
                         zodb_module) in filesystem_zodb_module_mapping_set:
                        if line.startswith("from " + filesystem_module + " "):
                            line = line.replace(filesystem_module, zodb_module,
                                                1)
                            break

                    source_code_line_list.append(line)

                source_code = ''.join(source_code_line_list)

        # Checking that the source code is syntactically correct is not
        # needed when importing from filesystem, moreover errors may occur
        # if in the same transaction a Component is created and another
        # one depending upon the former...
        object_id = '%s.%s.%s' % (cls.getIdPrefix(), version, reference)
        new_component = context.newContent(id=object_id,
                                           reference=reference,
                                           source_reference=source_reference,
                                           version=version,
                                           text_content=source_code,
                                           portal_type=cls.portal_type)

        return new_component


InitializeClass(ComponentMixin)
    def getConfigurationPropertyIdList(self):
        """
    """
        return self._getConfigurationPropertyDict().keys()

    security.declareProtected(Permissions.AccessContentsInformation,
                              'getConfigurationPropertyDict')

    def getConfigurationPropertyDict(self):
        """
    """
        return dict(self._getConfigurationPropertyDict())

    security.declareProtected(Permissions.ModifyPortalContent,
                              'updateConfiguration')

    def updateConfiguration(self, **kw):
        """
    """
        self._getConfigurationPropertyDict().update(kw)

    def _getConfigurationPropertyDict(self):
        if getattr(aq_base(self), '_configuration_property_dict',
                   None) is None:
            self._configuration_property_dict = PersistentMapping()
        return self._configuration_property_dict


InitializeClass(ConfigurableMixin)
    security.declareProtected(Permissions.AccessContentsInformation,
                              'getTargetFormatTitleList')

    def getTargetFormatTitleList(self):
        """
      Returns a list of acceptable formats for conversion
    """
        return [x[0] for x in self.getTargetFormatItemList()]

    security.declareProtected(Permissions.AccessContentsInformation,
                              'getTargetFormatList')

    def getTargetFormatList(self):
        """
      Returns a list of acceptable formats for conversion
    """
        return [x[1] for x in self.getTargetFormatItemList()]

    security.declareProtected(Permissions.ModifyPortalContent,
                              'isTargetFormatAllowed')

    def isTargetFormatAllowed(self, format):  # pylint: disable=redefined-builtin
        """
      Checks if the current document can be converted
      into the specified target format.
    """
        return format in self.getTargetFormatList()


InitializeClass(CachedConvertableMixin)
Exemple #16
0
    def isAuthenticationPolicyEnabled(self):
        """
    Return True if authentication policy is enabled.
    This method exists here due to bootstrap issues.
    It should work even if erp5_authentication_policy bt5 is not installed.
    """

        # XXX: define an interface
        def _isAuthenticationPolicyEnabled():
            portal_preferences = self.getPortalObject().portal_preferences
            method_id = 'isPreferredAuthenticationPolicyEnabled'
            method = getattr(self, method_id, None)
            if method is not None and method():
                return True
            return False

        tv = getTransactionalVariable()
        tv_key = 'PreferenceTool._isAuthenticationPolicyEnabled.%s' % getSecurityManager(
        ).getUser().getId()
        if tv.get(tv_key, None) is None:
            _isAuthenticationPolicyEnabled = CachingMethod(
                _isAuthenticationPolicyEnabled,
                id='PortalPreferences_isAuthenticationPolicyEnabled',
                cache_factory='erp5_content_short')
            tv[tv_key] = _isAuthenticationPolicyEnabled()
        return tv[tv_key]


InitializeClass(PreferenceTool)
Exemple #17
0
                if pass_if_exist:
                    pass

    security.declareProtected(Permissions.ManagePortal,
                              'getTrashBinObjectsList')

    def getTrashBinObjectsList(self, trashbin):
        """
      Return a list of trash objects for a given trash bin
    """
        def getChildObjects(obj):
            object_list = []
            if hasattr(aq_base(obj), 'objectValues'):
                childObjects = obj.objectValues()
            if hasattr(aq_base(obj), 'isHidden'):
                if not obj.isHidden:
                    object_list.append(obj)
            if len(childObjects) > 0:
                for o in childObjects:
                    object_list.extend(getChildObjects(o))
            else:
                object_list.append(obj)
            return object_list

        list = getChildObjects(trashbin)
        list.sort()
        return list


InitializeClass(TrashTool)
Exemple #18
0
    security.declareProtected(Permissions.ModifyPortalContent,
                              'notifyAfterUpdateRelatedContent')

    def notifyAfterUpdateRelatedContent(self, previous_category_url,
                                        new_category_url):
        """Hook called when a category is renamed.

      We must do some matrix range update in the event matrix range
      is defined by a category
    """
        LOG('XMLMatrix notifyAfterUpdateRelatedContent', 0,
            str(new_category_url))
        update_method = self.portal_categories.updateRelatedCategory
        for base_id in self.getMatrixList():
            cell_range = self.getCellRange(base_id=base_id)
            new_cell_range = []
            for range_item_list in cell_range:
                new_range_item_list = map(
                    lambda c: update_method(c, previous_category_url,
                                            new_category_url), range_item_list)
                new_cell_range.append(new_range_item_list)
            kwd = {'base_id': base_id}
            LOG('XMLMatrix notifyAfterUpdateRelatedContent matrix', 0,
                str(base_id))
            LOG('XMLMatrix notifyAfterUpdateRelatedContent _renameCellRange',
                0, str(new_cell_range))
            self._renameCellRange(*new_cell_range, **kwd)


InitializeClass(Matrix)
Exemple #19
0
        # have called it (= rule would have been excluded before, depending
        # on other criterions). Or there may be a bug.
        # We don't know why it failed so let Predicate.test() do the work.
        if rule.test(movement,
            tested_base_category_list=tested_base_category_list):
          rule_list.append(rule)

    return rule_list

  security.declarePrivate('updateSimulation')
  @UnrestrictedMethod
  def updateSimulation(self, message_list):
    expandable_dict = defaultdict(list)
    for m in message_list:
      expandable_dict[m.object].append(m)
    try:
      for expandable, message_list in expandable_dict.iteritems():
        kw = {}
        for m in message_list:
          kw.update(m.kw)
          m.result = None
        LOG("RuleTool", INFO, "Updating simulation for %s: %r"
                              % (expandable.getPath(), kw))
        expandable._updateSimulation(**kw)
    except Exception:
      exc_info = sys.exc_info()
      for m in message_list:
        m.raised(exc_info)

InitializeClass(RuleTool)
Exemple #20
0
    return value

  security.declareProtected(Permissions.ManagePortal, 'setAllCellTALES')
  def setAllCellTALES(self, new_cells) :
    """ set all cell values from a dict containing { name: TALES } """
    for cell_name, cell_TALES in new_cells.items() :
      self.setCellTALES(cell_name, cell_TALES)

  security.declareProtected(Permissions.View, 'getFormatMethodTALES')
  def getFormatMethodTALES(self):
    """ returns the TALES expression for the format method attribute """
    return self.__format_method__

  security.declareProtected(Permissions.ManagePortal, 'setFormatMethodTALES')
  def setFormatMethodTALES(self, TALES):
    """ sets TALES expression for the format method attribute """
    self.__format_method__ = str(TALES)

  security.declareProtected(Permissions.View, 'getPageRangeTALES')
  def getPageRangeTALES(self):
    """ returns the TALES expression for the page range attribute """
    return self.__page_range__

  security.declareProtected(Permissions.ManagePortal, 'setPageRangeTALES')
  def setPageRangeTALES(self, TALES):
    """ sets TALES expression for the page range attribute """
    self.__page_range__ = str(TALES)

InitializeClass(PDFForm)

Exemple #21
0
        try:
          for p in 'index.txt', 'crlnumber':
            p = os.path.join(self.certificate_authority_path, p)
            os.rename(p + '.old', p)
          for p in created:
            if os.path.exists(p):
              os.unlink(p)
        except:
          # do not raise during cleanup
          pass
        raise e[0], e[1], e[2]
    finally:
      self._unlockCertificateAuthority()

  def _getValidSerial(self, common_name):
    index = open(self.index).read().splitlines()
    valid_line_list = [q for q in index if q.startswith('V') and
      ('CN=%s/' % common_name in q)]
    if len(valid_line_list) != 1:
      raise ValueError('No certificate for %r' % common_name)
    return valid_line_list[0].split('\t')[3]

  security.declareProtected(Permissions.AccessContentsInformation,
    'revokeCertificate')
  def revokeCertificateByCommonName(self, common_name):
    self._checkCertificateAuthority()
    serial = self._getValidSerial(common_name)
    self.revokeCertificate(serial)

InitializeClass(CertificateAuthorityTool)
Exemple #22
0
from AccessControl import ClassSecurityInfo
from Products.ERP5Type.Globals import InitializeClass, DTMLFile
from Products.ERP5 import _dtmldir
from Products.ERP5Type import Permissions
from Products.ERP5Type.Tool.BaseTool import BaseTool
""" ERP5 portal_integrations tool """


class IntegrationTool(BaseTool):
    """
    The IntegrationTool is used to exchange with the differents external management systems.
  """

    id = 'portal_integrations'
    title = 'Integration Tool'
    meta_type = 'ERP5 Integration Tool'
    portal_type = 'Integration Tool'
    allowed_type = ()

    # Declarative Security
    security = ClassSecurityInfo()

    # ZMI Methods
    security.declareProtected(Permissions.ManagePortal, 'manage_overview')
    manage_overview = DTMLFile('explainIntegrationTool', _dtmldir)


InitializeClass(IntegrationTool)
Exemple #23
0
        raise NotImplementedError

    # Implementation of ISolver
    security.declarePrivate('solve')

    def solve(self, activate_kw=None):
        with super_user():
            self._solve(activate_kw=activate_kw)

    def getPortalTypeValue(self):
        return self.getPortalObject().portal_solvers._getOb(
            self.getPortalType())

    security.declareProtected(Permissions.AccessContentsInformation,
                              'searchDeliverySolverList')

    def searchDeliverySolverList(self, **kw):
        """
    this method returns a list of delivery solvers

    XXX here we cannot test delivery solver as a predicate, because
    predicate's context should be Solver Decision, not a target
    solver.
    """
        target_solver_type = self.getPortalTypeValue()
        solver_list = target_solver_type.getDeliverySolverValueList()
        return solver_list


InitializeClass(SolverMixin)
Exemple #24
0
                                                 inventory_date
                                                 )


    self.activate(after_method_id=('runInventoryMethod'),
                  after_tag="runInventoryMethod",
                  priority=5).InventoryModule_reindexMovementList(sql_catalog_id=destination_sql_catalog_id,
                                                                  final_activity_tag="InventoryModule_reindexMovementList"
                                                                  )

    if RESPONSE is not None:
      URL1 = REQUEST.get('URL1')
      RESPONSE.redirect(URL1 + '/portal_archives?portal_status_message=Archiving%20Started')


  def runInventoryMethod(self, archive_id, source_connection_id,
                         destination_sql_catalog_id, inventory_date):
    """
    Use a specific method to create inventory in order to use
    activity to execute it
    """
    archive = self._getOb(archive_id)
    inventory_method_id = archive.getInventoryMethodId()
    inventory_method = getattr(archive, inventory_method_id, None)
    if inventory_method is not None:
      inventory_method(source_connection_id, destination_sql_catalog_id,
                       inventory_date, tag='runInventoryMethod')


InitializeClass(ArchiveTool)
Exemple #25
0
                for property_group in delivery_builder.contentValues(
                        portal_type="Property group"):
                    if test_property in property_group.getTestedPropertyList():
                        application_value_level[
                            property_group.getCollectGroupOrder()] = None
        # etc. same

    security.declareProtected(Permissions.AccessContentsInformation,
                              'searchTargetSolverList')

    def searchTargetSolverList(self,
                               divergence_tester,
                               simulation_movement,
                               automatic_solver_only=False,
                               **kw):
        """
    this method returns a list of target solvers, as predicates against
    simulation movement.
    """
        solver_list = divergence_tester.getSolverValueList()
        if automatic_solver_only:
            return [x for x in solver_list if x.isAutomaticSolver() and \
                    x.test(simulation_movement, **kw)]
        else:
            return [
                x for x in solver_list if x.test(simulation_movement, **kw)
            ]


InitializeClass(SolverTool)
    """
        klass = self.getDocumentedObject().__class__
        return self._getPropertyHolder().getClassPropertyItemList(klass, **kw)

    security.declareProtected(Permissions.AccessContentsInformation,
                              'getClassPropertyIdList')

    def getClassPropertyIdList(self, **kw):
        """
    Return a list of tuple (id, method) for every class method
    """
        klass = self.getDocumentedObject().__class__
        return self._getPropertyHolder().getClassPropertyIdList(klass, **kw)

    security.declareProtected(Permissions.AccessContentsInformation,
                              'getGeneratedPropertyIdList')

    def getGeneratedPropertyIdList(self):
        """
    """

    security.declareProtected(Permissions.AccessContentsInformation,
                              'getGeneratedBaseCategoryIdList')

    def getGeneratedBaseCategoryIdList(self):
        """
    """


InitializeClass(PortalTypeInstanceDocumentationHelper)
Exemple #27
0
            if parent is not None:
                inner_obj = parent
                continue

            new = getattr(inner_obj, 'im_self', None)

            if new is not None:
                inner_obj = aq_inner(new)
                continue
            break

        return None


InitializeClass(ERP5User)


class ERP5UserFactory(BasePlugin):
    """ PAS plugin for creating users that understand local roles blocking based
  on type information's acquire_local_roles
  """
    meta_type = 'ERP5 User Factory'
    security = ClassSecurityInfo()

    def __init__(self, id, title=None):
        self._id = self.id = id
        self.title = title

    def createUser(self, user_id, name):
        """ See IUserFactoryPlugin
Exemple #28
0
    security.declareObjectProtected(Permissions.AccessContentsInformation)

    # Default Properties
    property_sheets = (PropertySheet.Base, PropertySheet.XMLObject,
                       PropertySheet.CategoryCore, PropertySheet.DublinCore,
                       PropertySheet.TargetSolver)

    def updateConfiguration(self, **kw):
        # This method is called once for each 'Solver Decision' of a
        # 'Solver Process' that maps into this solver for the same
        # Simulation Movement, so we need to take care not to lose
        # information by overwriting.
        configuration = self._getConfigurationPropertyDict()
        tested_property_list = configuration.get('tested_property_list')
        if tested_property_list is not None:
            tested_property_set = set(tested_property_list)
            tested_property_set.update(kw.get('tested_property_list', ()))
            kw['tested_property_list'] = list(tested_property_set)
        super(ConfigurablePropertySolverMixin, self).updateConfiguration(**kw)

    def getTestedPropertyList(self):
        configuration_dict = self.getConfigurationPropertyDict()
        tested_property_list = configuration_dict.get('tested_property_list')
        if tested_property_list is None:
            portal_type = self.getPortalObject().portal_types.getTypeInfo(self)
            tested_property_list = portal_type.getTestedPropertyList()
        return tested_property_list


InitializeClass(ConfigurablePropertySolverMixin)
Exemple #29
0
        amount._setQuantity(amount.getConvertedQuantity())
        amount._setQuantityUnit(amount.getResourceDefaultQuantityUnit())
        if rounding:
          # We hope here that rounding is sufficient at line level
          amount = getRoundingProxy(amount, context=self)
        amount._base = delivery_amount
        result.append(amount)
        # Contribute
        quantity *= property_dict.get('price', 1)
        try:
          quantity /= property_dict.get('efficiency', 1)
        except ZeroDivisionError:
          quantity *= float('inf')
        for base_contribution, variation_category_list in contribution_list:
          base_amount.contribute(base_contribution, variation_category_list,
                                 quantity)

    return result

  security.declareProtected(Permissions.AccessContentsInformation,
                            'getAggregatedAmountList')
  def getAggregatedAmountList(self, *args, **kw):
    """
    Implementation of a generic transformation algorith which is
    applicable to payroll, tax generation and BOMs. Return the
    list of amounts with aggregation.
    """
    return self.getGeneratedAmountList(*args, **kw).aggregate()

InitializeClass(AmountGeneratorMixin)
      # Note: special users are a bastard design in Zope: they are expected to
      # have a user name (aka, a login), but no id (aka, they do not exist as
      # users). This is likely done to prevent them from having any local role
      # (ownership or otherwise). In reality, they should have an id (they do
      # exist, and user ids are some internal detail where it is easy to avoid
      # such magic strings) and no login (because nobody should ever be able to
      # log in as a special user, and logins are exposed to users (duh !) and
      # hence magic values are impossible to avoid with ad-hoc code peppered
      # everywhere). To avoid such ad-hoc code, this plugin will find magic
      # users so code checking if a user login exists before allowing it to be
      # reused, preventing misleading logins from being misused.
      result.append({
        'id': special_user_name,
        'login': special_user_name,
        'pluginid': plugin_id,

        'path': None,
        'uid': None,
        'login_list': [
          {
            'reference': special_user_name,
            'path': None,
            'uid': None,
          }
        ]
      })
    return tuple(result)

classImplements(ERP5LoginUserManager, IAuthenticationPlugin, IUserEnumerationPlugin)
InitializeClass(ERP5LoginUserManager)