def create_account(registration_data):
    logger.debug('Creating account')
    url = f"{app.config['RAS_PARTY_SERVICE']}/party-api/v1/respondents"
    registration_data['status'] = 'CREATED'
    response = request_handler('POST',
                               url,
                               auth=app.config['BASIC_AUTH'],
                               json=registration_data)

    if response.status_code == 400:
        logger.debug('Email has already been used')
        raise ApiError(url=url, status_code=response.status_code)
    elif response.status_code != 200:
        logger.error('Failed to create account')
        raise ApiError(url=url, status_code=response.status_code)
def get_thread_message(encoded_jwt, thread_id, party_id):
    logger.debug('Attempting to retrieve thread message',
                 thread_id=thread_id,
                 party_id=party_id)
    method = 'GET'
    url = f"{app.config['RAS_SECURE_MESSAGE_SERVICE']}/thread/{thread_id}"
    headers = {"Authorization": encoded_jwt}
    response = request_handler(method, url, headers=headers)

    if response.status_code != 200:
        raise ApiError(url=url,
                       status_code=response.status_code,
                       description='Error retrieving the thread message',
                       thread_id=thread_id,
                       party_id=party_id)

    # Look for the last message in the thread not from the given party id
    thread = json.loads(response.text)
    for thread_message in thread['messages']:
        if thread_message['@msg_from']['id'] != party_id:
            message = thread_message
            break
    else:
        logger.debug('No message found in thread not belonging to the user',
                     thread_id=thread_id,
                     party_id=party_id)
        message = {}

    logger.debug('Retrieved message from thread successfully',
                 thread_id=thread_id,
                 party_id=party_id)
    return message
def get_iac_from_enrolment(enrolment_code):
    logger.debug('Retrieving IAC', enrolment_code=enrolment_code)
    url = f"{app.config['RM_IAC_SERVICE']}/iacs/{enrolment_code}"
    response = request_handler('GET', url, auth=app.config['BASIC_AUTH'])

    if response.status_code == 404:
        raise ApiError(url=url,
                       status_code=response.status_code,
                       description='IAC not found',
                       enrolment_code=enrolment_code)
    if response.status_code != 200:
        raise ApiError(url=url,
                       status_code=response.status_code,
                       description='Failed to retrieve IAC',
                       enrolment_code=enrolment_code)

    logger.debug('Successfully retrieved IAC', enrolment_code=enrolment_code)
    return json.loads(response.text)
def verify_email(token):
    logger.debug('Verifying email address', token=token)
    url = f"{app.config['RAS_PARTY_SERVICE']}/party-api/v1/emailverification/{token}"
    response = request_handler('PUT', url, auth=app.config['BASIC_AUTH'])

    if response.status_code != 200:
        logger.error('Failed to verify email address', token=token)
        raise ApiError(url=url, status_code=response.status_code)

    logger.debug('Successfully verified email address', token=token)
def get_party_by_respondent_id(party_id):
    logger.debug('Retrieving party', party_id=party_id)
    url = f"{app.config['RAS_PARTY_SERVICE']}/party-api/v1/respondents/id/{party_id}"
    response = request_handler('GET', url, auth=app.config['BASIC_AUTH'])

    if response.status_code != 200:
        logger.error('Failed to retrieve party', party_id=party_id)
        raise ApiError(url=url, status_code=response.status_code)

    logger.debug('Successfully retrieved party', party_id=party_id)
    return json.loads(response.text)
def get_collection_instrument(collection_instrument_id):
    logger.debug('Retrieving collection instrument',
                 collection_instrument_id=collection_instrument_id)
    url = f"{app.config['RAS_COLLECTION_INSTRUMENT_SERVICE']}/collection-instrument-api/1.0.2/collectioninstrument/id/{collection_instrument_id}"
    response = request_handler('GET', url, auth=app.config['BASIC_AUTH'])

    if response.status_code != 200:
        raise ApiError(url=url, status_code=response.status_code,
                       description='Failed to retrieve collection instrument',
                       collection_instrument_id=collection_instrument_id)
    return response.json()
def verify_token(token):
    logger.debug('Verifying token party')
    url = f"{app.config['RAS_PARTY_SERVICE']}/party-api/v1/tokens/verify/{token}"
    response = request_handler('GET', url, auth=app.config['BASIC_AUTH'])

    if response.status_code != 200:
        logger.error('Failed to verify token')
        raise ApiError(url=url, status_code=response.status_code)

    logger.debug('Successfully verified token')
    return json.loads(response.text)
