Пример #1
0
def delete(realms, status, date=None):
    """
    delete all rows in reporting database before a given date

    :param date: (optional)day until which all rows will be deleted
    :type date: string in format: 'yyyy-mm-dd'

    :return: number of deleted rows
    """

    if not isinstance(realms, (list, tuple)):
        realms = realms.split(',')

    realm_cond = tuple()
    for realm in realms:
       realm_cond += (or_(Reporting.realm == realm),)

    status_cond = tuple()
    for stat in status:
        status_cond += (or_(Reporting.parameter == stat),)

    date_cond = tuple()
    if date:
        date_cond += (and_(Reporting.timestamp < date),)

    conds = (and_(*date_cond), or_(*realm_cond), or_(*status_cond),)

    rows = Session.query(Reporting).filter(*conds)
    row_num = rows.count()

    for row in rows:
        Session.delete(row)
    return row_num
Пример #2
0
def deleteRealm(realmname):
    '''
    delete the realm from the Database Table with the given name

    :param realmname: the to be deleted realm
    :type  realmname: string
    '''

    log.debug("[delete] delete Realm object with name=%s" % realmname)
    r = getRealmObject(name=realmname)
    if r is None:
        ''' if no realm is found, we re-try the lowercase name for backward compatibility '''
        r = getRealmObject(name=realmname.lower())
    realmId = 0
    if r is not None:
        realmId = r.id

        if realmId != 0:
            log.debug(
                "[deleteRealm] Now deleting all realations with realm_id=%i" %
                realmId)
            Session.query(TokenRealm).filter(
                TokenRealm.realm_id == realmId).delete()
        Session.delete(r)

    else:
        log.warning(
            "[deleteRealm] There is no realm object with the name %s to be deleted."
            % realmname)
        return False
    # now delete all relations, i.e. remove all Tokens from this realm.

    return True
Пример #3
0
def deleteRealm(realmname):
    '''
    delete the realm from the Database Table with the given name

    :param realmname: the to be deleted realm
    :type  realmname: string
    '''

    log.debug("deleting realm object with name=%s" % realmname)
    r = getRealmObject(name=realmname)
    if r is None:
        ''' if no realm is found, we re-try the lowercase name for backward compatibility '''
        r = getRealmObject(name=realmname.lower())
    realmId = 0
    if r is not None:
        realmId = r.id

        if realmId != 0:
            log.debug("Deleting token relations for realm with id %i" % realmId)
            Session.query(TokenRealm).filter(TokenRealm.realm_id == realmId).delete()
        Session.delete(r)

    else:
        log.warning("Realm with name %s was not found." % realmname)
        return False
    # now delete all relations, i.e. remove all Tokens from this realm.

    # finally we delete the 'realmname' cache
    from linotp.lib.user import delete_realm_resolver_cache
    delete_realm_resolver_cache(realmname)

    return True
Пример #4
0
def _removeConfigDB(key):
    log.debug('removeConfigDB %r' % key)
    num = 0

    if (not key.startswith("linotp.")):
        if not key.startswith('enclinotp.'):
            key = u"linotp." + key

    confEntries = Session.query(Config).filter(Config.Key == unicode(key))

    num = confEntries.count()
    if num == 1:
        theConf = confEntries[0]

        try:
            # Session.add(theConf)
            Session.delete(theConf)

        except Exception as e:
            log.exception('[removeConfigDB] failed')
            raise ConfigAdminError("remove Config failed for %r: %r" %
                                   (key, e),
                                   id=1133)

    return num
Пример #5
0
def deleteRealm(realmname):
    '''
    delete the realm from the Database Table with the given name

    :param realmname: the to be deleted realm
    :type  realmname: string
    '''

    log.debug("deleting realm object with name=%s" % realmname)
    r = getRealmObject(name=realmname)
    if r is None:
        ''' if no realm is found, we re-try the lowercase name for backward compatibility '''
        r = getRealmObject(name=realmname.lower())
    realmId = 0
    if r is not None:
        realmId = r.id

        if realmId != 0:
            log.debug("Deleting token relations for realm with id %i" % realmId)
            Session.query(TokenRealm).filter(TokenRealm.realm_id == realmId).delete()
        Session.delete(r)

    else:
        log.warning("Realm with name %s was not found." % realmname)
        return False
    # now delete all relations, i.e. remove all Tokens from this realm.

    # finally we delete the 'realmname' cache
    from linotp.lib.user import delete_realm_resolver_cache
    delete_realm_resolver_cache(realmname)

    return True
