def test_good_key():
    """validating check_key logic"""
    connection = TinyMongoClient(CACHE_PATH)
    api_db = connection.prosperAPI.users
    vals = api_db.find()

    if not vals:
        global DO_API_TESTS
        DO_API_TESTS = False
        pytest.xfail('Unable to test without test keys')

    test_key = vals['api_key']
    assert api_utils.check_key(test_key)

    new_vals = api_db.find_one({'api_key': test_key})

    # TODO: fails on virgin key
    old_time = datetime.strptime(vals['last_accessed'],
                                 '%Y-%m-%dT%H:%M:%S.%f').timestamp()

    new_time = datetime.strptime(new_vals['last_accessed'],
                                 '%Y-%m-%dT%H:%M:%S.%f').timestamp()

    assert new_time > old_time
    connection.close()
def test_good_key():
    """validating check_key logic"""
    connection = TinyMongoClient(CACHE_PATH)
    api_db = connection.prosperAPI.users
    vals = api_db.find()

    if not vals:
        global DO_API_TESTS
        DO_API_TESTS = False
        pytest.xfail('Unable to test without test keys')

    test_key = vals['api_key']
    assert api_utils.check_key(test_key)

    new_vals = api_db.find_one({'api_key': test_key})

    # TODO: fails on virgin key
    old_time = datetime.strptime(
        vals['last_accessed'],
        '%Y-%m-%dT%H:%M:%S.%f').timestamp()

    new_time = datetime.strptime(
        new_vals['last_accessed'],
        '%Y-%m-%dT%H:%M:%S.%f').timestamp()

    assert new_time > old_time
    connection.close()
def test_get_api_key():
    """fetch api key from cache for testing"""
    global TEST_API_KEY
    connection = TinyMongoClient(CACHE_PATH)
    api_db = connection.prosperAPI.users
    vals = api_db.find()

    if not vals:
        pytest.xfail('Unable to test without test keys')

    test_key = vals['api_key']
    connection.close()
    TEST_API_KEY = test_key
Beispiel #4
0
def check_key(
        api_key,
        throw_on_fail=False,
        logger=LOGGER
):
    """check if API key is valid

    Args:
        api_key (str): given API key
        cache_path (str, optional): override for cache_path
        api_file (str, optional): tinydb filename
        throw_on_fail (bool, optional): raise exception if API key fails
        logger (:obj:`logging.logger`): logging handle

    Returns:
        (bool) access allowed or not

    """
    
    # Connect to TinyMongoDB and use prosperAPI DB 
    connection = TinyMongoClient(CACHE_PATH)
    userdb = connection.prosperAPI.users
    api_value = userdb.find_one({'api_key': api_key})

    access_allowed = False
    if api_value:
        logger.info(
            'accessed service - {0}:{1}'.format(
                api_value['user_name'],
                api_value['user_info']
            )
        )
        logger.debug(api_value)
        currenttime = datetime.now().isoformat()
        userdb.update(
            {'api_key': api_key},
            {
                '$set': {'last_accessed': currenttime}
            }
            )
        connection.close()
        access_allowed = True
    else:
        logger.warning('Invalid API key: {0}'.format(api_key))
        if throw_on_fail:
            raise exceptions.APIKeyInvalid(
                status=401,
                message='Invalid API key'
            )

    return access_allowed
Beispiel #5
0
def check_key(
        api_key,
        throw_on_fail=False,
        logger=logging.getLogger('publicAPI')
):
    """check if API key is valid

    Args:
        api_key (str): given API key
        cache_path (str, optional): override for cache_path
        api_file (str, optional): tinydb filename
        throw_on_fail (bool, optional): raise exception if API key fails
        logger (:obj:`logging.logger`): logging handle

    Returns:
        bool: access allowed or not

    """

    # Connect to TinyMongoDB and use prosperAPI DB
    connection = TinyMongoClient(CACHE_PATH)
    userdb = connection.prosperAPI.users
    api_value = userdb.find_one({'api_key': api_key})

    access_allowed = False
    if api_value:
        logger.info(
            'accessed service - {0}:{1}'.format(
                api_value['user_name'],
                api_value['user_info']
            )
        )
        logger.debug(api_value)
        currenttime = datetime.now().isoformat()
        userdb.update(
            {'api_key': api_key},
            {'$set': {'last_accessed': currenttime}}
        )
        connection.close()
        access_allowed = True
    else:
        logger.warning('Invalid API key: {0}'.format(api_key))
        if throw_on_fail:
            raise exceptions.APIKeyInvalid(
                status=401,
                message='Invalid API key'
            )

    return access_allowed
