Ejemplo n.º 1
0
 def updLocalRoles(self, path=None, row=None, roles=None):
     """ Update the specified roles.
     """
     if roles is None:
         roles = []
     if path and path in self.localRoles and row is not None:
         try:
             self.localRoles[path][row]['_roles'] = roles
         except (IndexError, TypeError):
             logger.warning("updLocalRoles error updating row %s from %s"
                            % (str(row), str(path)), exc_info=True)
 def updLocalRoles(self, path=None, row=None, roles=None):
     """ Update the specified roles.
     """
     if roles is None:
         roles = []
     if path and path in self.localRoles and row is not None:
         try:
             self.localRoles[path][row]['_roles'] = roles
         except (IndexError, TypeError):
             logger.warning("updLocalRoles error updating row %s from %s"
                            % (str(row), str(path)), exc_info=True)
Ejemplo n.º 3
0
    def authenticateCredentials(self, credentials):
        """See class's docstring and IAuthenticationPlugin."""

        mappings = credentials.pop('_getMappings', [])
        defaultRoles = credentials.pop('_defaultRoles', [])
        userId = credentials.get(usernameKey, None)

        pas = self._getPAS()

        if not pas:
            return None
        elif userId is None:
            return None  # Pass control to the next IAuthenticationPlugin.

        user = pas.getUserById(userId)

        if user is None:
            # Make a user with id `userId`, and assign him at least the Member
            # role, since user doesn't exist.

            # Make sure we actually have user adders and role assigners. It
            # would be ugly to succeed at making the user but be unable to
            # assign him the role.
            userAdders = self.plugins.listPlugins(IUserAdderPlugin)
            if not userAdders:
                raise NotImplementedError("I wanted to make a new user, but"
                                          " there are no PAS plugins active"
                                          " that can make users.")
            roleAssigners = self.plugins.listPlugins(IRoleAssignerPlugin)
            if not roleAssigners:
                raise NotImplementedError("I wanted to make a new user and give"
                                          " him the Member role, but there are"
                                          " no PAS plugins active that assign"
                                          " roles to users.")

            # Add the user to the first IUserAdderPlugin that works:
            user = None
            for _, curAdder in userAdders:
                if curAdder.doAddUser(userId, self._generatePassword()):
                    # Assign a dummy password. It'll never be used;.
                    user = self._getPAS().getUser(userId)
                    try:
                        membershipTool = getToolByName(self,
                                                       'portal_membership')
                        if not membershipTool.getHomeFolder(userId):
                            membershipTool.createMemberArea(userId)
                    except (ConflictError, KeyboardInterrupt):
                        raise
                    except Exception:
                        pass
                    self._updateUserProperties(user, credentials)
                    break

            # Build a list of roles to assign to the user, starting with the
            # default roles (usually at least Member)
            roles = {}
            for role in defaultRoles:
                roles[role] = True
            groups = []
            if credentials.has_key('filters'):
                for role in mappings:
                    # for each source given in authz_mappings
                    for ii in role['values'].iterkeys():
                        assignRole = False
                        # if the authz_mappings pattern is not set, assume ok
                        if not role['values'][ii]:
                            assignRole = True
                        # if the source exists in the environment
                        elif credentials['filters'].has_key(ii):
                            try:
                                # compile the pattern from authz_mappings
                                oRe = re.compile(role['values'][ii])
                                # and compare the pattern to the environment
                                # value
                                match = oRe.search(credentials['filters'][ii])
                            except (ConflictError, KeyboardInterrupt):
                                raise
                            except Exception:
                                match = False
                            if match:
                                assignRole = True
                        if not assignRole:
                            break
                    # either there was no pattern or the pattern matched
                    # for every mapping, so add specified roles or groups.
                    if assignRole:
                        for ii in role['roles'].iterkeys():
                            if role['roles'][ii] == 'on':
                                roles[ii] = True
                        for ii in role['groupid']:
                            groups.append(ii)

            # Map the given roles to the user using all available
            # IRoleAssignerPlugins (just like doAddUser does for some reason):
            for curAssignerId, curAssigner in roleAssigners:
                for role in roles.iterkeys():
                    try:
                        curAssigner.doAssignRoleToPrincipal(user.getId(), role)
                    except _SWALLOWABLE_PLUGIN_EXCEPTIONS:
                        logger.warning('RoleAssigner %s error' % curAssignerId,
                                       exc_info=True)

            source_groups = getToolByName(self, 'source_groups')
            for ii in groups:
                source_groups.addPrincipalToGroup(user.getId(), ii)
        else:
            config = self.getConfig()
            if config.get(autoUpdateUserPropertiesKey, 0):
                self._updateUserProperties(user, credentials)

        #Allow other plugins to handle credentials; eg session or cookie
        pas.updateCredentials(self.REQUEST,
                              self.REQUEST.RESPONSE, userId, "")
        return userId, userId
