def find_resolver_spec_for_config_identifier(realms_dict, config_identifier): """ Iterates through a realms dictionary, extracts the resolver specification and returns it, when its config identifier matches the provided config_identifier argument :param realms_dict: A realms dictionary :param config_identifier: The config identifier to search for :return Resolver specification (or None if no match occured) """ # FIXME: Exactly as the old algorithm this method # assumes, that the config_identifier is globally # unique. This is not necessarily the case for realm_dict in realms_dict.values(): resolver_specs = realm_dict['useridresolver'] for resolver_spec in resolver_specs: __, current_config_identifier = parse_resolver_spec(resolver_spec) if current_config_identifier.lower() == config_identifier.lower(): return resolver_spec return None
def active_users_per_realm(self, realm=None): """ get the number of users which are assigned to an active token in total or per realm and resolver :param realm: name of realm :return: dict with keys: resolvernames values: number of active token users """ realminfo = context.get('Config').getRealms().get(realm) resolver_specs = realminfo.get('useridresolver', '') realmdict = {} for resolver_spec in resolver_specs: __, config_identifier = parse_resolver_spec(resolver_spec) act_users_per_resolver = Session.query(Token.LinOtpUserid, Token.LinOtpIdResolver, Token.LinOtpIdResClass, Token.LinOtpIsactive)\ .join(TokenRealm)\ .join(Realm)\ .filter(and_( Token.LinOtpIsactive == True, Token.LinOtpIdResClass == resolver_spec, Realm.name == realm ))\ .group_by(Token.LinOtpUserid, Token.LinOtpIdResolver, Token.LinOtpIsactive, Token.LinOtpIdResClass) realmdict[config_identifier] = act_users_per_resolver.count() return realmdict
def getSearchFields(user): searchFields = {} log.debug("[getSearchFields] entering function getSearchFields") for resolver_spec in getResolvers(User): """ """ _cls_identifier, config_identifier = parse_resolver_spec(resolver_spec) if len(user.resolver_config_identifier) > 0: lower_config_id = user.resolver_config_identifier.lower() if config_identifier.lower() != lower_config_id: continue # try to load the UserIdResolver Class try: y = getResolverObject(resolver_spec) sf = y.getSearchFields() searchFields[resolver_spec] = sf except Exception as exx: log.warning('[getSearchField][ resolver spec %s: %r ]', resolver_spec, exx) continue return searchFields
def getSearchFields(user): searchFields = {} log.debug("[getSearchFields] entering function getSearchFields") for resolver_spec in getResolvers(User): """ """ cls_identifier, config_identifier = parse_resolver_spec(resolver_spec) if len(user.resolver_config_identifier) > 0: lower_config_id = user.resolver_config_identifier.lower() if config_identifier.lower() != lower_config_id: continue # try to load the UserIdResolver Class try: y = getResolverObject(resolver_spec) sf = y.getSearchFields() searchFields[resolver_spec] = sf except Exception as e: log.warning('[getSearchField][ resolver spec %s: %r ]' % (resolver_spec, e)) continue return searchFields
def get_uid_resolver(self, resolvers=None): """ generator to get the uid and resolver info of the user :param resolvers: provide the resolver, where to check for the user :return: the tuple of uid and resolver """ uid = None resolvers_list = [] # if the resolver is not provided, we make a lookup for all resolvers # in the user realm if not resolvers: if self.realm: realms = getRealms() if self.realm.lower() in realms: resolvers_list = realms.get(self.realm.lower(), {}).\ get('useridresolver', []) else: resolvers_list = [] for search_resolver in resolvers: fq_resolver = User.get_fq_resolver(search_resolver) if fq_resolver: resolvers_list.append(fq_resolver) if not resolvers_list: return for resolver_spec in resolvers_list: try: y = getResolverObject(resolver_spec) uid = y.getUserId(self.login) if not uid: uid = None continue # we add the gathered resolver info to our self for later usage # 1. to the resolver uid list self.resolverUid[resolver_spec] = uid # 2. the resolver spec list resId = y.getResolverId() resCId = resolver_spec __, conf = parse_resolver_spec(resolver_spec) self.resolverConf[resolver_spec] = (resId, resCId, conf) # remember that we identified the user self.exist = True yield uid, resolver_spec except Exception as exx: log.exception("Error while accessing resolver %r", exx)
def getResolversOfUser(user): ''' getResolversOfUser returns the list of the Resolvers of a user in a given realm. A user can be be in more than one resolver if the login name is the same and if the user has the same id. The usecase behind this constrain is that an user for example could be ldap wise in a group which could be addressed by two queries. :param user: userobject with user.login, user.realm :returns: array of resolvers, the user was found in ''' login = user.login realm = user.realm if not realm: realm = getDefaultRealm() realm = realm.lower() # calling the worker which stores resolver in the cache resolvers = get_resolvers_of_user(login, realm) # -- ------------------------------------------------------------------ -- # below we adjust the legacy stuff and put the resolver info into the user # -- ------------------------------------------------------------------ -- for resolver_spec in resolvers: # this is redundant but cached login, uid, _user_info = lookup_user_in_resolver( login, None, resolver_spec) if not uid: continue try: # we require the resId y = getResolverObject(resolver_spec) resId = y.getResolverId() resCId = resolver_spec except Exception as exx: log.exception("Failed to establish resolver %r: %r", resolver_spec, exx) continue __, config_identifier = parse_resolver_spec(resolver_spec) user.addResolverUId(resolver_spec, uid, config_identifier, resId, resCId) return resolvers
def getUserListIterators(param, search_user): """ return a list of iterators for all userid resolvers :param param: request params (dict), which might be realm or resolver conf :param search_user: restrict the resolvers to those of the search_user """ user_iters = [] searchDict = {} log.debug("Entering function getUserListIterator") searchDict.update(param) if 'realm' in searchDict: del searchDict['realm'] if 'resConf' in searchDict: del searchDict['resConf'] log.debug("searchDict %r", searchDict) resolverrrs = getResolvers(search_user) for resolver_spec in resolverrrs: cls_identifier, config_identifier = parse_resolver_spec(resolver_spec) if len(search_user.resolver_config_identifier) > 0: lower_config_id = search_user.resolver_config_identifier.lower() if config_identifier.lower() != lower_config_id: continue # try to load the UserIdResolver Class try: log.debug('Check for resolver: %r', resolver_spec) y = getResolverObject(resolver_spec) log.debug("With this search dictionary: %r ", searchDict) if hasattr(y, 'getUserListIterator'): uit = y.getUserListIterator(searchDict, limit_size=False) else: uit = iter(y.getUserList(searchDict)) user_iters.append((uit, resolver_spec)) except KeyError as exx: log.exception('[ resolver class %r:%r ]', cls_identifier, exx) raise exx except Exception as exx: log.exception('[ resolver class %r:%r ]', cls_identifier, exx) continue return user_iters
def getUserListIterators(param, search_user): """ return a list of iterators for all userid resolvers :param param: request params (dict), which might be realm or resolver conf :param search_user: restrict the resolvers to those of the search_user """ user_iters = [] searchDict = {} log.debug("Entering function getUserListIterator") searchDict.update(param) if 'realm' in searchDict: del searchDict['realm'] if 'resConf' in searchDict: del searchDict['resConf'] log.debug("searchDict %r" % searchDict) resolverrrs = getResolvers(search_user) for resolver_spec in resolverrrs: cls_identifier, config_identifier = parse_resolver_spec(resolver_spec) if len(search_user.resolver_config_identifier) > 0: lower_config_id = search_user.resolver_config_identifier.lower() if config_identifier.lower() != lower_config_id: continue # try to load the UserIdResolver Class try: log.debug('Check for resolver: %r' % resolver_spec) y = getResolverObject(resolver_spec) log.debug("With this search dictionary: %r " % searchDict) if hasattr(y, 'getUserListIterator'): uit = y.getUserListIterator(searchDict, limit_size=False) else: uit = iter(y.getUserList(searchDict)) user_iters.append((uit, resolver_spec)) except KeyError as exx: log.exception('[ resolver class %r:%r ]' % (cls_identifier, exx)) raise exx except Exception as exx: log.exception('[ resolver class %r:%r ]' % (cls_identifier, exx)) continue return user_iters
def resolverinfo(self, realm): """ get the resolvers for one realm and the number of users per resolver :param realm: the realm to query :return: dict with resolvernames as keys and number of users as value """ realminfo = context.get('Config').getRealms().get(realm) resolver_specs = realminfo.get('useridresolver', '') realmdict = {} for resolver_spec in resolver_specs: __, config_identifier = parse_resolver_spec(resolver_spec) realmdict[config_identifier] = 0 user = getUserFromParam({'realm': realm}, optionalOrRequired=True) users_iters = iterate_users(getUserListIterators({'realm': realm}, user)) for next_one in users_iters: for key in realmdict: if key in next_one: realmdict[key] += 1 return realmdict
def resolverinfo(self, realm): """ get the resolvers for one realm and the number of users per resolver :param realm: the realm to query :return: dict with resolvernames as keys and number of users as value """ realminfo = context.get('Config').getRealms().get(realm) resolver_specs = realminfo.get('useridresolver', '') realmdict = {} for resolver_spec in resolver_specs: __, config_identifier = parse_resolver_spec(resolver_spec) realmdict[config_identifier] = 0 user = getUserFromParam({'realm': realm}) users = getUserList({'realm': realm, 'username': '******'}, user) for next_one in users: resolver = next_one['useridresolver'].split('.')[-1] if resolver in realmdict: realmdict[resolver] += 1 return realmdict
def resolverinfo(self, realm): """ get the resolvers for one realm and the number of users per resolver :param realm: the realm to query :return: dict with resolvernames as keys and number of users as value """ realminfo = context.get("Config").getRealms().get(realm) resolver_specs = realminfo.get("useridresolver", "") realmdict = {} for resolver_spec in resolver_specs: __, config_identifier = parse_resolver_spec(resolver_spec) realmdict[config_identifier] = 0 user = getUserFromParam({"realm": realm}) users = getUserList({"realm": realm, "username": "******"}, user) for next_one in users: resolver = next_one["useridresolver"].split(".")[-1] if resolver in realmdict: realmdict[resolver] += 1 return realmdict
def getResolversOfUser(user, use_default_realm=True, allRealms=None, defaultRealm=None): ''' This returns the list of the Resolvers of a user in a given realm. Usually this should only return one resolver input: user.login, user.realm returns: array of resolvers, the user was found in ''' login = user.login realm = user.realm if not defaultRealm: defaultRealm = getDefaultRealm() Resolvers = user.getResolvers() if len(Resolvers) > 0: return Resolvers if not login: return Resolvers if realm is None or realm == "": if use_default_realm: realm = defaultRealm if not allRealms: allRealms = getRealms() realms = allRealms if user.resolver_config_identifier != "": resolver_spec = find_resolver_spec_for_config_identifier(realms, user.resolver_config_identifier) if resolver_spec is not None: Resolvers.append(resolver_spec) else: Realm_resolvers = getResolvers(User("", realm, "")) log.debug("[getResolversOfUser] check if user %r is in resolver %r" % (login, Realm_resolvers)) # Search for user in each resolver in the realm_ for resolver_spec in Realm_resolvers: log.debug("[getResolversOfUser] checking in %r" % resolver_spec) y = getResolverObject(resolver_spec) if y is None: log.error('[getResolversOfUser] [resolver with spec %r ' 'not found!]' % (resolver_spec)) try: log.debug("[getResolversOfUser] checking in module %r" % y) uid = y.getUserId(login) log.debug("[getResolversOfUser] type of uid: %s" % type(uid)) log.debug("[getResolversOfUser] type of resolver_spec: %s" % type(resolver_spec)) log.debug("[getResolversOfUser] type of login: %s" % type(login)) if uid not in ["", None]: log.info("[getResolversOfUser] user %r found in resolver %r" % (login, resolver_spec)) log.info("[getResolversOfUser] userid resolved to %r " % uid) # Unicode Madness: # This will break as soon as the unicode "uid" is put into a tuple # v = (login, realm_resolver, uid) # log.info("[getResolversOfUser] %s %s %s" % v) resId = y.getResolverId(); resCId = resolver_spec Resolvers.append(resolver_spec) __, config_identifier = parse_resolver_spec(resolver_spec) user.addResolverUId(resolver_spec, uid, config_identifier, resId, resCId) else: log.debug("[getResolversOfUser] user %r not found" " in resolver %r" % (login, resolver_spec)) except Exception as e: log.exception('[getResolversOfUser] error searching user in ' 'resolver with spec %r:%r' % (resolver_spec, e)) log.debug("[getResolversOfUser] Resolvers: %r" % Resolvers) log.debug("[getResolversOfUser] Found the user %r in %r" % (login, Resolvers)) return Resolvers
def getResolversOfUser(user, use_default_realm=True, allRealms=None, defaultRealm=None): ''' This returns the list of the Resolvers of a user in a given realm. Usually this should only return one resolver input: user.login, user.realm returns: array of resolvers, the user was found in ''' login = user.login realm = user.realm if not defaultRealm: defaultRealm = getDefaultRealm() Resolvers = user.getResolvers() if len(Resolvers) > 0: return Resolvers if not login: return Resolvers if realm is None or realm == "": if use_default_realm: realm = defaultRealm if not allRealms: allRealms = getRealms() realms = allRealms if user.resolver_config_identifier != "": resolver_spec = find_resolver_spec_for_config_identifier(realms, user.resolver_config_identifier) if resolver_spec is not None: Resolvers.append(resolver_spec) else: Realm_resolvers = getResolvers(User("", realm, "")) log.debug("[getResolversOfUser] check if user %r is in resolver %r", login, Realm_resolvers) # Search for user in each resolver in the realm_ for resolver_spec in Realm_resolvers: log.debug("[getResolversOfUser] checking in %r", resolver_spec) y = getResolverObject(resolver_spec) if y is None: log.error('[getResolversOfUser] [resolver with spec %r ' 'not found!]', resolver_spec) try: log.debug("[getResolversOfUser] checking in module %r", y) uid = y.getUserId(login) log.debug("[getResolversOfUser] type of uid: %s", type(uid)) log.debug("[getResolversOfUser] type of resolver_spec: %s", type(resolver_spec)) log.debug("[getResolversOfUser] type of login: %s", type(login)) if uid not in ["", None]: log.info("[getResolversOfUser] user %r found in resolver " "%r", login, resolver_spec) log.info("[getResolversOfUser] userid resolved to %r ", uid) # Unicode Madness: # This will break as soon as the unicode "uid" is put into # a tuple # v = (login, realm_resolver, uid) # log.info("[getResolversOfUser] %s %s %s" % v) resId = y.getResolverId() resCId = resolver_spec Resolvers.append(resolver_spec) __, config_identifier = parse_resolver_spec(resolver_spec) user.addResolverUId(resolver_spec, uid, config_identifier, resId, resCId) else: log.debug("[getResolversOfUser] user %r not found" " in resolver %r", login, resolver_spec) except Exception as exx: log.exception('[getResolversOfUser] error searching user in ' 'resolver with spec %r:%r', resolver_spec, exx) log.debug("[getResolversOfUser] Resolvers: %r", Resolvers) log.debug("[getResolversOfUser] Found the user %r in %r", login, Resolvers) return Resolvers
def getUserId(user, resolvers=None): """ getUserId (userObject) return (uid,resId,resIdC) """ uid = '' loginUser = user.login if not resolvers: resolvers = getResolversOfUser(user) for resolver_spec in resolvers: resId = "" resIdC = "" uid = user.getResolverUId(resolver_spec) if uid != '': (resId, resIdC, _conf) = user.getResolverConf(resolver_spec) break cls_identifier, config_identifier = parse_resolver_spec(resolver_spec) if user.resolver_config_identifier: lower_config_id = user.resolver_config_identifier.lower() if config_identifier.lower() != lower_config_id: continue # try to load the UserIdResolver Class try: log.debug('[getUserId] Getting resolver class: [%s]', cls_identifier) y = getResolverObject(resolver_spec) log.debug("[getUserId] Getting UserID for user %r", loginUser) uid = y.getUserId(loginUser) log.debug("[getUserId] Got UserId for user %r: %r", loginUser, uid) log.debug("[getUserId] Retrieving ResolverID...") resId = y.getResolverId() resIdC = resolver_spec log.debug("[getUserId] Got ResolverID: %r, Loginuser: %r, " "Uid: %r ]", resId, loginUser, uid) if uid != "": break except Exception as exx: log.exception("[getUserId] resolver class identifier %s: %r ]", cls_identifier, exx) continue if (uid == ''): log.warning("[getUserId] No uid found for the user >%r< in realm %r" % (loginUser, user.realm)) raise UserError("getUserId failed: no user >%s< found!" % unicode(loginUser), id=1205) log.debug("[getUserId] we are done!") return (unicode(uid), unicode(resId), unicode(resIdC))
def getUserList(param, search_user): users = [] searchDict = {} log.debug("[getUserList] entering function getUserList") # we have to recreate a new searchdict without the realm key # as delete does not work for key in param: lval = param[key] if key == "realm": continue if key == "resConf": continue searchDict[key] = lval log.debug("[getUserList] Parameter key:%r=%r" % (key, lval)) resolverrrs = getResolvers(search_user) for resolver_spec in resolverrrs: cls_identifier, config_identifier = parse_resolver_spec(resolver_spec) if len(search_user.resolver_config_identifier) > 0: lower_config_id = search_user.resolver_config_identifier.lower() if config_identifier.lower() != lower_config_id: continue # try to load the UserIdResolver Class try: log.debug("[getUserList] Check for resolver: %r" % resolver_spec) y = getResolverObject(resolver_spec) log.debug("[getUserList] with this search dictionary: %r " % searchDict) if hasattr(y, 'getUserListIterator'): try: ulist_gen = y.getUserListIterator(searchDict) while True: ulist = ulist_gen.next() log.debug("[getUserList] setting the resolver <%r> " "for each user" % resolver_spec) for u in ulist: u["useridresolver"] = resolver_spec log.debug("[getUserList] Found this userlist: %r" % ulist) users.extend(ulist) except StopIteration as exx: # we are done: all users are fetched or # page size limit reached pass else: ulist = y.getUserList(searchDict) for u in ulist: u["useridresolver"] = resolver_spec log.debug("[getUserList] Found this userlist: %r" % ulist) users.extend(ulist) except KeyError as exx: log.exception('[getUserList][ resolver class identifier %s:%r ]' % (cls_identifier, exx)) raise exx except Exception as exx: log.exception('[getUserList][ resolver class identifier %s:%r ]' % (cls_identifier, exx)) continue return users
def getUserList(param, search_user): users = [] searchDict = {} log.debug("[getUserList] entering function getUserList") # we have to recreate a new searchdict without the realm key # as delete does not work for key in param: lval = param[key] if key == "realm": continue if key == "resConf": continue searchDict[key] = lval log.debug("[getUserList] Parameter key:%r=%r", key, lval) resolverrrs = getResolvers(search_user) for resolver_spec in resolverrrs: cls_identifier, config_identifier = parse_resolver_spec(resolver_spec) if len(search_user.resolver_config_identifier) > 0: lower_config_id = search_user.resolver_config_identifier.lower() if config_identifier.lower() != lower_config_id: continue # try to load the UserIdResolver Class try: log.debug("[getUserList] Check for resolver: %r", resolver_spec) y = getResolverObject(resolver_spec) log.debug("[getUserList] with this search dictionary: %r ", searchDict) try: ulist_gen = y.getUserListIterator(searchDict) while True: ulist = ulist_gen.next() log.debug("[getUserList] setting the resolver <%r> " "for each user", resolver_spec) for u in ulist: u["useridresolver"] = resolver_spec log.debug("[getUserList] Found this userlist: %r", ulist) users.extend(ulist) except StopIteration as exx: # we are done: all users are fetched or # page size limit reached pass except Exception as exc: log.info("Getting userlist using iterator not possible. " "Falling back to fetching userlist without iterator. " "Reason: %r", exc) ulist = y.getUserList(searchDict) for u in ulist: u["useridresolver"] = resolver_spec log.debug("[getUserList] Found this userlist: %r", ulist) users.extend(ulist) except KeyError as exx: log.exception('[getUserList][ resolver class identifier %s:%r ]', cls_identifier, exx) raise exx except Exception as exx: log.exception('[getUserList][ resolver class identifier %s:%r ]', cls_identifier, exx) continue return users
def getUserId(user, resolvers=None): """ getUserId (userObject) return (uid,resId,resIdC) """ uid = '' loginUser = u'' loginUser = user.login; if not resolvers: resolvers = getResolversOfUser(user) for resolver_spec in resolvers: resId = "" resIdC = "" conf = "" uid = user.getResolverUId(resolver_spec) if uid != '': (resId, resIdC, conf) = user.getResolverConf(resolver_spec) break cls_identifier, config_identifier = parse_resolver_spec(resolver_spec) if user.resolver_config_identifier: lower_config_id = user.resolver_config_identifier.lower() if config_identifier.lower() != lower_config_id: continue # try to load the UserIdResolver Class try: log.debug('[getUserId] Getting resolver class: [%s]' % cls_identifier) y = getResolverObject(resolver_spec) log.debug("[getUserId] Getting UserID for user %r" % loginUser) uid = y.getUserId(loginUser) log.debug("[getUserId] Got UserId for user %r: %r" % (loginUser, uid)) log.debug("[getUserId] Retrieving ResolverID...") resId = y.getResolverId() resIdC = resolver_spec log.debug("[getUserId] Got ResolverID: %r, Loginuser: %r, " "Uid: %r ]" % (resId, loginUser, uid)) if uid != "": break; except Exception as e: log.exception("[getUserId] resolver class identifier %s: %r ]" % (cls_identifier, e)) continue if (uid == ''): log.warning("[getUserId] No uid found for the user >%r< in realm %r" % (loginUser, user.realm)) raise UserError(u"getUserId failed: no user >%s< found!" % unicode(loginUser), id=1205) log.debug("[getUserId] we are done!") return (unicode(uid), unicode(resId), unicode(resIdC))