Пример #6
0
def deleteRealm(realmname):
    '''
    delete the realm from the Database Table with the given name

    :param realmname: the to be deleted realm
    :type  realmname: string
    '''

    log.debug("[delete] delete Realm object with name=%s" % realmname)
    r = getRealmObject(name=realmname)
    if r is None:
        ''' if no realm is found, we re-try the lowercase name for backward compatibility '''
        r = getRealmObject(name=realmname.lower())
    realmId = 0
    if r is not None:
        realmId = r.id

        if realmId != 0:
            log.debug("[deleteRealm] Now deleting all realations with realm_id=%i" % realmId)
            Session.query(TokenRealm).filter(TokenRealm.realm_id == realmId).delete()
        Session.delete(r)

    else:
        log.warning("[deleteRealm] There is no realm object with the name %s to be deleted." % realmname)
        return False
    # now delete all relations, i.e. remove all Tokens from this realm.

    return True
Пример #7
0
 def deleteToken(self):
     # # some dbs (eg. DB2) runs in deadlock, if the TokenRealm entry
     # # is deleteted via foreign key relation
     # # so we delete it explicitly
     Session.query(TokenRealm).filter(
         TokenRealm.token_id == self.LinOtpTokenId).delete()
     Session.delete(self)
     return True
Пример #8
0
 def deleteToken(self):
     log.debug('deleteToken()')
     ## some dbs (eg. DB2) runs in deadlock, if the TokenRealm entry
     ## is deleteted via foreign key relation
     ## so we delete it explicit
     Session.query(TokenRealm).filter(TokenRealm.token_id == self.LinOtpTokenId).delete()
     Session.delete(self)
     log.debug('delete token success')
     return True
Пример #9
0
def delete_reporting():
    """
    delete all rows in reporting database

    :return: number of deleted rows
    """
    rows = Session.query(Reporting)
    row_num = rows.count()
    for row in rows.all():
        Session.delete(row)
    return row_num
Пример #10
0
    def deleteToken(self):
        # some dbs (eg. DB2) runs in deadlock, if the TokenRealm entry
        # is deleteted via foreign key relation
        # so we delete it explicitly
        token_realm_entries = Session.query(TokenRealm).filter(
                            TokenRealm.token_id == self.LinOtpTokenId).all()

        for token_realm_entry in token_realm_entries:
            Session.delete(token_realm_entry)

        Session.delete(self)
        return True
Пример #11
0
    def deleteToken(self):
        # some dbs (eg. DB2) runs in deadlock, if the TokenRealm entry
        # is deleteted via foreign key relation
        # so we delete it explicitly
        token_realm_entries = Session.query(TokenRealm).filter(
            TokenRealm.token_id == self.LinOtpTokenId).all()

        for token_realm_entry in token_realm_entries:
            Session.delete(token_realm_entry)

        Session.delete(self)
        return True
Пример #12
0
def delete_before(date):
    """
    delete all rows in reporting database before a given date

    :param date: day until which all rows will be deleted
    :type date: string in format: 'yyyy-mm-dd'

    :return: number of deleted rows
    """
    rows = Session.query(Reporting).filter(Reporting.timestamp < date)
    row_num = rows.count()

    for row in rows:
        Session.delete(row)
    return row_num
Пример #13
0
    def delete_challenges(self, challenges):
        """
        delete challenges, which match those listed ones

        :param challenges: list of (dict|int|str) challenges
        :return: result of the delete operation
        """

        challenge_ids = []
        for challenge in challenges:
            if type(challenge) == dict:
                if challenge.has_key("id"):
                    challenge_id = challenge.get("id")
            elif type(challenge) == Challenge:
                challenge_id = challenge.get("id")
            elif type(challenge) in (unicode, str, int):
                challenge_id = challenge

            try:
                challenge_ids.append(int(challenge_id))
            except ValueError:
                ## ignore
                LOG.warning("failed to concert the challengeId %r to int()" % challenge_id)

        res = 1

        # 1. get all challeges which are to be deleted
        # 2. self.token.select_challenges()

        if len(challenge_ids) > 0:

            del_challes = (
                Session.query(Challenge)
                .filter(Challenge.tokenserial == u"" + self.token.getSerial())
                .filter(Challenge.id.in_(challenge_ids))
                .all()
            )

            for dell in del_challes:
                Session.delete(dell)
                # pass

        return res
