Ejemplo n.º 1
0
def HandleRemoved(property, event):
    if guaranteePluginExists():
        # A new fully configured plugin has been created, so we do not
        # need to do anything anymore.
        return

    luf=getLDAPPlugin()._getLDAPUserFolder()
    luf.manage_deleteLDAPSchemaItems([str(property.ldap_name)])
Ejemplo n.º 2
0
 def anon_cache(self):
     try:
         luf=getLDAPPlugin()._getLDAPUserFolder()
     except KeyError:
         return []
     users = luf.getUsers(authenticated=0)
     for user in users:
         user.cache_type = 'anonymous'
     return users
Ejemplo n.º 3
0
 def auth_cache(self):
     try:
         luf = getLDAPPlugin()._getLDAPUserFolder()
     except KeyError:
         return []
     users = luf.getUsers(authenticated=1)
     for user in users:
         user.cache_type = "authenticated"
     return users
Ejemplo n.º 4
0
def _get_userid_by_email(self, email):
    uid = ''
    luf=getLDAPPlugin()._getLDAPUserFolder()
    result = luf._lookupuserbyattr('mail', email)
    if len(result)>3:
        attrs = result[2]
        try:
            uid = attrs.get('uid')[0]
        except:
            pass
    return uid
Ejemplo n.º 5
0
def HandleRemoved(server, event):
    if guaranteePluginExists():
        # A new fully configured plugin has been created, so we do not
        # need to do anything anymore.
        return

    luf=getLDAPPlugin()._getLDAPUserFolder()
    servers=luf.getServers()

    for i in range(len(servers)):
        if servers[i]['host']==server.server and servers[i]['port']==server.port:
            luf.manage_deleteServers((i,))
            return
    def _extractCacheSettings(self):
        """Extract ldap cache settings"""
        fragment = self._doc.createDocumentFragment()
        node = self._doc.createElement('cache-settings')
        luf = getLDAPPlugin()._getLDAPUserFolder()

        for cache_value_name, cache_type in CACHE_MAPPING.items():
            child = self._doc.createElement('property')
            child.setAttribute('name', cache_value_name)
            value = luf.getCacheTimeout(cache_type)
            child.appendChild(self._doc.createTextNode(self._toString(value)))
            node.appendChild(child)
        fragment.appendChild(node)

        return fragment
Ejemplo n.º 7
0
 def handle_update_cache_timeouts(self, action, data):
     luf = getLDAPPlugin()._getLDAPUserFolder()
     for cache_type, cache_value_name in [
             ('authenticated', 'auth_cache_seconds'),
             ('anonymous', 'anon_cache_seconds'),
             ('negative', 'negative_cache_seconds'), ]:
         cache_value = self.request.form['form.' + cache_value_name]
         try:
             cache_value = int(cache_value)
         except ValueError:
             continue
         if cache_value != getattr(self, cache_value_name, None):
             luf.setCacheTimeout(cache_type=cache_type, timeout=cache_value)
             self.status = 'Cache timeout changed'
     return self.request.response.redirect(self.nextURL())
Ejemplo n.º 8
0
def HandleCreated(server, event):
    if guaranteePluginExists():
        # A new fully configured plugin has been created, so we do not
        # need to do anything anymore.
        return

    if not server.enabled:
        return

    luf=getLDAPPlugin()._getLDAPUserFolder()
    luf.manage_addServer(host=server.server,
                         port=server.port,
                         use_ssl=server.connection_type,
                         conn_timeout=server.connection_timeout,
                         op_timeout=server.operation_timeout)
 def _initCacheSettings(self, node):
     """Initialize cache settings"""
     luf = getLDAPPlugin()._getLDAPUserFolder()
     
     for child in node.childNodes:
         if child.nodeName != 'cache-settings':
             continue
         
         for gchild in child.childNodes:
             if gchild.nodeName != 'property':
                 continue
             
             value = self._getNodeText(gchild)
             attr_name = gchild.getAttribute('name')
             if attr_name in CACHE_MAPPING:
                 luf.setCacheTimeout(cache_type=CACHE_MAPPING[attr_name],
                                     timeout=int(value))
