コード例 #1
0
    def _get_serial_condition(self, serial, allowed_realm):
        """
        add condition for a given serial

        :param serial: serial number of token
        :param allowed_realm: the allowed realms
        """
        scondition = None

        if serial is None:
            return scondition

        # check if the requested serial is
        # in the realms of the admin (filterRealm)
        allowed = False
        if "*" in allowed_realm:
            allowed = True
        else:
            realms = getTokenRealms(serial)
            for realm in realms:
                if realm in allowed_realm:
                    allowed = True

        # if we have a serial and no realm, we return a un-resolvable condition
        if serial and not allowed:
            scondition = and_(Token.LinOtpTokenSerialnumber == '')
            return scondition

        if "*" in serial:
            like_serial = serial.replace("*", "%")
            scondition = and_(Token.LinOtpTokenSerialnumber.like(like_serial))
        else:
            scondition = and_(Token.LinOtpTokenSerialnumber == serial)

        return scondition
コード例 #2
0
    def _get_serial_condition(self, serial, filterRealm):
        scondition = None

        if serial is None:
            return scondition

        # check if the requested serial is in the realms of the admin (filterRealm)
        log.debug('[TokenIterator::init] start search for serial: >%r<' % (serial))

        allowed = False
        if filterRealm == ['*']:
            allowed = True
        else:
            realms = getTokenRealms(serial)
            for realm in realms:
                if realm in filterRealm:
                    allowed = True

        if allowed == True:
            if "*" in serial:
                like_serial = serial.replace("*", "%")
                scondition = and_(Token.LinOtpTokenSerialnumber.like(like_serial))
            else:
                scondition = and_(Token.LinOtpTokenSerialnumber == serial)

        return scondition
コード例 #3
0
    def _get_serial_condition(self, serial, allowed_realm):
        """
        add condition for a given serial

        :param serial: serial number of token
        :param allowed_realm: the allowed realms
        """
        scondition = None

        if serial is None:
            return scondition

        # check if the requested serial is
        # in the realms of the admin (filterRealm)
        allowed = False
        if "*" in allowed_realm:
            allowed = True
        else:
            realms = getTokenRealms(serial)
            for realm in realms:
                if realm in allowed_realm:
                    allowed = True

        # if we have a serial and no realm, we return a un-resolvable condition
        if serial and not allowed:
            scondition = and_(Token.LinOtpTokenSerialnumber == '')
            return scondition

        if "*" in serial:
            like_serial = serial.replace("*", "%")
            scondition = and_(Token.LinOtpTokenSerialnumber.like(like_serial))
        else:
            scondition = and_(Token.LinOtpTokenSerialnumber == serial)

        return scondition
コード例 #4
0
ファイル: __init__.py プロジェクト: soitun/LinOTP
    def get_token_realm_user(self):

        user = None
        realms = getTokenRealms(self.getSerial())

        if len(realms) == 1:
            user = User(login="", realm=realms[0])

        elif len(realms) == 0:
            realm = getDefaultRealm()
            user = User(login="", realm=realm)
            log.info("No token realm found - using default realm.")

        else:
            msg = ("Multiple realms for token found. But one dedicated "
                   "realm is required for further processing.")
            log.error(msg)
            raise Exception(msg)

        return user
コード例 #5
0
    def get_token_realm_user(self):

        user = None
        realms = getTokenRealms(self.getSerial())

        if len(realms) == 1:
            user = User(login='', realm=realms[0])

        elif len(realms) == 0:
            realm = getDefaultRealm()
            user = User(login='', realm=realm)
            log.info('No token realm found - using default realm.')

        else:
            msg = ('Multiple realms for token found. But one dedicated '
                   'realm is required for further processing.')
            log.error(msg)
            raise Exception(msg)

        return user
コード例 #6
0
ファイル: forwardtoken.py プロジェクト: soitun/LinOTP
def do_forward_failcounter(token):
    """
    this function checks the for the policy

        scope=authentication,
        action=forwardtoken:no_failcounter_forwarding

    defining if the target token failcounter should be incremented / reseted

    :param serial: the token serial number, which allows to derive the
                   realm(s) and owner from
    :return: boolean
    """
    boolean = True

    owner = get_token_owner(token)
    if owner and owner.realm:
        realms = [owner.realm]
    else:
        realms = getTokenRealms(token.getSerial())

    if not realms:
        realms = ["*"]

    for realm in realms:
        params = {
            "scope": "authentication",
            "realm": realm,
            "action": "forwardtoken:no_failcounter_forwarding",
        }

        if owner and owner.login:
            params["user"] = owner.login

        pol = getPolicy(params)

        if pol:
            boolean = False
            break

    return boolean