Пример #14
0
def _removeConfigDB(key):
    """
    remove entry from config table

    :param key: the name of the entry
    :return: number of deleted entries
    """
    log.debug('removeConfigDB %r' % key)

    if (not key.startswith("linotp.")):
        if not key.startswith('enclinotp.'):
            key = u"linotp." + key

    confEntries = Session.query(Config).filter(
        Config.Key == unicode(key)).all()

    if not confEntries:
        return 0

    theConf = confEntries[0]

    to_be_deleted = []
    to_be_deleted.append(theConf)

    # if entry is a contious type, delete all of this kind
    if theConf.Type == 'C' and theConf.Description[:len('0:')] == '0:':
        _start, end = theConf.Description.split(':')
        search_key = "%s__[%%:%s]" % (key, end)
        cont_entries = Session.query(Config).filter(
            Config.Key.like(search_key)).all()
        to_be_deleted.extend(cont_entries)

    try:
        for entry in to_be_deleted:
            # Session.add(theConf)
            Session.delete(entry)

    except Exception as e:
        log.exception('[removeConfigDB] failed')
        raise ConfigAdminError("remove Config failed for %r: %r" % (key, e),
                               id=1133)

    return len(to_be_deleted)
Пример #15
0
def _removeConfigDB(key):
    """
    remove entry from config table

    :param key: the name of the entry
    :return: number of deleted entries
    """
    log.debug('removeConfigDB %r' % key)

    if (not key.startswith("linotp.")):
        if not key.startswith('enclinotp.'):
            key = u"linotp." + key

    confEntries = Session.query(Config).filter(Config.Key == unicode(key)).all()

    if not confEntries:
        return 0

    theConf = confEntries[0]

    to_be_deleted = []
    to_be_deleted.append(theConf)

    # if entry is a contious type, delete all of this kind
    if theConf.Type == 'C' and theConf.Description[:len('0:')] == '0:':
        _start, end = theConf.Description.split(':')
        search_key = "%s__[%%:%s]" % (key, end)
        cont_entries = Session.query(Config).filter(Config.Key.like(search_key)).all()
        to_be_deleted.extend(cont_entries)

    try:
        for entry in to_be_deleted:
            # Session.add(theConf)
            Session.delete(entry)

    except Exception as e:
        log.exception('[removeConfigDB] failed')
        raise ConfigAdminError("remove Config failed for %r: %r"
                               % (key, e), id=1133)

    return len(to_be_deleted)
Пример #16
0
    def delete_challenges(self, challenges):
        '''
        delete challenges, which match those listed ones

        :param challenges: list of (dict|int|str) challenges
        :return: result of the delete operation
        '''

        challenge_ids = []
        for challenge in challenges:
            if type(challenge) == dict:
                if challenge.has_key('id'):
                    challenge_id = challenge.get('id')
            elif type(challenge) == Challenge:
                challenge_id = challenge.get('id')
            elif type(challenge) in (unicode, str, int):
                challenge_id = challenge

            try:
                challenge_ids.append(int(challenge_id))
            except ValueError:
                ## ignore
                LOG.warning("failed to concert the challengeId %r to int()" %
                            challenge_id)

        res = 1

        # 1. get all challeges which are to be deleted
        # 2. self.token.select_challenges()

        if len(challenge_ids) > 0:

            del_challes = Session.query(Challenge).\
                filter(Challenge.tokenserial == u'' + self.token.getSerial()).\
                filter(Challenge.id.in_(challenge_ids)).all()

            for dell in del_challes:
                Session.delete(dell)
                #pass

        return res
Пример #17
0
def delete(realms, status, date=None):
    """
    delete all rows in reporting database before a given date,
    filtered by realm and status

    :param realms: the ralm to filter
    :param status: the status to filter
    :param date: (optional) day until which all rows will be deleted
    :type date: string in format: 'yyyy-mm-dd'

    :return: number of deleted rows
    """

    if not isinstance(realms, (list, tuple)):
        realms = realms.split(',')

    realm_cond = tuple()
    for realm in realms:
        realm_cond += (or_(Reporting.realm == realm), )

    status_cond = tuple()
    for stat in status:
        status_cond += (or_(Reporting.parameter == stat), )

    date_cond = tuple()
    if date:
        date_cond += (and_(Reporting.timestamp < date), )

    conds = (
        and_(*date_cond),
        or_(*realm_cond),
        or_(*status_cond),
    )

    rows = Session.query(Reporting).filter(*conds)
    row_num = rows.count()

    for row in rows:
        Session.delete(row)
    return row_num