Ejemplo n.º 10
0
def HandleCreated(property, event):
    if guaranteePluginExists():
        # A new fully configured plugin has been created, so we do not
        # need to do anything anymore.
        return

    luf=getLDAPPlugin()._getLDAPUserFolder()
    # In case if the user is adding a property which is already present in the
    # backend since it is obligatory we try to delete it first.
    luf.manage_deleteLDAPSchemaItems([str(property.ldap_name)])

    luf.manage_addLDAPSchemaItem(
            ldap_name=str(property.ldap_name),
            friendly_name=property.description,
            public_name=str(property.plone_name),
            multivalued=property.multi_valued,
            binary=property.binary)
Ejemplo n.º 11
0
def HandleModified(config, event):
    if guaranteePluginExists():
        # A new fully configured plugin has been created, so we do not
        # need to do anything anymore.
        return

    luf=getLDAPPlugin()._getLDAPUserFolder()
    luf.manage_edit(
            title="Plone managed LDAP",
            login_attr=str(config.schema[config.login_attribute].ldap_name),
            uid_attr=str(config.schema[config.userid_attribute].ldap_name),
            rdn_attr=str(config.schema[config.rdn_attribute].ldap_name),
            users_base=config.user_base or "",
            users_scope=config.user_scope,
            groups_base=config.group_base or "",
            groups_scope=config.group_scope,
            binduid=str(config.bind_dn) or "",
            bindpwd=str(config.bind_password) or "",
            roles="Member",
            obj_classes=config.user_object_classes)
Ejemplo n.º 12
0
 def get_negative_cache_seconds(self):
     try:
         luf = getLDAPPlugin()._getLDAPUserFolder()
     except KeyError:
         return 600
     return luf.getCacheTimeout("negative")
Ejemplo n.º 13
0
 def set_anon_cache_seconds(self, value):
     luf = getLDAPPlugin()._getLDAPUserFolder()
     self._cache("anonymous").setTimeout(value)
Ejemplo n.º 14
0
 def get_anon_cache_seconds(self):
     try:
         luf = getLDAPPlugin()._getLDAPUserFolder()
     except KeyError:
         return 600
     return luf.getCacheTimeout("anonymous")
Ejemplo n.º 15
0
 def set_auth_cache_seconds(self, value):
     luf = getLDAPPlugin()._getLDAPUserFolder()
     self._cache("authenticated").setTimeout(value)
Ejemplo n.º 16
0
 def get_auth_cache_seconds(self):
     try:
         luf = getLDAPPlugin()._getLDAPUserFolder()
     except KeyError:
         return 600
     return luf.getCacheTimeout("authenticated")
Ejemplo n.º 17
0
 def set_auth_cache_seconds(self, value):
     luf = getLDAPPlugin()._getLDAPUserFolder()
     luf.setCacheTimeout(cache_type='authenticated', timeout=value)