Example #8
0
def get_case_categories():
    logger.debug('Retrieving case categories')
    url = f"{app.config['RM_CASE_SERVICE']}/categories"
    response = request_handler('GET', url, auth=app.config['BASIC_AUTH'])

    if response.status_code != 200:
        raise ApiError(url=url,
                       status_code=response.status_code,
                       description='Failed to retrieve case categories')

    logger.debug('Successfully retrieved case categories')
    return json.loads(response.text)
    def test_api_error_method_handler_no_status_code(self):
        error = ApiError('url', None, 'data', 'description')

        with self.app_context, self.app_request_context:
            with self.assertLogs() as cm:
                response, code = api_error_method(error)

        self.assertIn('ERROR', cm[1][0])
        self.assertIn('"status": null', cm[1][0])
        self.assertIn('"description"', cm[1][0])
        self.assertIn(b"error", response.data)
        self.assertIn(b"data", response.data)
        self.assertEqual(500, code)
def get_party_by_business_id(party_id, collection_exercise_id=None):
    logger.debug('Retrieving party', party_id=party_id)
    url = f"{app.config['RAS_PARTY_SERVICE']}/party-api/v1/businesses/id/{party_id}"
    if collection_exercise_id:
        url += f"?collection_exercise_id={collection_exercise_id}&verbose=True"
    response = request_handler('GET', url, auth=app.config['BASIC_AUTH'])

    if response.status_code != 200:
        logger.error('Failed to retrieve party', party_id=party_id)
        raise ApiError(url=url, status_code=response.status_code)

    logger.debug('Successfully retrieved party', party_id=party_id)
    return json.loads(response.text)
def reset_password_request(username):
    logger.debug('Sending reset password request party')
    post_data = {"email_address": username}
    url = f"{app.config['RAS_PARTY_SERVICE']}/party-api/v1/respondents/request_password_change"
    response = request_handler('POST',
                               url,
                               auth=app.config['BASIC_AUTH'],
                               json=post_data)

    if response.status_code != 200:
        logger.error('Failed to send reset password request party')
        raise ApiError(url=url, status_code=response.status_code)

    logger.debug('Successfully sent reset password request party')
    def test_api_error_method_handler_not_500(self):
        error = ApiError('url', 400, 'data', 'description', key='value')

        with self.app_context, self.app_request_context:
            with self.assertLogs() as cm:
                response, code = api_error_method(error)

        self.assertIn('INFO', cm[1][0])
        self.assertIn('"status": 400', cm[1][0])
        self.assertIn('"description"', cm[1][0])
        self.assertIn('"key": "value"', cm[1][0])
        self.assertIn(b"error", response.data)
        self.assertIn(b"data", response.data)
        self.assertEqual(400, code)
def add_survey(party_id, enrolment_code):
    logger.debug('Adding a survey')
    url = f"{app.config['RAS_PARTY_SERVICE']}/party-api/v1/respondents/add_survey"
    request_json = {"party_id": party_id, "enrolment_code": enrolment_code}
    response = request_handler('POST',
                               url,
                               auth=app.config['BASIC_AUTH'],
                               json=request_json)

    if response.status_code != 200:
        raise ApiError(url=url,
                       status_code=response.status_code,
                       description='Failed to add a survey')

    logger.debug('Successfully added a survey')
def upload_collection_instrument(upload_file, case_id, party_id):
    logger.info('Attempting to upload collection instrument', case_id=case_id)
    url = f"{app.config['RAS_COLLECTION_INSTRUMENT_SERVICE']}/survey_response-api/v1/survey_responses/{case_id}"
    response = request_handler('POST', url, auth=app.config['BASIC_AUTH'], files=upload_file)

    # Post relevant upload case event
    category = 'SUCCESSFUL_RESPONSE_UPLOAD' if response.status_code == 200 else 'UNSUCCESSFUL_RESPONSE_UPLOAD'
    case_controller.post_case_event(case_id,
                                    party_id=party_id,
                                    category=category,
                                    description=f'Survey response for case {case_id} uploaded by {party_id}')

    if response.status_code == 400:
        data = {
            'message': response.text
        }
        raise ApiError(url=url, status_code=response.status_code, data=data, description='Invalid file uploaded',
                       case_id=case_id)

    if response.status_code != 200:
        raise ApiError(url=url, status_code=response.status_code, description='Failed to upload collection instrument',
                       case_id=case_id)

    logger.debug('Successfully uploaded collection instrument', case_id=case_id)
Example #15
0
def get_collection_exercise(collection_exercise_id):
    logger.debug('Retrieving collection exercise',
                 collection_exercise_id=collection_exercise_id)
    url = f"{app.config['RM_COLLECTION_EXERCISE_SERVICE']}/collectionexercises/{collection_exercise_id}"
    response = request_handler('GET', url, auth=app.config['BASIC_AUTH'])

    if response.status_code != 200:
        raise ApiError(url=url,
                       status_code=response.status_code,
                       description='Failed to retrieve collection exercise',
                       collection_exercise_id=collection_exercise_id)

    logger.debug('Successfully retrieved collection exercise',
                 collection_exercise_id=collection_exercise_id)
    return response.json()