Пример #18
0
def delete_challenges(serial, challenges):
    '''
    delete some challenges of a token

    :param serial: the serial number of the token
    :param challenges: list of (dict|int|str|challenge objects)

    :return: result of the delete operation
    '''

    challenge_ids = []
    for challenge in challenges:
        if type(challenge) == dict:
            if 'id' in challenge:
                challenge_id = challenge.get('id')
        elif type(challenge) == Challenge:
            challenge_id = challenge.get('id')
        elif type(challenge) in (unicode, str, int):
            challenge_id = challenge

        try:
            challenge_ids.append(int(challenge_id))
        except ValueError:
            # ignore
            log.warning("failed to convert the challengeId %r to int()" %
                        challenge_id)

    res = 1
    # gather all challenges with one sql 'in' statement
    if len(challenge_ids) > 0:
        del_challes = Session.query(Challenge).\
            filter(Challenge.tokenserial == serial).\
            filter(Challenge.id.in_(challenge_ids)).all()

        # and delete them via session
        for dell in del_challes:
            Session.delete(dell)

    return res
Пример #19
0
def delete_challenges(serial, challenges):
    '''
    delete some challenges of a token

    :param serial: the serial number of the token
    :param challenges: list of (dict|int|str|challenge objects)

    :return: result of the delete operation
    '''

    challenge_ids = []
    for challenge in challenges:
        if type(challenge) == dict:
            if 'id' in challenge:
                challenge_id = challenge.get('id')
        elif type(challenge) == Challenge:
            challenge_id = challenge.get('id')
        elif type(challenge) in (unicode, str, int):
            challenge_id = challenge

        try:
            challenge_ids.append(int(challenge_id))
        except ValueError:
            # ignore
            log.warning("failed to convert the challengeId %r to int()" %
                        challenge_id)

    res = 1
    # gather all challenges with one sql 'in' statement
    if len(challenge_ids) > 0:
        del_challes = Session.query(Challenge).\
            filter(Challenge.tokenserial == serial).\
            filter(Challenge.id.in_(challenge_ids)).all()

        # and delete them via session
        for dell in del_challes:
            Session.delete(dell)

    return res
Пример #20
0
def _removeConfigDB(key):
    log.debug('removeConfigDB %r' % key)
    num = 0

    if (not key.startswith("linotp.")):
        if not key.startswith('enclinotp.'):
            key = u"linotp." + key

    confEntries = Session.query(Config).filter(Config.Key == unicode(key))

    num = confEntries.count()
    if num == 1:
        theConf = confEntries[0]

        try:
            # Session.add(theConf)
            Session.delete(theConf)

        except Exception as e:
            log.exception('[removeConfigDB] failed')
            raise ConfigAdminError("remove Config failed for %r: %r"
                                   % (key, e), id=1133)

    return num
Пример #21
0
def create_challenge(token, options=None):
    """
    dedicated method to create a challenge to support the implementation
    of challenge policies in future

    :param options: optional parameters for token specific tokens
                    eg. request a signed challenge
    :return: a tuple of  (boolean, and a dict, which contains the
             {'challenge' : challenge} description)
    """

    ## response dict, describing the challenge reply
    challenge = {}
    ## the allocated db challenge object
    challenge_obj = None
    retry_counter = 0
    reason = None

    id_length = int(getFromConfig("TransactionIdLength", 12))

    while True:
        try:

            transactionid = Challenge.createTransactionId(length=id_length)
            num_challenges = Session.query(Challenge).filter(Challenge.transid == transactionid).count()

            if num_challenges == 0:
                challenge_obj = Challenge(transid=transactionid, tokenserial=token.getSerial())
            if challenge_obj is not None:
                break

        except Exception as exce:
            LOG.info("Failed to create Challenge: %r", exce)
            reason = exce

        ## prevent an unlimited loop
        retry_counter = retry_counter + 1
        if retry_counter > 100:
            LOG.info("Failed to create Challenge for %d times: %r -quiting!", retry_counter, reason)
            raise Exception("Failed to create challenge %r" % reason)

    challenges = get_challenges(serial=token.getSerial())

    ## carefully create a new challenge
    try:

        ## we got a challenge object allocated and initialize the challenge
        (res, open_transactionid, message, attributes) = token.initChallenge(
            transactionid, challenges=challenges, options=options
        )

        if res == False:
            ## if a different transid is returned, this indicates, that there
            ## is already an outstanding challenge we can refere to
            if open_transactionid != transactionid:
                transactionid = open_transactionid

        else:
            ## in case the init was successfull, we preserve no the challenge data
            ## to support the implementation of a blocking based on the previous
            ## stored data
            challenge_obj.setChallenge(message)
            challenge_obj.save()

            (res, message, data, attributes) = token.createChallenge(transactionid, options=options)

            if res == True:
                ## persist the final challenge data + message
                challenge_obj.setChallenge(message)
                challenge_obj.setData(data)
                challenge_obj.save()
            else:
                transactionid = ""

    except Exception as exce:
        reason = exce
        res = False

    ## if something goes wrong with the challenge, remove it
    if res == False and challenge_obj is not None:
        try:
            LOG.debug("deleting session")
            Session.delete(challenge_obj)
            Session.commit()
        except Exception as exx:
            LOG.debug("deleting session failed: %r" % exx)
            try:
                Session.expunge(challenge_obj)
                Session.commit()
            except Exception as exx:
                LOG.debug("expunge session failed: %r" % exx)

    ## in case that create challenge fails, we must raise this reason
    if reason is not None:
        message = "%r" % reason
        LOG.error("Failed to create or init challenge %r " % reason)
        raise reason

    ## prepare the response for the user
    if transactionid is not None:
        challenge["transactionid"] = transactionid

    if message is not None:
        challenge["message"] = message

    if attributes is not None and type(attributes) == dict:
        challenge.update(attributes)

    return (res, challenge)