Ejemplo n.º 18
0
    def extractData(self, root, pas, out):
        plug_id = str(root.getAttribute('id'))
        update = root.getAttribute('update') == 'True'

        settings = {}
        interfaces = []
        plugin_props = []
        for prop in root.getElementsByTagName('plugin_property'):
            p_type = prop.getAttribute('type')
            p_id = prop.getAttribute('id')
            value = prop.getAttribute('value')
            if p_type == 'int':
                value = int(value)
            if p_type == 'string':
                value = str(value)
            plugin_props.append({'id':p_id, 'type': p_type, 'value': value})

        for iface in root.getElementsByTagName('interface'):
            interfaces.append(iface.getAttribute('value'))

        caches = list()
        for node in root.getElementsByTagName('cache'):
            caches.append(node.getAttribute('value'))

        if len(caches) > 1:
            raise ValueError('You can not define multiple <cache> properties')

        cache = ''
        if len(caches):
            cache = caches[0]

        for prop in root.getElementsByTagName('property'):
            type = prop.getAttribute('type')
            values = []
            for v in prop.getElementsByTagName('item'):
                values.append(v.getAttribute('value'))
            id = prop.getAttribute('id')
            if type == 'list':
                value = values
            else:
                value = values[0]
            if type == 'int':
                value = int(value)
            if type == 'bool':
                value = (value.lower() != 'false' and 1 or 0)
            settings[id] = value
        schema = {}
        for schemanode in root.getElementsByTagName('schema'):
            for attr in schemanode.getElementsByTagName('attr'):
                c_id = attr.getAttribute('id')
                c_attr = {}
                for item in attr.getElementsByTagName('item'):
                    if item.getAttribute('value') != 'False':
                        c_attr[str(item.getAttribute('id'))] = str(item.getAttribute('value'))
                    else:
                        c_attr[str(item.getAttribute('id'))] = False
                schema[str(c_id)] = c_attr
        servers = []
        for server in root.getElementsByTagName('server'):
            c_server = {'update': (server.getAttribute('update') == 'True'),
                        'delete': (server.getAttribute('delete') == 'True')}
            for item in server.getElementsByTagName('item'):
                value = item.getAttribute('value')
                type = item.getAttribute('type')
                id = item.getAttribute('id')
                if type == 'int':
                    value = int(value)
                c_server[id] = value
            servers.append(c_server)

        # always update if it doesn't exist
        if plug_id not in pas.objectIds():
            update = True

        if update:
            # delete existing LDAP plug-in
            if plug_id in pas.objectIds():
                try:
                    plugin = getLDAPPlugin()
                    pas = getPAS()
                    pas.manage_delObjects([plugin.getId()])
                except KeyError:
                    # pass
                    """
                    There are two reasons to not pass here. First, if we pass
                    and go to recreate later and both plugins have the same it, it
                    will error out for the id already existing. Second, if they
                    don't have the same id but have the same settings, they will then
                    in practice (if its set up correct) have duplicate users, which
                    will subsequently break any group or role lookups which assert
                    on the duplicate users. I don't see any tests on this so if there
                    is an argument to leave this as a pass let me know.
                    """
                    logging.error("There is an ldap multi plugin in your "+
                        "system (%s) that is not managed "%plug_id +
                        "by this generic setup script. To have everything "+
                        "managed by GS, please delete and " +
                        "reinstall or set update=False in your ldap_plugin.xml"+
                        " root.")
                    logging.error("Installing LDAP Plugin with GS failed")
                    return


            # base configuration
            config = getUtility(ILDAPConfiguration)
            config.login_attribute = settings['_login_attr']
            config.userid_attribute = settings['_uid_attr']
            config.rdn_attribute = settings['_rdnattr']
            config.user_base = settings['users_base']
            config.user_scope = settings['users_scope']
            config.group_base = settings['groups_base']
            config.group_scope = settings['groups_scope']
            config.bind_dn = settings['_binduid']
            config.bind_password = settings['_bindpwd']
            config.user_object_classes = ','.join(settings['_user_objclasses'])
            config.password_encryption = settings['_pwd_encryption']
            config.default_user_roles = ','.join(settings['_roles'])
            config.read_only = settings['read_only']
            config.activated_plugins = interfaces
            config.cache = cache

            # servers
            config.servers = LDAPServerStorage()
            for server in servers:
                obj = LDAPServer(server=server['host'],
                                 connection_type=(server['protocol'] == 'ldaps'),
                                 connection_timeout=server['conn_timeout'],
                                 operation_timeout=server['op_timeout'],
                                 enabled=True)
                config.servers.addItem(obj)

            # schema
            config.schema = LDAPSchema()
            for property in schema.itervalues():
                obj = LDAPProperty(ldap_name=property.get('ldap_name', ''),
                                   plone_name=property.get('public_name', ''),
                                   description=property.get('friendly_name', ''),
                                   multi_valued=property.get('multivalued', False),
                                   binary=property.get('binary', False))
                config.schema.addItem(obj)
            # recreate new LDAP plug-in
            createLDAPPlugin(plug_id)
            configureLDAPServers()
            configureLDAPSchema()
Ejemplo n.º 19
0
 def set_anon_cache_seconds(self, value):
     luf = getLDAPPlugin()._getLDAPUserFolder()
     luf.setCacheTimeout(cache_type='anonymous', timeout=value)
Ejemplo n.º 20
0
 def get_negative_cache_seconds(self):
     try:
         luf = getLDAPPlugin()._getLDAPUserFolder()
     except KeyError:
         return 600
     return luf.getCacheTimeout('negative')
Ejemplo n.º 21
0
 def get_auth_cache_seconds(self):
     try:
         luf = getLDAPPlugin()._getLDAPUserFolder()
     except KeyError:
         return 600
     return luf.getCacheTimeout('authenticated')
Ejemplo n.º 22
0
 def set_negative_cache_seconds(self, value):
     luf = getLDAPPlugin()._getLDAPUserFolder()
     luf.setCacheTimeout(cache_type='negative', timeout=value)
Ejemplo n.º 23
0
 def set_negative_cache_seconds(self, value):
     luf = getLDAPPlugin()._getLDAPUserFolder()
     luf.setCacheTimeout(cache_type='negative', timeout=value)
