Пример #1
0
    def getUserInfo(self, resolver=None):
        userInfo = {}

        lookup_resolvers = None
        if resolver:
            lookup_resolvers = [resolver]

        userid, resolverC = self.get_uid_resolver(lookup_resolvers)

        if not userid:
            return {}

        try:
            (package, module, _class, _conf) = splitResolver(resolverC)
            module = package + "." + module

            y = getResolverObject(resolverC)
            log.debug("[getUserInfo] Getting user info for userid "
                      ">%r< in resolver" % userid)
            userInfo = y.getUserInfo(userid)
            self.info[resolverC] = userInfo

        except Exception as e:
            log.exception("[getUserInfo][ module %r notfound! :%r ]"
                          % (module, e))

        return userInfo
Пример #2
0
def getSearchFields(User):

    searchFields = {}

    log.debug("[getSearchFields] entering function getSearchFields")

    for reso in getResolvers(User):
        """  """
        (_package, module, class_, conf) = splitResolver(reso)

        if len(User.conf) > 0:
            if conf.lower() != User.conf.lower():
                continue

        ## try to load the UserIdResolver Class
        try:
            y = getResolverObject(reso)
            sf = y.getSearchFields()
            searchFields[reso] = sf

        except Exception as e:
            log.warning("[getSearchField][ module %r: %r ]" % (module, e))
            continue

    return searchFields
Пример #3
0
def check_user_password(username, realm, password):
    '''
    This is a helper function to check the username and password against
    a userstore.

    return

      success    --- This is the username of the authenticated user. If unsuccessful,
                      returns None
    '''
    success = None
    try:
        log.info("[check_user_password] User %r from realm %r tries to "
                 "authenticate to selfservice" % (username, realm))
        if type(username) != unicode:
            username = username.decode(ENCODING)
        u = User(username, realm, "")
        res = getResolversOfUser(u)
        # Now we know, the resolvers of this user and we can verify the password
        if (len(res) == 1):
            (uid, resolver, resolverC) = getUserId(u)
            log.info("[check_user_password] the user resolves to %r" % uid)
            log.info("[check_user_password] The username is found within the "
                     "resolver %r" % resolver)
            # Authenticate user
            try:
                (package, module, class_, conf) = splitResolver(resolverC)
                module = package + "." + module
                y = getResolverObject(resolverC)
            except Exception as e:
                log.error("[check_user_password] [ module %r notfound! :%r ]"
                          % (module, e))
            try:
                if  y.checkPass(uid, password):
                    log.debug("[check_user_password] Successfully "
                              "authenticated user %r." % username)
                    # try:
                    #identity = self.add_metadata( environ, identity )
                    success = username + '@' + realm
                else:
                    log.info("[check_user_password] user %r failed "
                             "to authenticate." % username)
            except Exception as e:
                log.error("[check_user_password] Error checking password "
                          "within module %r:%r" % (module, e))
                log.error("[check_user_password] %s" % traceback.format_exc())

        elif (len(res) == 0):
            log.error("[check_user_password] The username %r exists in NO "
                      "resolver within the realm %r." % (username, realm))
        else:
            log.error("[check_user_password] The username %r exists in more "
                      "than one resolver within the realm %r" % (username, realm))
            log.error(res)
    except UserError as e:
        log.error("[check_user_password] Error while trying to verify "
                  "the username: %r" % e.description)

    return success