コード例 #7
0
ファイル: forwardtoken.py プロジェクト: rb12345/LinOTP
def do_forward_failcounter(token):
    '''
    this function checks the for the policy

        scope=authentication,
        action=forwardtoken:no_failcounter_forwarding

    defining if the target token failcounter should be incremented / reseted

    :param serial: the token serial number, which allows to derive the
                   realm(s) and owner from
    :return: boolean
    '''
    boolean = True

    owner = get_token_owner(token)
    if owner and owner.realm:
        realms = [owner.realm]
    else:
        realms = getTokenRealms(token.getSerial())

    if not realms:
        realms = ['*']

    for realm in realms:
        params = {
            'scope': 'authentication',
            'realm': realm,
            'action': "forwardtoken:no_failcounter_forwarding"
        }

        if owner and owner.login:
            params['user'] = owner.login

        pol = getPolicy(params)

        if pol:
            boolean = False
            break

    return boolean
コード例 #8
0
ファイル: forwardtoken.py プロジェクト: gsnbng/LinOTP
def do_forward_failcounter(token):
    '''
    this function checks the for the policy

        scope=authentication,
        action=forwardtoken:no_failcounter_forwarding

    defining if the target token failcounter should be incremented / reseted

    :param serial: the token serial number, which allows to derive the
                   realm(s) and owner from
    :return: boolean
    '''
    boolean = True

    owner = get_token_owner(token)
    if owner and owner.realm:
        realms = [owner.realm]
    else:
        realms = getTokenRealms(token.getSerial())

    if not realms:
        realms = ['*']

    for realm in realms:
        params = {'scope': 'authentication',
                  'realm': realm,
                  'action': "forwardtoken:no_failcounter_forwarding"
                  }

        if owner and owner.login:
            params['user'] = owner.login

        pol = getPolicy(params)

        if pol:
            boolean = False
            break

    return boolean
コード例 #9
0
ファイル: __init__.py プロジェクト: soitun/LinOTP
    def check_standard(self, passw, user, options=None):
        """
        do a standard verification, as we are not in a challengeResponse mode

        the upper interfaces expect in the success the otp counter or at
        least 0 if we have a success. A -1 identifies an error

        :param passw: the password, which should be checked
        :param options: dict with additional request parameters

        :return: tuple of matching otpcounter and a potential reply
        """

        otp_count = -1
        pin_match = False
        reply = None

        # fallback in case of check_s, which does not provide a user
        # but as for further prcessing a dummy user with only the realm defined
        # is required for the policy evaluation
        if user is None:
            realms = getTokenRealms(self.getSerial())
            if len(realms) == 1:
                user = User(login="", realm=realms[0])
            elif len(realms) == 0:
                realm = getDefaultRealm()
                user = User(login="", realm=realm)
                log.info("No token realm found - using default realm.")
            else:
                msg = ("Multiple realms for token found. But one dedicated "
                       "realm is required for further processing.")
                log.error(msg)
                raise Exception(msg)
        import linotp.lib.policy

        support_challenge_response = (
            linotp.lib.policy.get_auth_challenge_response(
                user, self.getType()))

        if len(self.mode) == 1 and self.mode[0] == "challenge":
            # the support_challenge_response is overruled, if the token
            # supports only challenge processing
            support_challenge_response = True

        try:
            # call the token authentication
            (pin_match, otp_count, reply) = self.authenticate(passw,
                                                              user,
                                                              options=options)
        except Exception as exx:
            if (support_challenge_response is True and
                    self.is_challenge_request(passw, user, options=options)):
                log.info("Retry on base of a challenge request:")
                pin_match = False
                otp_count = -1
            else:
                log.error(exx)
                raise

        if otp_count < 0 or pin_match is False:
            if (support_challenge_response is True and self.isActive() and
                    self.is_challenge_request(passw, user, options=options)):
                # we are in createChallenge mode
                # fix for #12413:
                # - moved the create_challenge call to the checkTokenList!
                # after all tokens are processed and only one is challengeing
                # (_res, reply) = create_challenge(self.token, options=options)
                self.challenge_token.append(self)

        if len(self.challenge_token) == 0:
            if otp_count >= 0:
                self.valid_token.append(self)
            elif pin_match is True:
                self.pin_matching_token.append(self)
            else:
                self.invalid_token.append(self)

        return (otp_count, reply)
