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)])
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
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
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
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
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())
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))
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)
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)
def get_negative_cache_seconds(self): try: luf = getLDAPPlugin()._getLDAPUserFolder() except KeyError: return 600 return luf.getCacheTimeout("negative")
def set_anon_cache_seconds(self, value): luf = getLDAPPlugin()._getLDAPUserFolder() self._cache("anonymous").setTimeout(value)
def get_anon_cache_seconds(self): try: luf = getLDAPPlugin()._getLDAPUserFolder() except KeyError: return 600 return luf.getCacheTimeout("anonymous")
def set_auth_cache_seconds(self, value): luf = getLDAPPlugin()._getLDAPUserFolder() self._cache("authenticated").setTimeout(value)
def get_auth_cache_seconds(self): try: luf = getLDAPPlugin()._getLDAPUserFolder() except KeyError: return 600 return luf.getCacheTimeout("authenticated")
def set_auth_cache_seconds(self, value): luf = getLDAPPlugin()._getLDAPUserFolder() luf.setCacheTimeout(cache_type='authenticated', timeout=value)
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()
def set_anon_cache_seconds(self, value): luf = getLDAPPlugin()._getLDAPUserFolder() luf.setCacheTimeout(cache_type='anonymous', timeout=value)
def get_negative_cache_seconds(self): try: luf = getLDAPPlugin()._getLDAPUserFolder() except KeyError: return 600 return luf.getCacheTimeout('negative')
def get_auth_cache_seconds(self): try: luf = getLDAPPlugin()._getLDAPUserFolder() except KeyError: return 600 return luf.getCacheTimeout('authenticated')
def set_negative_cache_seconds(self, value): luf = getLDAPPlugin()._getLDAPUserFolder() luf.setCacheTimeout(cache_type='negative', timeout=value)
def set_negative_cache_seconds(self, value): luf = getLDAPPlugin()._getLDAPUserFolder() self._cache("negative").setTimeout(value)
def get_anon_cache_seconds(self): try: luf = getLDAPPlugin()._getLDAPUserFolder() except KeyError: return 600 return luf.getCacheTimeout('anonymous')
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()
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())
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]
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())