Ejemplo n.º 24
0
 def set_anon_cache_seconds(self, value):
     luf = getLDAPPlugin()._getLDAPUserFolder()
     luf.setCacheTimeout(cache_type='anonymous', timeout=value)
Ejemplo n.º 25
0
 def set_negative_cache_seconds(self, value):
     luf = getLDAPPlugin()._getLDAPUserFolder()
     self._cache("negative").setTimeout(value)
Ejemplo n.º 26
0
 def set_auth_cache_seconds(self, value):
     luf = getLDAPPlugin()._getLDAPUserFolder()
     luf.setCacheTimeout(cache_type='authenticated', timeout=value)
Ejemplo n.º 27
0
 def get_anon_cache_seconds(self):
     try:
         luf = getLDAPPlugin()._getLDAPUserFolder()
     except KeyError:
         return 600
     return luf.getCacheTimeout('anonymous')
Ejemplo n.º 28
0
    def extractData(self, root, pas, out):
        plug_id = str(root.getAttribute("id"))
        update = root.getAttribute("update") == "True"

        settings = {}
        interfaces = []
        plugin_props = []
        for prop in root.getElementsByTagName("plugin_property"):
            p_type = prop.getAttribute("type")
            p_id = prop.getAttribute("id")
            value = prop.getAttribute("value")
            if p_type == "int":
                value = int(value)
            if p_type == "string":
                value = str(value)
            plugin_props.append({"id": p_id, "type": p_type, "value": value})

        for iface in root.getElementsByTagName("interface"):
            interfaces.append(iface.getAttribute("value"))

        caches = list()
        for node in root.getElementsByTagName("cache"):
            caches.append(node.getAttribute("value"))

        if len(caches) > 1:
            raise ValueError("You can not define multiple <cache> properties")

        cache = ""
        if len(caches):
            cache = caches[0]

        for prop in root.getElementsByTagName("property"):
            type = prop.getAttribute("type")
            values = []
            for v in prop.getElementsByTagName("item"):
                values.append(v.getAttribute("value"))
            id = prop.getAttribute("id")
            if type == "list":
                # values are unicode strings
                # _user_objclasses and _roles need to be strings
                if id in ["_user_objclasses", "_roles"]:
                    value = [item.encode("utf8") for item in values]
                else:
                    value = values
            else:
                value = values[0]
            if type == "int":
                value = int(value)
            if type == "bool":
                value = value.lower() != "false" and 1 or 0
            settings[id] = value
        schema = {}
        for schemanode in root.getElementsByTagName("schema"):
            for attr in schemanode.getElementsByTagName("attr"):
                c_id = attr.getAttribute("id")
                c_attr = {}
                for item in attr.getElementsByTagName("item"):
                    if item.getAttribute("value") != "False":
                        c_attr[str(item.getAttribute("id"))] = str(item.getAttribute("value"))
                    else:
                        c_attr[str(item.getAttribute("id"))] = False
                schema[str(c_id)] = c_attr
        servers = []
        for server in root.getElementsByTagName("server"):
            c_server = {
                "update": (server.getAttribute("update") == "True"),
                "delete": (server.getAttribute("delete") == "True"),
            }
            for item in server.getElementsByTagName("item"):
                value = item.getAttribute("value")
                type = item.getAttribute("type")
                id = item.getAttribute("id")
                if type == "int":
                    value = int(value)
                c_server[id] = value
            servers.append(c_server)

        # always update if it doesn't exist
        if plug_id not in pas.objectIds():
            update = True

        if update:
            # delete existing LDAP plug-in
            if plug_id in pas.objectIds():
                try:
                    plugin = getLDAPPlugin()
                    pas = getPAS()
                    pas.manage_delObjects([plugin.getId()])
                except KeyError:
                    # pass
                    """
                    There are two reasons to not pass here. First, if we pass
                    and go to recreate later and both plugins have the same it, it
                    will error out for the id already existing. Second, if they
                    don't have the same id but have the same settings, they will then
                    in practice (if its set up correct) have duplicate users, which
                    will subsequently break any group or role lookups which assert
                    on the duplicate users. I don't see any tests on this so if there
                    is an argument to leave this as a pass let me know.
                    """
                    logging.error(
                        "There is an ldap multi plugin in your "
                        + "system (%s) that is not managed " % plug_id
                        + "by this generic setup script. To have everything "
                        + "managed by GS, please delete and "
                        + "reinstall or set update=False in your ldap_plugin.xml"
                        + " root."
                    )
                    logging.error("Installing LDAP Plugin with GS failed")
                    return

            # base configuration
            config = getUtility(ILDAPConfiguration)
            config.login_attribute = settings["_login_attr"]
            config.userid_attribute = settings["_uid_attr"]
            config.rdn_attribute = settings["_rdnattr"]
            config.user_base = settings["users_base"]
            config.user_scope = settings["users_scope"]
            config.group_base = settings["groups_base"]
            config.group_scope = settings["groups_scope"]
            config.bind_dn = settings["_binduid"]
            config.bind_password = settings["_bindpwd"]
            config.user_object_classes = ",".join(settings["_user_objclasses"])
            config.password_encryption = settings["_pwd_encryption"]
            config.default_user_roles = ",".join(settings["_roles"])
            config.read_only = settings["read_only"]
            config.activated_plugins = interfaces
            config.cache = cache

            # servers
            config.servers = LDAPServerStorage()
            for server in servers:
                obj = LDAPServer(
                    server=server["host"],
                    connection_type=(server["protocol"] == "ldaps"),
                    connection_timeout=server["conn_timeout"],
                    operation_timeout=server["op_timeout"],
                    enabled=True,
                )
                config.servers.addItem(obj)

            # schema
            config.schema = LDAPSchema()
            for property in schema.itervalues():
                obj = LDAPProperty(
                    ldap_name=property.get("ldap_name", ""),
                    plone_name=property.get("public_name", ""),
                    description=property.get("friendly_name", ""),
                    multi_valued=property.get("multivalued", False),
                    binary=property.get("binary", False),
                )
                config.schema.addItem(obj)
            # recreate new LDAP plug-in
            createLDAPPlugin(plug_id)
            configureLDAPServers()
            configureLDAPSchema()