コード例 #10
0
    def check_standard(self, passw, user, options=None):
        """
        do a standard verification, as we are not in a challengeResponse mode

        the upper interfaces expect in the success the otp counter or at
        least 0 if we have a success. A -1 identifies an error

        :param passw: the password, which should be checked
        :param options: dict with additional request parameters

        :return: tuple of matching otpcounter and a potential reply
        """

        otp_count = -1
        pin_match = False
        reply = None

        # fallback in case of check_s, which does not provide a user
        # but as for further prcessing a dummy user with only the realm defined
        # is required for the policy evaluation
        if user is None:
            realms = getTokenRealms(self.getSerial())
            if len(realms) == 1:
                user = User(login='', realm=realms[0])
            elif len(realms) == 0:
                realm = getDefaultRealm()
                user = User(login='', realm=realm)
                log.info('No token realm found - using default realm.')
            else:
                msg = ('Multiple realms for token found. But one dedicated '
                       'realm is required for further processing.')
                log.error(msg)
                raise Exception(msg)
        import linotp.lib.policy
        support_challenge_response = \
            linotp.lib.policy.get_auth_challenge_response(user, self.getType())

        if len(self.mode) == 1 and self.mode[0] == "challenge":
            # the support_challenge_response is overruled, if the token
            # supports only challenge processing
            support_challenge_response = True

        try:
            # call the token authentication
            (pin_match, otp_count, reply) = self.authenticate(passw, user,
                                                              options=options)
        except Exception as exx:
            if (support_challenge_response is True and
                    self.is_challenge_request(passw, user, options=options)):
                log.info("Retry on base of a challenge request:")
                pin_match = False
                otp_count = -1
            else:
                log.exception("%r" % exx)
                raise Exception(exx)

        if otp_count < 0 or pin_match is False:
            if (support_challenge_response is True and
                    self.isActive() and
                    self.is_challenge_request(passw, user, options=options)):
                # we are in createChallenge mode
                # fix for #12413:
                # - moved the create_challenge call to the checkTokenList!
                # after all tokens are processed and only one is challengeing
                # (_res, reply) = create_challenge(self.token, options=options)
                self.challenge_token.append(self)

        if len(self.challenge_token) == 0:
            if otp_count >= 0:
                self.valid_token.append(self)
            elif pin_match is True:
                self.pin_matching_token.append(self)
            else:
                self.invalid_token.append(self)

        return (otp_count, reply)