Пример #22
0
def create_challenge(token, options=None):
    """
    dedicated method to create a challenge to support the implementation
    of challenge policies in future

    :param options: optional parameters for token specific tokens
                    eg. request a signed challenge
    :return: a tuple of  (boolean, and a dict, which contains the
             {'challenge' : challenge} description)
    """

    ## response dict, describing the challenge reply
    challenge = {}
    ## the allocated db challenge object
    challenge_obj = None
    retry_counter = 0
    reason = None

    id_length = int(getFromConfig('TransactionIdLength', 12))

    while True:
        try:

            transactionid = Challenge.createTransactionId(length=id_length)
            num_challenges = Session.query(Challenge).\
                    filter(Challenge.transid == transactionid).count()

            if num_challenges == 0:
                challenge_obj = Challenge(transid=transactionid,
                                          tokenserial=token.getSerial())
            if challenge_obj is not None:
                break

        except Exception as exce:
            LOG.info("Failed to create Challenge: %r", exce)
            reason = exce

        ## prevent an unlimited loop
        retry_counter = retry_counter + 1
        if retry_counter > 100:
            LOG.info("Failed to create Challenge for %d times: %r -quiting!",
                     retry_counter, reason)
            raise Exception('Failed to create challenge %r' % reason)

    challenges = get_challenges(serial=token.getSerial())

    ## carefully create a new challenge
    try:

        ## we got a challenge object allocated and initialize the challenge
        (res, open_transactionid, message, attributes) = \
                             token.initChallenge(transactionid,
                                                 challenges=challenges,
                                                 options=options)

        if res == False:
            ## if a different transid is returned, this indicates, that there
            ## is already an outstanding challenge we can refere to
            if open_transactionid != transactionid:
                transactionid = open_transactionid

        else:
            ## in case the init was successfull, we preserve no the challenge data
            ## to support the implementation of a blocking based on the previous
            ## stored data
            challenge_obj.setChallenge(message)
            challenge_obj.save()

            (res, message, data, attributes) = \
                        token.createChallenge(transactionid, options=options)

            if res == True:
                ## persist the final challenge data + message
                challenge_obj.setChallenge(message)
                challenge_obj.setData(data)
                challenge_obj.save()
            else:
                transactionid = ''

    except Exception as exce:
        reason = exce
        res = False

    ## if something goes wrong with the challenge, remove it
    if res == False and challenge_obj is not None:
        try:
            LOG.debug("deleting session")
            Session.delete(challenge_obj)
            Session.commit()
        except Exception as exx:
            LOG.debug("deleting session failed: %r" % exx)
            try:
                Session.expunge(challenge_obj)
                Session.commit()
            except Exception as exx:
                LOG.debug("expunge session failed: %r" % exx)

    ## in case that create challenge fails, we must raise this reason
    if reason is not None:
        message = "%r" % reason
        LOG.error("Failed to create or init challenge %r " % reason)
        raise reason

    ## prepare the response for the user
    if transactionid is not None:
        challenge['transactionid'] = transactionid

    if message is not None:
        challenge['message'] = message

    if attributes is not None and type(attributes) == dict:
        challenge.update(attributes)

    return (res, challenge)