Пример #4
0
def getUserList(param, 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(User)

    for reso in resolverrrs:
        (package, module, class_, conf) = splitResolver(reso)
        module = package + "." + module

        if len(User.conf) > 0:
            if conf.lower() != User.conf.lower():
                continue

        ## try to load the UserIdResolver Class
        try:
            log.debug("[getUserList] Check for resolver class: %r" % reso)
            y = getResolverObject(reso)
            log.debug("[getUserList] with this search dictionary: %r " %
                      searchDict)
            ulist = y.getUserList(searchDict)
            log.debug("[getUserList] setting the resolver <%r> for each user" %
                      reso)
            for u in ulist:
                u["useridresolver"] = reso

            log.debug("[getUserList] Found this userlist: %r" % ulist)
            users.extend(ulist)

        except KeyError as exx:
            log.error("[getUserList][ module %r:%r ]" % (module, exx))
            log.error("[getUserList] %s" % traceback.format_exc())
            raise exx

        except Exception as exx:
            log.error("[getUserList][ module %r:%r ]" % (module, exx))
            log.error("[getUserList] %s" % traceback.format_exc())
            continue

    return users
Пример #5
0
def getUserId(user):
    """
    getUserId (userObject)

    return (uid,resId,resIdC)
    """

    uid = ""
    loginUser = u""
    loginUser = user.login

    resolvers = getResolversOfUser(user)
    for reso in resolvers:
        resId = ""
        resIdC = ""
        conf = ""
        uid = user.getResolverUId(reso)
        if uid != "":
            (resId, resIdC, conf) = user.getResolverConf(reso)
            break

        (package, module, class_, conf) = splitResolver(reso)

        if len(user.conf) > 0:
            if conf.lower() != user.conf.lower():
                continue

        # try to load the UserIdResolver Class
        try:
            module = package + "." + module
            log.debug("[getUserId] Getting resolver class: [%r] [%r]" % (module, class_))
            y = getResolverObject(reso)
            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 = reso
            log.debug("[getUserId] Got ResolverID: %r, Loginuser: %r, " "Uid: %r ]" % (resId, loginUser, uid))

            if uid != "":
                break

        except Exception as e:
            log.exception("[getUserId] module %r: %r ]" % (module, 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))
Пример #6
0
def get_authenticated_user(username, realm, password):
    '''
    check the username and password against a userstore.

    :param username: the user login name
    :param realm: the realm, where the user belongs to
    :param password: the to be checked userstore password

    :return: None or user@realm of the authenticated user.
    '''
    auth_user = None
    try:
        log.info("User %r from realm %r tries to authenticate to selfservice"
                 % (username, realm))
        if type(username) != unicode:
            username = username.decode(ENCODING)
        u = User(username, realm, "")
        res = getResolversOfUser(u)
        # Now we know, the resolvers of this user and we can verify the password
        if (len(res) == 1):
            (uid, resolver, resolverC) = getUserId(u)
            log.info("the user resolves to %r" % uid)
            log.info("The username is found within the resolver %r" % resolver)
            # Authenticate user
            try:
                (package, module, class_, conf) = splitResolver(resolverC)
                module = package + "." + module
                y = getResolverObject(resolverC)
            except Exception as e:
                log.error("[ module %r notfound! :%r ]" % (module, e))
            try:
                if  y.checkPass(uid, password):
                    log.debug("Successfully authenticated user %r." % username)
                    # try:
                    #identity = self.add_metadata( environ, identity )
                    auth_user = username + '@' + realm
                else:
                    log.info("user %r failed to authenticate." % username)
            except Exception as e:
                log.error("Error checking password within module %r:%r" 
                          % (module, e))
                log.error("%s" % traceback.format_exc())

        elif (len(res) == 0):
            log.error("The username %r exists in NO resolver within the "
                      "realm %r." % (username, realm))
        else:
            log.error("The username %r exists in more than one resolver "
                      "within the realm %r" % (username, realm))
            log.error(res)
    except UserError as exx:
        log.error("Error while trying to verify the username: %r" % exx)

    return auth_user
Пример #7
0
def get_authenticated_user(username, realm, password):
    '''
    check the username and password against a userstore.

    :param username: the user login name
    :param realm: the realm, where the user belongs to
    :param password: the to be checked userstore password

    :return: None or user@realm of the authenticated user.
    '''
    auth_user = None
    try:
        log.info("User %r from realm %r tries to authenticate to selfservice" %
                 (username, realm))
        if type(username) != unicode:
            username = username.decode(ENCODING)
        u = User(username, realm, "")
        res = getResolversOfUser(u)
        # Now we know, the resolvers of this user and we can verify the password
        if (len(res) == 1):
            (uid, resolver, resolverC) = getUserId(u)
            log.info("the user resolves to %r" % uid)
            log.info("The username is found within the resolver %r" % resolver)
            # Authenticate user
            try:
                (package, module, class_, conf) = splitResolver(resolverC)
                module = package + "." + module
                y = getResolverObject(resolverC)
            except Exception as e:
                log.error("[ module %r notfound! :%r ]" % (module, e))
            try:
                if y.checkPass(uid, password):
                    log.debug("Successfully authenticated user %r." % username)
                    # try:
                    # identity = self.add_metadata( environ, identity )
                    auth_user = username + '@' + realm
                else:
                    log.info("user %r failed to authenticate." % username)
            except Exception as e:
                log.error("Error checking password within module %r:%r" %
                          (module, e))
                log.error("%s" % traceback.format_exc())

        elif (len(res) == 0):
            log.error("The username %r exists in NO resolver within the "
                      "realm %r." % (username, realm))
        else:
            log.error("The username %r exists in more than one resolver "
                      "within the realm %r" % (username, realm))
            log.error(res)
    except UserError as exx:
        log.error("Error while trying to verify the username: %r" % exx)

    return auth_user
Пример #8
0
def getUserList(param, 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(User)

    for reso in resolverrrs:
        (package, module, class_, conf) = splitResolver(reso)
        module = package + "." + module

        if len(User.conf) > 0:
            if conf.lower() != User.conf.lower():
                continue

        ## try to load the UserIdResolver Class
        try:
            log.debug("[getUserList] Check for resolver class: %r" % reso)
            y = getResolverObject(reso)
            log.debug("[getUserList] with this search dictionary: %r " % searchDict)
            ulist = y.getUserList(searchDict)
            log.debug("[getUserList] setting the resolver <%r> for each user" % reso)
            for u in ulist:
                u["useridresolver"] = reso

            log.debug("[getUserList] Found this userlist: %r" % ulist)
            users.extend (ulist)

        except KeyError as exx:
            log.error("[getUserList][ module %r:%r ]" % (module, exx))
            log.error("[getUserList] %s" % traceback.format_exc())
            raise exx

        except Exception as exx:
            log.error("[getUserList][ module %r:%r ]" % (module, exx))
            log.error("[getUserList] %s" % traceback.format_exc())
            continue

    return users
Пример #9
0
def getConf(Realms, Conf):
    """
    extract the configguration part from the resolver definition
    """
    for k in Realms:
        r = Realms[k]
        resIds = r["useridresolver"]
        for reso in resIds:
            (_package, _module, _class_, conf) = splitResolver(reso)
            if conf.lower() == Conf.lower():
                return reso
    return ""
Пример #10
0
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 reso in resolverrrs:
        (package, module, _class, conf) = splitResolver(reso)
        module = package + "." + module

        if len(search_user.conf) > 0:
            if conf.lower() != search_user.conf.lower():
                continue

        # try to load the UserIdResolver Class
        try:
            log.debug("Check for resolver class: %r" % reso)
            y = getResolverObject(reso)
            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, reso))

        except KeyError as exx:
            log.error("[ module %r:%r ]" % (module, exx))
            log.error("%s" % traceback.format_exc())
            raise exx

        except Exception as exx:
            log.error("[ module %r:%r ]" % (module, exx))
            log.error("%s" % traceback.format_exc())
            continue

    return user_iters