Beispiel #6
0
def clear_tinymongo_cache(bool_prod=False):
    """tinymongo uses all collections in one file, clearing requires direct access"""
    if not bool_prod:
        remove(path.join(TEST_CACHE_PATH, 'prosperAPI.json'))
        return

    with open(path.join(PROD_CACHE_PATH, 'prosperAPI.json'), 'r') as tdb_fh:
        raw_json = json.load(tdb_fh)

    collections = raw_json.keys()
    tdb = TinyMongoClient(PROD_CACHE_PATH)
    for collection in collections:
        if collection in SPECIAL_CACHE_COLLECTIONS:
            #skip special tables
            continue

        tdb.prosperAPI[collection].delete_many({})  #nuke it from orbit

    tdb.close()
Beispiel #7
0
def clear_tinymongo_cache(bool_prod=False):
    """tinymongo uses all collections in one file, clearing requires direct access"""
    if not bool_prod:
        remove(path.join(TEST_CACHE_PATH, 'prosperAPI.json'))
        return

    with open(path.join(PROD_CACHE_PATH, 'prosperAPI.json'), 'r') as tdb_fh:
        raw_json = json.load(tdb_fh)

    collections = raw_json.keys()
    tdb = TinyMongoClient(PROD_CACHE_PATH)
    for collection in collections:
        if collection in SPECIAL_CACHE_COLLECTIONS:
            #skip special tables
            continue

        tdb.prosperAPI[collection].delete_many({})  #nuke it from orbit

    tdb.close()
Beispiel #8
0
    def main(self):
        """application runtime"""
        global LOGGER
        LOGGER = self.__log_builder.logger

        LOGGER.info('hello world')
        if not self.testkey:
            username = cli.terminal.readline(
                message='Username for key: '
            ).rstrip()
            id_info = cli.terminal.readline(
                message='Info about user: '******'travis_test_user'
            id_info = 'automated test key'

        LOGGER.info('making key for {0}:{1}'.format(username, id_info))
        
        # Connect to TinyMongoDB and use prosperAPI DB 
        connection = TinyMongoClient(CACHE_PATH)
        userdb = connection.prosperAPI.users
        # Attach to users collection

        current_key = userdb.find_one({'user_name': username })
        
        if current_key:
        
            key_msg = \
            'user already has a key' + \
            '\n\tapi_key={0}'.format(current_key['api_key']) + \
            '\n\tuser_name={0}'.format(current_key['user_name']) + \
            '\n\tuser_info={0}'.format(current_key['user_info']) + \
            '\n\tkey_generated={0}'.format(current_key['key_generated']) + \
            '\n\tlast_accessed={0}'.format(current_key['last_accessed'])
            
            print(key_msg)
            if not self.debug:
                LOGGER.info(key_msg)

            if not self.force:
                exit()

        if current_key and not self.debug:
            print("Delete Key")
            userdb.delete_one({'user_name': username})

        last_accessed = None
        
        if self.testkey:
            last_accessed = datetime.now().isoformat()
        api_key_entry = {
            'api_key': shortuuid.uuid(),
            'user_name': username,
            'user_info': id_info,
            'key_generated': datetime.now().isoformat(),
            'last_accessed': last_accessed
        }

        if not self.debug:
            userdb.insert_one(api_key_entry)

        check_key = userdb.find_one({'user_name': username})

        if self.debug:
            api_msg = 'Key generated for {0}: {1}'.format(username, api_key_entry['api_key'])
        else:
            api_msg = 'Key generated for {0}: {1}'.\
                format(check_key['user_name'], check_key['api_key'])
        connection.close()
        print(api_msg)
        if not self.debug:
            LOGGER.info(api_msg)