コード例 #11
0
ファイル: tokeniterator.py プロジェクト: I85YL64/LinOTP
    def __init__(self, user, serial, page=None, psize=None, filter=None,
                 sort=None, sortdir=None, filterRealm=None, user_fields=None,
                 params=None):
        '''
        constructor of Tokeniterator, which gathers all conditions to build
        a sqalchemy query - iterator

        :param user:     User object - user provides as well the searchfield
                                       entry
        :type  user:     User class
        :param serial:   serial number of a token
        :type  serial:   string
        :param page:     page number
        :type  page:     int
        :param psize:    how many entries per page
        :type  psize:    int
        :param filter:   additional condition
        :type  filter:   string
        :param sort:     sort field definition
        :type  sort:     string
        :param sortdir:  sort direction: ascending or descending
        :type  sortdir:  string
        :param filterRealm:  restrict the set of token to those in
                             the filterRealm
        :type  filterRealm:  string or list
        :param user_fields:  list of additional fields from the user owner
        :type  user_fields: array
        :param params:  list of additional request parameters
                        - currently not used
        :type  params: dict

        :return: - nothing / None

        '''
        log.debug('[TokenIterator::init] begin. start creating TokenIterator \
        class with parameters: user:%r, serial:%r, page=%r, psize:%r, \
                    filter:%r, sort:%r, sortdir:%r, filterRealm:%r' %
                (user, serial, page, psize, filter, sort, sortdir,
                 filterRealm))

        if params is None:
            params = {}

        self.page = 1
        self.pages = 1
        self.tokens = 0
        self.user_fields = user_fields
        if self.user_fields == None:
            self.user_fields = []

        condition = None
        ucondition = None
        scondition = None
        r_condition = None

        if type(filterRealm) in (str, unicode):
            filterRealm = filterRealm.split(',')

        if type(filterRealm) in [list]:
            s_realms = []
            for f in filterRealm:
                #  support for multiple realm filtering in the ui
                #  as a coma separated string
                for s_realm in f.split(','):
                    s_realms.append(s_realm.strip())
            filterRealm = s_realms

        #  create a list of all realms, which are allowed to be searched
        #  based on the list of the existing ones
        valid_realms = []
        realms = getRealms().keys()
        if '*' in filterRealm:
            valid_realms.append("*")
        else:
            for realm in realms:
                if realm in filterRealm:
                    realm = linotp.lib.crypt.uencode(realm)
                    valid_realms.append(realm)

        if serial is not None:
            #  check if the requested serial is in the realms of
            # the admin (filterRealm)
            log.debug('[TokenIterator::init] start search for serial: >%r<'
                       % (serial))

            allowed = False
            if filterRealm == ['*']:
                allowed = True
            else:
                realms = getTokenRealms(serial)
                for realm in realms:
                    if realm in filterRealm:
                        allowed = True

            if allowed == True:
                if '*' in serial:
                    serial = serial.replace('*', '%')
                    scondition = and_(Token.LinOtpTokenSerialnumber.like(serial))
                else:
                    scondition = and_(Token.LinOtpTokenSerialnumber == serial)

        if user.isEmpty() == False and user is not None:
            log.debug('[TokenIterator::init] start search for username: >%r<'
                      % (user))

            if user.login is not None and (user.login) > 0 :
                loginUser = user.login.lower()
                loginUser = loginUser.replace('"', '')
                loginUser = loginUser.replace("'", '')

                searchType = "any"

                #  search for a 'blank' user
                if len(loginUser) == 0 and len(user.login) > 0:
                    searchType = "blank"
                elif loginUser == "/:no user:/" or loginUser == "/:none:/":
                    searchType = "blank"
                elif loginUser == "/:no user info:/":
                    searchType = "wildcard"
                elif "*" in loginUser or "." in loginUser:
                    searchType = "wildcard"
                else:
                    #  no blank and no wildcard search
                    searchType = "exact"

                if searchType == "blank":
                    log.debug('[TokenIterator::init] search for empty user:'******' >%r<' % (user.login))
                    ucondition = and_(or_(Token.LinOtpUserid == u'',
                                          Token.LinOtpUserid == None))

                if searchType == "exact":
                    log.debug('[TokenIterator::init] search for exact user:'******' %r' % (user))
                    serials = []
                    users = []

                    #  if search for a realmuser 'user@realm' we can take the
                    #  realm from the argument
                    if len(user.realm) > 0:
                        users.append(user)
                    else:
                        for realm in valid_realms:
                            users.append(User(user.login, realm))

                    # resolve the realm with wildcard:
                    # identify all users and add these to the userlist
                    userlist = []
                    for usr in users:
                        urealm = usr.realm
                        if urealm == '*':
                            # if the realm is set to *, the getUserId
                            # triggers the identification of all resolvers,
                            # where the user might reside: tigger the user
                            # resolver lookup
                            (uid, resolver, resolverClass) = getUserId(usr)
                            userlist.extend(usr.getUserPerConf())
                        else:
                            userlist.append(usr)

                    for usr in userlist:
                        try:
                            tokens = getTokens4UserOrSerial(user=usr, _class=False)
                            for tok in tokens:
                                serials.append(tok.LinOtpTokenSerialnumber)
                        except UserError as ex:
                            #  we get an exception if the user is not found
                            log.debug('[TokenIterator::init] no exact user: %r'
                                      % (user))
                            log.debug('[TokenIterator::init] %r' % ex)
                    if len(serials) > 0:
                        # if tokens found, search for their serials
                        ucondition = and_(Token.LinOtpTokenSerialnumber.in_(serials))
                    else:
                        # if no token is found, block search for user
                        # and return nothing
                        ucondition = and_(Token.LinOtpTokenSerialnumber == u'')

                #  handle case, when nothing found in former cases
                if searchType == "wildcard":
                    log.debug('[TokenIterator::init] wildcard search: %r' % (user))
                    serials = []
                    users = getAllTokenUsers()
                    logRe = None
                    lU = loginUser.replace('*', '.*')
                    # lU = lU.replace('..', '.')
                    logRe = re.compile(lU)

                    for ser in users:
                        userInfo = users.get(ser)
                        tokenUser = userInfo.get('username').lower()
                        try:
                            if logRe.match(u'' + tokenUser) is not None:
                                serials.append(ser)
                        except Exception as e:
                            log.error('error no express %r ' % e)

                    #  to prevent warning, we check is serials are found
                    #  SAWarning: The IN-predicate on
                    #  "Token.LinOtpTokenSerialnumber" was invoked with an
                    #  empty sequence. This results in a contradiction, which
                    #  nonetheless can be expensive to evaluate.  Consider
                    #  alternative strategies for improved performance.
                    if len(serials) > 0:
                        ucondition = and_(Token.LinOtpTokenSerialnumber.in_(serials))
                    else:
                        ucondition = and_(Token.LinOtpTokenSerialnumber == u'')

        if filter is None:
            condition = None
        elif filter in ['/:active:/', '/:enabled:/',
                        '/:token is active:/', '/:token is enabled:/' ]:
            condition = and_(Token.LinOtpIsactive == True)
        elif filter in ['/:inactive:/', '/:disabled:/',
                        '/:token is inactive:/', '/:token is disabled:/']:
            condition = and_(Token.LinOtpIsactive == False)
        else:
            #  search in other colums
            filter = linotp.lib.crypt.uencode(filter)
            condition = or_(Token.LinOtpTokenDesc.contains(filter),
                            Token.LinOtpIdResClass.contains(filter),
                            Token.LinOtpTokenSerialnumber.contains(filter),
                            Token.LinOtpUserid.contains(filter),
                            Token.LinOtpTokenType.contains(filter))

        ###################################################################
        #   The condition for only getting certain realms!
        if '*' in valid_realms:
            log.debug("[TokenIterator::init] wildcard for realm '*' found."
                      " Tokens of all realms will be displayed")
        elif len(valid_realms) > 0:
            log.debug("[TokenIterator::init] adding filter condition"
                      " for realm %r" % valid_realms)

            #  get all matching realms
            realm_id_tuples = Session.query(Realm.id).\
                                filter(Realm.name.in_(valid_realms)).all()
            realm_ids = set()
            for realm_tuple in realm_id_tuples:
                realm_ids.add(realm_tuple[0])
            #  get all tokenrealm ids
            token_id_tuples = Session.query(TokenRealm.token_id).\
                        filter(TokenRealm.realm_id.in_(realm_ids)).all()
            token_ids = set()
            for token_tuple in token_id_tuples:
                token_ids.add(token_tuple[0])

            #  define the token id condition
            r_condition = and_(Token.LinOtpTokenId.in_(token_ids))

        elif ("''" in filterRealm or '""' in filterRealm or
              "/:no realm:/" in filterRealm):
            log.debug("[TokenIterator::init] search for all tokens, which are"
                      " in no realm")

            #  get all tokenrealm ids
            token_id_tuples = Session.query(TokenRealm.token_id).all()
            token_ids = set()
            for token_tuple in token_id_tuples:
                token_ids.add(token_tuple[0])

            #  define the token id not condition
            r_condition = and_(not_(Token.LinOtpTokenId.in_(token_ids)))

        #  create the final condition as AND of all conditions
        condTuple = ()
        for conn in (condition, ucondition, scondition, r_condition):
            if type(conn).__name__ != 'NoneType':
                condTuple += (conn,)

        condition = and_(*condTuple)

        order = Token.LinOtpTokenDesc

        if sort == "TokenDesc":
            order = Token.LinOtpTokenDesc
        elif sort == "TokenId":
            order = Token.LinOtpTokenId
        elif sort == "TokenType":
            order = Token.LinOtpTokenType
        elif sort == "TokenSerialnumber":
            order = Token.LinOtpTokenSerialnumber
        elif sort == "TokenType":
            order = Token.LinOtpTokenType
        elif sort == "IdResClass":
            order = Token.LinOtpIdResClass
        elif sort == "IdResolver":
            order = Token.LinOtpIdResolver
        elif sort == "Userid":
            order = Token.LinOtpUserid
        elif sort == "FailCount":
            order = Token.LinOtpFailCount
        elif sort == "Userid":
            order = Token.LinOtpUserid
        elif sort == "Isactive":
            order = Token.LinOtpIsactive

        #  care for the result sort order
        if sortdir is not None and sortdir == "desc":
            order = order.desc()
        else:
            order = order.asc()

        #  care for the result pageing
        if page is None:
            self.toks = Session.query(Token).filter(condition).order_by(order).distinct()
            self.tokens = self.toks.count()

            log.debug("[TokenIterator] DB-Query returned # of objects:"
                      " %i" % self.tokens)
            self.pagesize = self.tokens
            self.it = iter(self.toks)
            return

        try:
            if psize is None:
                pagesize = int(getFromConfig("pagesize", 50))
            else:
                pagesize = int(psize)
        except:
            pagesize = 20

        try:
            thePage = int (page) - 1
        except:
            thePage = 0
        if thePage < 0:
            thePage = 0

        start = thePage * pagesize
        stop = (thePage + 1) * pagesize

        self.toks = Session.query(Token).filter(condition).\
                                         order_by(order).distinct()
        self.tokens = self.toks.count()
        log.debug("[TokenIterator::init] DB-Query returned # of objects:"
                  " %i" % self.tokens)
        self.page = thePage + 1
        fpages = float(self.tokens) / float(pagesize)
        self.pages = int(fpages)
        if fpages - int(fpages) > 0:
            self.pages = self.pages + 1
        self.pagesize = pagesize
        self.toks = self.toks.slice(start, stop)

        self.it = iter(self.toks)

        log.debug('[TokenIterator::init] end. Token iterator created: %r' % \
                  (self.it))

        return