Пример #11
0
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 reso in resolverrrs:
        (package, module, _class, conf) = splitResolver(reso)
        module = package + "." + module

        if len(search_user.conf) > 0:
            if conf.lower() != search_user.conf.lower():
                continue

        # try to load the UserIdResolver Class
        try:
            log.debug("Check for resolver class: %r" % reso)
            y = getResolverObject(reso)
            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, reso))

        except KeyError as exx:
            log.error("[ module %r:%r ]" % (module, exx))
            log.error("%s" % traceback.format_exc())
            raise exx

        except Exception as exx:
            log.error("[ module %r:%r ]" % (module, exx))
            log.error("%s" % traceback.format_exc())
            continue

    return user_iters
Пример #12
0
def getUserInfo(userid, resolver, resolverC):
    log.debug("[getUserInfo] uid:%r resolver:%r class:%r" % (userid, resolver, resolverC))
    # [PasswdIdResolver] [IdResolver]
    userInfo = {}
    module = ""

    if not (userid):
        return userInfo

    try:
        (package, module, _class, _conf) = splitResolver(resolverC)
        module = package + "." + module

        y = getResolverObject(resolverC)
        log.debug("[getUserInfo] Getting user info for userid " ">%r< in resolver" % userid)
        userInfo = y.getUserInfo(userid)

    except Exception as e:
        log.error("[getUserInfo][ module %r notfound! :%r ]" % (module, e))

    return userInfo