Example #16
0
def get_case_by_party_id(party_id, case_events=False):
    logger.debug('Retrieving case', party_id=party_id)
    url = f"{app.config['RM_CASE_SERVICE']}/cases/partyid/{party_id}"
    if case_events:
        url = f'{url}?caseevents=true'
    response = request_handler('GET', url, auth=app.config['BASIC_AUTH'])

    if response.status_code != 200:
        raise ApiError(url=url,
                       status_code=response.status_code,
                       description='Failed to retrieve case',
                       party_id=party_id)

    logger.debug('Successfully retrieved case', party_id=party_id)
    return json.loads(response.text)
def change_password(password, token):
    logger.debug('Changing password party')
    post_data = {"new_password": password}
    url = f"{app.config['RAS_PARTY_SERVICE']}/party-api/v1/respondents/change_password/{token}"
    response = request_handler('PUT',
                               url,
                               auth=app.config['BASIC_AUTH'],
                               json=post_data)

    if response.status_code != 200:
        raise ApiError(url=url,
                       status_code=response.status_code,
                       description='Failed to change password party')

    logger.debug('Successfully changed password party')
def download_collection_instrument(collection_instrument_id, case_id, party_id):
    logger.debug('Downloading collection instrument', collection_instrument_id=collection_instrument_id)
    url = f"{app.config['RAS_COLLECTION_INSTRUMENT_SERVICE']}/collection-instrument-api/1.0.2/download/{collection_instrument_id}"
    response = request_handler('GET', url, auth=app.config['BASIC_AUTH'])

    # Post relevant download case event
    category = 'COLLECTION_INSTRUMENT_DOWNLOADED' if response.status_code == 200 else 'COLLECTION_INSTRUMENT_ERROR'
    case_controller.post_case_event(case_id,
                                    party_id=party_id,
                                    category=category,
                                    description=f'Instrument {collection_instrument_id} downloaded by {party_id} for case {case_id}')

    if response.status_code != 200:
        raise ApiError(url=url, status_code=response.status_code,
                       description='Failed to download collection instrument',
                       collection_instrument_id=collection_instrument_id)

    logger.debug('Successfully downloaded collection instrument', collection_instrument_id=collection_instrument_id)
    return response.content, response.headers.items()
def send_message(encoded_jwt, message_json):
    logger.debug('Attempting to send message')
    headers = {"Authorization": encoded_jwt}
    url = f"{app.config['RAS_SECURE_MESSAGE_SERVICE']}/v2/messages"
    response = request_handler('POST', url, headers=headers, json=message_json)

    if response.status_code == 400:
        logger.debug('Form submitted with errors')
        form_errors = json.loads(response.text)
        return {"form_errors": form_errors}
    elif response.status_code != 201:
        raise ApiError(url=url,
                       status_code=response.status_code,
                       description='Failed to send message')

    message = json.loads(response.text)
    logger.info('Secure Message sent successfully',
                message_id=message['msg_id'])
    return message
Example #20
0
def request_handler(method, url, auth=None, headers=None, json=None, data=None, files=None, fail=True):
    try:
        if method == 'GET':
            response = requests.get(url, json=json, auth=auth, headers=headers)
        elif method == 'POST':
            response = requests.post(url, auth=auth, headers=headers, json=json, data=data, files=files)
        elif method == 'PUT':
            response = requests.put(url, auth=auth, headers=headers, json=json)
        else:
            logger.error('Invalid request method', method=str(method), url=url)
            raise InvalidRequestMethod(method, url)
    except ConnectionError:
        logger.exception('Failed to connect to external service', method=method, url=url)
        # If specified not to fail on this request just return False
        if fail:
            raise ApiError(url)
        else:
            return False

    return response
Example #21
0
def post_case_event(case_id, party_id, category, description):
    logger.debug('Posting case event', case_id=case_id)
    validate_case_category(category)
    url = f"{app.config['RM_CASE_SERVICE']}/cases/{case_id}/events"
    message = {
        'description': description,
        'category': category,
        'partyId': party_id,
        'createdBy': 'RAS_FRONTSTAGE_API'
    }
    response = request_handler('POST',
                               url,
                               auth=app.config['BASIC_AUTH'],
                               json=message)

    if response.status_code != 201:
        raise ApiError(url=url,
                       status_code=response.status_code,
                       description='Failed to post to case service',
                       case_id=case_id)
    logger.debug('Successfully posted case event', case_id=case_id)