Ejemplo n.º 4
0
    def authenticateCredentials(self, credentials):
        """See class's docstring and IAuthenticationPlugin."""

        mappings = credentials.pop('_getMappings', [])
        defaultRoles = credentials.pop('_defaultRoles', [])
        userId = credentials.get(usernameKey, None)

        pas = self._getPAS()

        if not pas:  # pragma: no cover
            return None
        elif userId is None:
            return None  # Pass control to the next IAuthenticationPlugin.

        user = pas.getUserById(userId)

        if user is None:
            with safe_write(self.REQUEST):
                # Make a user with id `userId`, and assign him at least the Member
                # role, since user doesn't exist.

                # Make sure we actually have user adders and role assigners. It
                # would be ugly to succeed at making the user but be unable to
                # assign him the role.
                userAdders = self.plugins.listPlugins(IUserAdderPlugin)
                if not userAdders:
                    raise NotImplementedError(
                        "I wanted to make a new user, but"
                        " there are no PAS plugins active"
                        " that can make users.")
                roleAssigners = self.plugins.listPlugins(IRoleAssignerPlugin)
                if not roleAssigners:
                    raise NotImplementedError(
                        "I wanted to make a new user and give"
                        " him the Member role, but there are"
                        " no PAS plugins active that assign"
                        " roles to users.")

                # Add the user to the first IUserAdderPlugin that works:
                user = None
                for _, curAdder in userAdders:
                    if curAdder.doAddUser(userId, self._generatePassword()):
                        # Assign a dummy password. It'll never be used;.
                        user = self._getPAS().getUser(userId)
                        try:
                            membershipTool = getToolByName(
                                self, 'portal_membership')
                            if not membershipTool.getHomeFolder(userId):
                                membershipTool.createMemberArea(userId)
                        except (ConflictError, KeyboardInterrupt):
                            raise
                        except Exception:
                            pass
                        self._updateUserProperties(user, credentials)
                        break

                # Build a list of roles to assign to the user, starting with the
                # default roles (usually at least Member)
                roles = {}
                for role in defaultRoles:
                    roles[role] = True
                groups = []
                if credentials.has_key('filters'):
                    for role in mappings:
                        # for each source given in authz_mappings
                        for ii in role['values'].iterkeys():
                            assignRole = False
                            # if the authz_mappings pattern is not set, assume ok
                            if not role['values'][ii]:
                                assignRole = True
                            # if the source exists in the environment
                            elif credentials['filters'].has_key(ii):
                                try:
                                    # compile the pattern from authz_mappings
                                    oRe = re.compile(role['values'][ii])
                                    # and compare the pattern to the environment
                                    # value
                                    match = oRe.search(
                                        credentials['filters'][ii])
                                except (ConflictError, KeyboardInterrupt):
                                    raise
                                except Exception:
                                    match = False
                                if match:
                                    assignRole = True
                            if not assignRole:
                                break
                        # either there was no pattern or the pattern matched
                        # for every mapping, so add specified roles or groups.
                        if assignRole:
                            for ii in role['roles'].iterkeys():
                                if role['roles'][ii] == 'on':
                                    roles[ii] = True
                            for ii in role['groupid']:
                                groups.append(ii)

                # Map the given roles to the user using all available
                # IRoleAssignerPlugins (just like doAddUser does for some reason):
                for curAssignerId, curAssigner in roleAssigners:
                    for role in roles.iterkeys():
                        try:
                            curAssigner.doAssignRoleToPrincipal(
                                user.getId(), role)
                        except _SWALLOWABLE_PLUGIN_EXCEPTIONS:
                            logger.warning('RoleAssigner %s error' %
                                           curAssignerId,
                                           exc_info=True)

                source_groups = getToolByName(self, 'source_groups')
                for ii in groups:
                    source_groups.addPrincipalToGroup(user.getId(), ii)
        else:
            config = self.getConfig()
            if config.get(autoUpdateUserPropertiesKey, 0):
                if time.time() > user.getProperty(
                        LAST_UPDATE_USER_PROPERTY_KEY) + config.get(
                            autoUpdateUserPropertiesIntervalKey, 0):
                    with safe_write(self.REQUEST):
                        self._updateUserProperties(user, credentials)

        #Allow other plugins to handle credentials; eg session or cookie
        pas.updateCredentials(self.REQUEST, self.REQUEST.RESPONSE, userId, "")
        return userId, userId