コード例 #12
0
ファイル: tokeniterator.py プロジェクト: lucab/LinOTP
    def __init__(self, user, serial, page=None, psize=None, filter=None,
                 sort=None, sortdir=None, filterRealm=None, user_fields=None,
                 params=None):
        '''
        constructor of Tokeniterator, which gathers all conditions to build
        a sqalchemy query - iterator

        :param user:     User object - user provides as well the searchfield
                                       entry
        :type  user:     User class
        :param serial:   serial number of a token
        :type  serial:   string
        :param page:     page number
        :type  page:     int
        :param psize:    how many entries per page
        :type  psize:    int
        :param filter:   additional condition
        :type  filter:   string
        :param sort:     sort field definition
        :type  sort:     string
        :param sortdir:  sort direction: ascending or descending
        :type  sortdir:  string
        :param filterRealm:  restrict the set of token to those in
                             the filterRealm
        :type  filterRealm:  string or list
        :param user_fields:  list of additional fields from the user owner
        :type  user_fields: array
        :param params:  list of additional request parameters
                        - currently not used
        :type  params: dict

        :return: - nothing / None

        '''
        log.debug('[TokenIterator::init] begin. start creating TokenIterator \
        class with parameters: user:%r, serial:%r, page=%r, psize:%r, \
                    filter:%r, sort:%r, sortdir:%r, filterRealm:%r' %
                (user, serial, page, psize, filter, sort, sortdir,
                 filterRealm))

        if params is None:
            params = {}

        self.page = 1
        self.pages = 1
        self.tokens = 0
        self.user_fields = user_fields
        if self.user_fields == None:
            self.user_fields = []

        condition = None
        ucondition = None
        scondition = None
        r_condition = None

        if type(filterRealm) in (str, unicode):
            filterRealm = filterRealm.split(',')

        if type(filterRealm) in [list]:
            s_realms = []
            for f in filterRealm:
                #  support for multiple realm filtering in the ui
                #  as a coma separated string
                for s_realm in f.split(','):
                    s_realms.append(s_realm.strip())
            filterRealm = s_realms

        #  create a list of all realms, which are allowed to be searched
        #  based on the list of the existing ones
        valid_realms = []
        realms = getRealms().keys()
        if '*' in filterRealm:
            valid_realms.append("*")
        else:
            for realm in realms:
                if realm in filterRealm:
                    realm = linotp.lib.crypt.uencode(realm)
                    valid_realms.append(realm)

        if serial is not None:
            #  check if the requested serial is in the realms of
            # the admin (filterRealm)
            log.debug('[TokenIterator::init] start search for serial: >%r<'
                       % (serial))

            allowed = False
            if filterRealm == ['*']:
                allowed = True
            else:
                realms = getTokenRealms(serial)
                for realm in realms:
                    if realm in filterRealm:
                        allowed = True

            if allowed == True:
                if '*' in serial:
                    serial = serial.replace('*', '%')
                    scondition = and_(Token.LinOtpTokenSerialnumber.like(serial))
                else:
                    scondition = and_(Token.LinOtpTokenSerialnumber == serial)

        if user.isEmpty() == False and user is not None:
            log.debug('[TokenIterator::init] start search for username: >%r<'
                      % (user))

            if user.login is not None and (user.login) > 0 :
                loginUser = user.login.lower()
                loginUser = loginUser.replace('"', '')
                loginUser = loginUser.replace("'", '')

                searchType = "any"

                #  search for a 'blank' user
                if len(loginUser) == 0 and len(user.login) > 0:
                    searchType = "blank"
                elif loginUser == "/:no user:/" or loginUser == "/:none:/":
                    searchType = "blank"
                elif loginUser == "/:no user info:/":
                    searchType = "wildcard"
                elif "*" in loginUser or "." in loginUser:
                    searchType = "wildcard"
                else:
                    #  no blank and no wildcard search
                    searchType = "exact"

                if searchType == "blank":
                    log.debug('[TokenIterator::init] search for empty user:'******' >%r<' % (user.login))
                    ucondition = and_(or_(Token.LinOtpUserid == u'',
                                          Token.LinOtpUserid == None))

                if searchType == "exact":
                    log.debug('[TokenIterator::init] search for exact user:'******' %r' % (user))
                    serials = []
                    users = []

                    #  if search for a realmuser 'user@realm' we can take the
                    #  realm from the argument
                    if len(user.realm) > 0:
                        users.append(user)
                    else:
                        for realm in valid_realms:
                            users.append(User(user.login, realm))

                    # resolve the realm with wildcard:
                    # identify all users and add these to the userlist
                    userlist = []
                    for usr in users:
                        urealm = usr.realm
                        if urealm == '*':
                            # if the realm is set to *, the getUserId
                            # triggers the identification of all resolvers,
                            # where the user might reside: tigger the user
                            # resolver lookup
                            (uid, resolver, resolverClass) = getUserId(usr)
                            userlist.extend(usr.getUserPerConf())
                        else:
                            userlist.append(usr)

                    for usr in userlist:
                        try:
                            tokens = getTokens4UserOrSerial(user=usr, _class=False)
                            for tok in tokens:
                                serials.append(tok.LinOtpTokenSerialnumber)
                        except UserError as ex:
                            #  we get an exception if the user is not found
                            log.debug('[TokenIterator::init] no exact user: %r'
                                      % (user))
                            log.debug('[TokenIterator::init] %r' % ex)

                    if len(serials) > 0:
                        #  if tokens found, search for their serials
                        ucondition = and_(Token.LinOtpTokenSerialnumber.in_(serials))
                    else:
                        #  if no token is found, block search for user
                        #  and return nothing
                        ucondition = and_(or_(Token.LinOtpUserid == u'',
                                              Token.LinOtpUserid == None))

                #  handle case, when nothing found in former cases
                if searchType == "wildcard":
                    log.debug('[TokenIterator::init] wildcard search: %r' % (user))
                    serials = []
                    users = getAllTokenUsers()
                    logRe = None
                    lU = loginUser.replace('*', '.*')
                    # lU = lU.replace('..', '.')
                    logRe = re.compile(lU)

                    for ser in users:
                        userInfo = users.get(ser)
                        tokenUser = userInfo.get('username').lower()
                        try:
                            if logRe.match(u'' + tokenUser) is not None:
                                serials.append(ser)
                        except Exception as e:
                            log.error('error no express %r ' % e)

                    #  to prevent warning, we check is serials are found
                    #  SAWarning: The IN-predicate on
                    #  "Token.LinOtpTokenSerialnumber" was invoked with an
                    #  empty sequence. This results in a contradiction, which
                    #  nonetheless can be expensive to evaluate.  Consider
                    #  alternative strategies for improved performance.
                    if len(serials) > 0:
                        ucondition = and_(Token.LinOtpTokenSerialnumber.in_(serials))
                    else:
                        ucondition = and_(or_(Token.LinOtpUserid == u'',
                                              Token.LinOtpUserid == None))

        if filter is None:
            condition = None
        elif filter in ['/:active:/', '/:enabled:/',
                        '/:token is active:/', '/:token is enabled:/' ]:
            condition = and_(Token.LinOtpIsactive == True)
        elif filter in ['/:inactive:/', '/:disabled:/',
                        '/:token is inactive:/', '/:token is disabled:/']:
            condition = and_(Token.LinOtpIsactive == False)
        else:
            #  search in other colums
            filter = linotp.lib.crypt.uencode(filter)
            condition = or_(Token.LinOtpTokenDesc.contains(filter),
                            Token.LinOtpIdResClass.contains(filter),
                            Token.LinOtpTokenSerialnumber.contains(filter),
                            Token.LinOtpUserid.contains(filter),
                            Token.LinOtpTokenType.contains(filter))

        ###################################################################
        #   The condition for only getting certain realms!
        if '*' in valid_realms:
            log.debug("[TokenIterator::init] wildcard for realm '*' found."
                      " Tokens of all realms will be displayed")
        elif len(valid_realms) > 0:
            log.debug("[TokenIterator::init] adding filter condition"
                      " for realm %r" % valid_realms)

            #  get all matching realms
            realm_id_tuples = Session.query(Realm.id).\
                                filter(Realm.name.in_(valid_realms)).all()
            realm_ids = set()
            for realm_tuple in realm_id_tuples:
                realm_ids.add(realm_tuple[0])
            #  get all tokenrealm ids
            token_id_tuples = Session.query(TokenRealm.token_id).\
                        filter(TokenRealm.realm_id.in_(realm_ids)).all()
            token_ids = set()
            for token_tuple in token_id_tuples:
                token_ids.add(token_tuple[0])

            #  define the token id condition
            r_condition = and_(Token.LinOtpTokenId.in_(token_ids))

        elif ("''" in filterRealm or '""' in filterRealm or
              "/:no realm:/" in filterRealm):
            log.debug("[TokenIterator::init] search for all tokens, which are"
                      " in no realm")

            #  get all tokenrealm ids
            token_id_tuples = Session.query(TokenRealm.token_id).all()
            token_ids = set()
            for token_tuple in token_id_tuples:
                token_ids.add(token_tuple[0])

            #  define the token id not condition
            r_condition = and_(not_(Token.LinOtpTokenId.in_(token_ids)))

        #  create the final condition as AND of all conditions
        condTuple = ()
        for conn in (condition, ucondition, scondition, r_condition):
            if type(conn).__name__ != 'NoneType':
                condTuple += (conn,)

        condition = and_(*condTuple)

        order = Token.LinOtpTokenDesc

        if sort == "TokenDesc":
            order = Token.LinOtpTokenDesc
        elif sort == "TokenId":
            order = Token.LinOtpTokenId
        elif sort == "TokenType":
            order = Token.LinOtpTokenType
        elif sort == "TokenSerialnumber":
            order = Token.LinOtpTokenSerialnumber
        elif sort == "TokenType":
            order = Token.LinOtpTokenType
        elif sort == "IdResClass":
            order = Token.LinOtpIdResClass
        elif sort == "IdResolver":
            order = Token.LinOtpIdResolver
        elif sort == "Userid":
            order = Token.LinOtpUserid
        elif sort == "FailCount":
            order = Token.LinOtpFailCount
        elif sort == "Userid":
            order = Token.LinOtpUserid
        elif sort == "Isactive":
            order = Token.LinOtpIsactive

        #  care for the result sort order
        if sortdir is not None and sortdir == "desc":
            order = order.desc()
        else:
            order = order.asc()

        #  care for the result pageing
        if page is None:
            self.toks = Session.query(Token).filter(condition).order_by(order).distinct()
            self.tokens = self.toks.count()

            log.debug("[TokenIterator] DB-Query returned # of objects:"
                      " %i" % self.tokens)
            self.pagesize = self.tokens
            self.it = iter(self.toks)
            return

        try:
            if psize is None:
                pagesize = int(getFromConfig("pagesize", 50))
            else:
                pagesize = int(psize)
        except:
            pagesize = 20

        try:
            thePage = int (page) - 1
        except:
            thePage = 0
        if thePage < 0:
            thePage = 0

        start = thePage * pagesize
        stop = (thePage + 1) * pagesize

        self.toks = Session.query(Token).filter(condition).\
                                         order_by(order).distinct()
        self.tokens = self.toks.count()
        log.debug("[TokenIterator::init] DB-Query returned # of objects:"
                  " %i" % self.tokens)
        self.page = thePage + 1
        fpages = float(self.tokens) / float(pagesize)
        self.pages = int(fpages)
        if fpages - int(fpages) > 0:
            self.pages = self.pages + 1
        self.pagesize = pagesize
        self.toks = self.toks.slice(start, stop)

        self.it = iter(self.toks)

        log.debug('[TokenIterator::init] end. Token iterator created: %r' % \
                  (self.it))

        return