Пример #13
0
def getUserInfo(userid, resolver, resolverC):
    log.debug("[getUserInfo] uid:%r resolver:%r class:%r" %
              (userid, resolver, resolverC))
                ## [PasswdIdResolver] [IdResolver]
    userInfo = {}
    module = ""

    if not(userid):
        return userInfo

    try:
        (package, module, class_, conf) = splitResolver(resolverC)
        module = package + "." + module

        y = getResolverObject(resolverC)
        log.debug("[getUserInfo] Getting user info for userid "
                  ">%r< in resolver" % userid)
        userInfo = y.getUserInfo(userid)

    except Exception as e:
        log.error("[getUserInfo][ module %r notfound! :%r ]" % (module, e))

    return userInfo
Пример #14
0
    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)
        resolvers = realminfo.get('useridresolver', '')
        realmdict = {}

        for resolver in resolvers:
            package, module, classs, conf = splitResolver(resolver)
            realmdict[conf] = 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
Пример #15
0
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 reso in resolverrrs:
        (package, module, _class, conf) = splitResolver(reso)
        module = package + "." + module

        if len(search_user.conf) > 0:
            if conf.lower() != search_user.conf.lower():
                continue

        # try to load the UserIdResolver Class
        try:

            log.debug("[getUserList] Check for resolver class: %r" % reso)
            y = getResolverObject(reso)
            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" % reso)
                        for u in ulist:
                            u["useridresolver"] = reso
                        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"] = reso
                log.debug("[getUserList] Found this userlist: %r" % ulist)
                users.extend(ulist)

        except KeyError as exx:
            log.exception("[getUserList][ module %r:%r ]" % (module, exx))
            raise exx

        except Exception as exx:
            log.exception("[getUserList][ module %r:%r ]" % (module, exx))
            continue

    return users
Пример #16
0
def getUserId(user):
    """
    getUserId (userObject)

    return (uid,resId,resIdC)
    """

    uid = ''
    loginUser = u''
    loginUser = user.login;

    resolvers = '';
    realms = getRealms();

    # Get the first resolver they're present in, because UID is independent of realm.
    for key, v in realms.items():
        resolvers = getResolversOfUser(User(user.login, v['realmname'], ""))
        if (resolvers):
            break;

    for reso in resolvers:
        resId = ""
        resIdC = ""
        conf = ""
        uid = user.getResolverUId(reso)
        if uid != '':
            (resId, resIdC, conf) = user.getResolverConf(reso)
            break

        (package, module, class_, conf) = splitResolver(reso)

        if len(user.conf) > 0:
            if conf.lower() != user.conf.lower():
                continue

        ## try to load the UserIdResolver Class
        try:
            module = package + "." + module
            log.debug("[getUserId] Getting resolver class: [%r] [%r]"
                       % (module, class_))
            y = getResolverObject(reso)
            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 = reso
            log.debug("[getUserId] Got ResolverID: %r, Loginuser: %r, "
                      "Uid: %r ]" % (resId, loginUser, uid))

            if uid != "":
                break;

        except Exception as e:
            log.error("[getUserId] module %r: %r ]" % (module, 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))