Ejemplo n.º 29
0
 def handle_cache_purge(self, action, data):
     luf = getLDAPPlugin()._getLDAPUserFolder()
     luf.manage_reinit()
     self.status = "User caches cleared"
     return self.request.response.redirect(self.nextURL())
Ejemplo n.º 30
0
    def _get_users_to_sync(self):
        """Perform a custom LDAP query to limit the users
        who should be updated.

        Looks for users that have changed since the last sync,
        according to the LDAP_CHANGED_ATTRIBUTE

        (Requires plone.app.ldap)
        """
        last_sync = get_last_sync(self.context)
        if not last_sync:
            # First sync is always a full sync
            return super(LDAPChangedUsersPropertySync,
                         self)._get_users_to_sync()

        logger.info('Looking for LDAP users changed since {0}'.format(
            last_sync,
        ))

        try:
            ldap_plugin = getLDAPPlugin()
        except KeyError:
            logger.error('No LDAP plugin found!')
            return []

        ldap_folder = ldap_plugin['acl_users']

        # Convert to AD/LDAP date string
        datestring = last_sync.strftime('%Y%m%d%H%M%S.0Z')
        changed_filter = '({0}>={1})'.format(
            LDAP_CHANGED_ATTRIBUTE,
            datestring,
        )
        # Combine date check with the default LDAP filters
        search_str = ldap_folder._getUserFilterString(
            filters=(changed_filter,)
        )

        # Perform a search using the LDAPUserFolder
        login_attr = ldap_folder._login_attr
        results = ldap_folder._delegate.search(
            base=ldap_folder.users_base,
            scope=ldap_folder.users_scope,
            filter=search_str,
            attrs=(login_attr, ),
        )
        if results['exception']:
            logger.debug('Error in ldap query (%s)' % results['exception'])
            return []
        if results['size'] == 0:
            logger.info('No users to update')
            return []

        # Translate to membrane profiles
        userids = [x[login_attr][0] for x in results['results']]
        mtool = api.portal.get_tool('membrane_tool')
        users = mtool.searchResults(exact_getUserId=userids)
        logger.info('Found {0} users to update from LDAP'.format(
            len(users)
        ))
        return [user.getObject() for user in users]
Ejemplo n.º 31
0
 def handle_cache_purge(self, action, data):
     luf = getLDAPPlugin()._getLDAPUserFolder()
     luf.manage_reinit()
     self.status = 'User caches cleared'
     return self.request.response.redirect(self.nextURL())