Пример #17
0
def getResolversOfUser(user):
    '''
    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

    Resolvers = user.getResolvers()

    if len(Resolvers) > 0:
        return Resolvers

    if realm is None or realm == "":
        realm = getDefaultRealm()

    #if realm is None or realm=="" or login is None or login == "":
    #    log.error("[getResolversOfUser] You need to specify the name ( %s) and the realm (%s) of a user with conf %s" % (login, realm, user.conf))

    realms = getRealms();

    if user.conf != "":
        reso = getConf(realms, user.conf)
        if len(reso) > 0:
            Resolvers.append(reso)
    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 realm_resolver in Realm_resolvers:
            log.debug("[getResolversOfUser] checking in %r" % realm_resolver)

            (package, module, class_, conf) = splitResolver(realm_resolver)
            module = package + "." + module

            y = getResolverObject(realm_resolver)
            if y is None:
                log.error("[getResolversOfUser] [ module %r not found!]"
                                                                    % (module))

            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 realm_resolver: %s" % type(realm_resolver))
                log.debug("[getResolversOfUser] type of login: %s" % type(login))
                if uid not in ["", None]:
                    log.debug("[getResolversOfUser] user %r found in resolver %r" % (login, realm_resolver))
                    log.debug("[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 = realm_resolver
                    Resolvers.append(realm_resolver)
                    user.addResolverUId(realm_resolver, uid, conf, resId, resCId)
                else:
                    log.debug("[getResolversOfUser] user %r not found"
                              " in resolver %r" % (login, realm_resolver))
            except Exception as e:
                log.error("[getResolversOfUser] error searching user in"
                          " module %r:%r" % (module, e))
                log.error("[getResolversOfUser] %s" % traceback.format_exc())

            log.debug("[getResolversOfUser] Resolvers: %r" % Resolvers)

    log.debug("[getResolversOfUser] Found the user %r in %r" % (login, Resolvers))
    return Resolvers
Пример #18
0
def get_authenticated_user(username, realm, password=None,
                           realm_box=False, authenticate=True,
                           options=None):
    '''
    check the username and password against a userstore.

    remark: the method is called in the context of repoze.who
            during authentication and during auto_enrollToken/auto_assignToken

    :param username: the user login name
    :param realm: the realm, where the user belongs to
    :param password: the to be checked userstore password
    :param realm_box: take the information, if realmbox is displayed
    :parm authenticate: for the selftest, we skip the authentication

    :return: None or authenticated user object
    '''

    log.info("User %r from realm %r tries to authenticate to selfservice"
             % (username, realm))

    if type(username) != unicode:
        username = username.decode(ENCODING)

    # ease the handling of options
    if not options:
        options = {}

    users = []
    uid = None
    resolver = None
    resolverC = None

    # if we have an realmbox, we take the user as it is
    # - the realm is always given
    # - appended realms result in error
    if realm_box:
        user = User(username, realm, "")
        users.append(user)

    # else if no realm box is given
    #   and realm is not empty:
    #    - create the user from the values (as we are in auto_assign, etc)
    #   and the realm is empty! (s. login.mako
    #    - the user either appends his realm
    #    - or will get the realm appended
    #
    else:
        if realm:
            user = User(username, realm, "")
            users.append(user)
        else:
            def_realm = options.get('defaultRealm', getDefaultRealm())
            if def_realm:
                user = User(username, def_realm, "")
                users.append(user)
            if '@' in username:
                u_name, u_realm = username.rsplit('@', 1)
                user = User(u_name, u_realm, "")
                users.append(user)

    identified_users = []
    for user in users:
        username = user.login
        realm = user.realm
        res = getResolversOfUser(user, use_default_realm=False)
        if not res:
            log.info("The username %r exists in NO resolver within the "
                      "realm %r.", username, realm)
            continue

        # fill in the set of resolvers
        getUserId(user)
        for resolverClass, uid in user.resolverUid.items():
            identified_users.append((user, uid, resolverClass, resolverClass))
            log.info("the user resolves to %r", uid)
            log.info("The username is found within the resolver %r", resolver)

    if not identified_users:
        log.info("The username %s could not be found." % username)
        return None

    if not authenticate:
        (user, uid, resolver, resolverC) = identified_users[0]
        return user

    # Authenticate user
    auth_user = None
    for identified_user in identified_users:
        (user, uid, resolver, resolverC) = identified_user
        try:
            (package, module, _class_, _conf) = splitResolver(resolverC)
            module = package + "." + module
            y = getResolverObject(resolverC)

            if y.checkPass(uid, password):
                # we stop with the first successful authenticated user
                log.debug("Successfully authenticated user %r.", username)
                auth_user = user
                break
            else:
                log.info("user %r failed to authenticate.", username)

        except UserError as exx:
            log.info("failed to verify the username: %s@%s: %r",
                     user.login, user.realm, exx)

    if not auth_user:
        log.error("Error while trying to verify the username: %s", username)

    return auth_user
Пример #19
0
def get_authenticated_user(username,
                           realm,
                           password=None,
                           realm_box=False,
                           authenticate=True,
                           options=None):
    '''
    check the username and password against a userstore.

    remark: the method is called in the context of repoze.who
            during authentication and during auto_enrollToken/auto_assignToken

    :param username: the user login name
    :param realm: the realm, where the user belongs to
    :param password: the to be checked userstore password
    :param realm_box: take the information, if realmbox is displayed
    :parm authenticate: for the selftest, we skip the authentication

    :return: None or authenticated user object
    '''

    log.info("User %r from realm %r tries to authenticate to selfservice" %
             (username, realm))

    if type(username) != unicode:
        username = username.decode(ENCODING)

    # ease the handling of options
    if not options:
        options = {}

    users = []
    uid = None
    resolver = None
    resolverC = None

    # if we have an realmbox, we take the user as it is
    # - the realm is always given
    # - appended realms result in error
    if realm_box:
        user = User(username, realm, "")
        users.append(user)

    # else if no realm box is given
    #   and realm is not empty:
    #    - create the user from the values (as we are in auto_assign, etc)
    #   and the realm is empty! (s. login.mako
    #    - the user either appends his realm
    #    - or will get the realm appended
    #
    else:
        if realm:
            user = User(username, realm, "")
            users.append(user)
        else:
            def_realm = options.get('defaultRealm', getDefaultRealm())
            if def_realm:
                user = User(username, def_realm, "")
                users.append(user)
            if '@' in username:
                u_name, u_realm = username.rsplit('@', 1)
                user = User(u_name, u_realm, "")
                users.append(user)

    identified_users = []
    for user in users:
        username = user.login
        realm = user.realm
        res = getResolversOfUser(user, use_default_realm=False)
        if (len(res) != 1):
            if (len(res) == 0):
                log.info("The username %r exists in NO resolver within the "
                         "realm %r." % (username, realm))
            else:
                log.info("The username %r exists in more than one resolver "
                         "within the realm %r" % (username, realm))
            continue

        # we got one resolver, so lets check if user exists
        (uid, resolver, resolverC) = getUserId(user)
        identified_users.append((user, uid, resolver, resolverC))
        log.info("the user resolves to %r" % uid)
        log.info("The username is found within the resolver %r" % resolver)

    ide_user = len(identified_users)
    if ide_user != 1:
        if ide_user > 1:
            log.info("The username %s could not be identified uniquely" %
                     username)
        if ide_user == 0:
            log.info("The username %s could not be found." % username)
        return None

    (user, uid, resolver, resolverC) = identified_users[0]
    if not authenticate:
        return user

    # Authenticate user
    auth_user = None
    try:
        (package, module, class_, conf) = splitResolver(resolverC)
        module = package + "." + module
        y = getResolverObject(resolverC)

        if y.checkPass(uid, password):
            log.debug("Successfully authenticated user %r." % username)
            auth_user = user
        else:
            log.info("user %r failed to authenticate." % username)

    except UserError as exx:
        log.info("failed to verify the username: %s@%s" %
                 (user.login, user.realm))

    if not auth_user:
        log.error("Error while trying to verify the username: %s" % username)

    return auth_user
Пример #20
0
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 reso in resolverrrs:
        (package, module, _class, conf) = splitResolver(reso)
        module = package + "." + module

        if len(search_user.conf) > 0:
            if conf.lower() != search_user.conf.lower():
                continue

        # try to load the UserIdResolver Class
        try:

            log.debug("[getUserList] Check for resolver class: %r" % reso)
            y = getResolverObject(reso)
            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" % reso)
                        for u in ulist:
                            u["useridresolver"] = reso
                        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"] = reso
                log.debug("[getUserList] Found this userlist: %r" % ulist)
                users.extend(ulist)

        except KeyError as exx:
            log.error("[getUserList][ module %r:%r ]" % (module, exx))
            log.error("[getUserList] %s" % traceback.format_exc())
            raise exx

        except Exception as exx:
            log.error("[getUserList][ module %r:%r ]" % (module, exx))
            log.error("[getUserList] %s" % traceback.format_exc())
            continue

    return users