def _audit_title_viewed(title_number, username):
    # This puts something in our audit logs of what a user/ip address viewed at what time
    ip_address = utils.get_ip_address()
    date_and_time_viewed = datetime.now()
    auditing.audit(
        "VIEWED TITLE ON CONFIRM PAGE: Title number {0} was viewed by {3} on ip address {1} viewed on {2}"
        .format(title_number, ip_address, date_and_time_viewed, username))
def title_summary(encrypted_title_number):
    # On return from LRPI, the title number is unencrypted
    # In order to mask it from google analytics, we need to encrypt it and redirect the user on
    if len(encrypted_title_number) < 10:
        return redirect(
            url_for('title_summary',
                    encrypted_title_number=encryption_utils.encrypt(
                        encrypted_title_number),
                    **request.args))
    """Show title (result) if user is logged in, has paid and hasn't viewed before."""
    title_number = encryption_utils.decrypt(encrypted_title_number)
    LOGGER.debug(
        "STARTED: title_summary title_number: {0}".format(title_number))

    username = utils.username_from_header(request)
    trans_id = request.args.get('transid')
    search_term = request.args.get('search_term', title_number)

    params = _get_title_data(trans_id, username, title_number)

    auditing.audit("VIEW REGISTER: Title number {0} was viewed by {1}".format(
        title_number, username))

    LOGGER.debug("ENDED: title_summary")

    return render_template('display_title.html',
                           search_term=search_term,
                           encrypted_title_number=encrypted_title_number,
                           show_summary_map=app.config['SHOW_SUMMARY_MAP'],
                           **params)
def get_ip_address():
    ip_address_actual = request.headers.get("iv-remote-address", None)
    if ip_address_actual:
        auditing.audit("IP Address: {}".format(ip_address_actual))
    if ip_address_actual is None:
        auditing.audit("IP ADDRESS EMPTY")
    return ip_address_actual
def unlock_account(user_id):
    if db_access.update_failed_logins(user_id, 0):
        auditing.audit('Reset failed login attempts for user {}'.format(user_id))
        return Response(json.dumps({'reset': True}),
                        mimetype=JSON_CONTENT_TYPE)
    else:
        return USER_NOT_FOUND_RESPONSE
def _handle_locked_user_auth_request(user_id, failed_login_attempts):
    failed_login_attempts += 1

    auditing.audit('Too many bad logins. username: {}, attempt: {}.'.format(
        user_id, failed_login_attempts
    ))

    db_access.update_failed_logins(user_id, failed_login_attempts)
    return Response(AUTH_FAILURE_RESPONSE_BODY, status=401, mimetype=JSON_CONTENT_TYPE)
def delete_user(user_id):
    if db_access.delete_user(user_id):
        auditing.audit('Deleted user {}'.format(user_id))
        return Response(
            json.dumps({'deleted': True}),
            mimetype=JSON_CONTENT_TYPE
        )
    else:
        return USER_NOT_FOUND_RESPONSE
def find_titles_page(search_term=''):
    LOGGER.debug("STARTED: find_titles_page search_term: {}".format(search_term))
    display_page_number = int(request.args.get('page') or 1)
    page_number = display_page_number - 1  # page_number is 0 indexed
    username = _username_from_header(request)
    search_term = search_term.strip()
    if not search_term:
        LOGGER.debug("ENDED: find_titles_page")
        return _initial_search_page(request)
    else:
        message_format = "SEARCH REGISTER: '{0}' was searched by {1}"
        auditing.audit(message_format.format(search_term, username))
        LOGGER.debug("ENDED: find_titles_page search_term: {0}".format(search_term))
        return _get_address_search_response(search_term, page_number)
    def registration_successful(title_number, search_term):
        ip_address = utils.get_ip_address()
        auditing.audit("ACCOUNT CREATED: IP Address {0} ".format(ip_address))

        # If we've been redirected here from the account creation form, render the success message
        if request.referrer and url_for('create_account') in request.referrer:
            if title_number and search_term:
                return render_template(
                    'account/registration_successful.html',
                    title_number=encryption_utils.encrypt(title_number),
                    search_term=search_term)
            else:
                return render_template('account/registration_successful.html')

        # Otherwise the user has managed to arrive here "directly" such as via entering the url manually
        # In this situation we redirect them on to the search page
        return redirect(url_for('search'))
def _handle_allowed_user_auth_request(user_id, password, failed_login_attempts):
    password_salt = app.config['PASSWORD_SALT']
    password_hash = security.get_user_password_hash(user_id, password, password_salt)
    user = db_access.get_user(user_id, password_hash)

    if user:
        # Reset failed login attempts to zero and proceed
        db_access.update_failed_logins(user_id, 0)
        return Response(_authenticated_response_body(user), mimetype=JSON_CONTENT_TYPE)
    else:
        failed_login_attempts += 1
        db_access.update_failed_logins(user_id, failed_login_attempts)
        auditing.audit('Invalid credentials used. username: {}, attempt: {}.'.format(
            user_id, failed_login_attempts
        ))

        return Response(AUTH_FAILURE_RESPONSE_BODY, status=401, mimetype=JSON_CONTENT_TYPE)
def create_user():
    request_json = _try_get_request_json(request)
    if request_json and _is_create_request_data_valid(request_json):
        user = request_json['user']
        user_id = user['user_id']
        password = user['password']
        # TODO: common code
        password_hash = security.get_user_password_hash(
            user_id,
            password,
            app.config['PASSWORD_SALT']
        )
        if db_access.create_user(user_id, password_hash):
            auditing.audit('Created user {}'.format(user_id))
            return Response(json.dumps({'created': True}), mimetype=JSON_CONTENT_TYPE)
        else:
            response_body = json.dumps({'error': 'User already exists'})
            return Response(response_body, 409, mimetype=JSON_CONTENT_TYPE)
    else:
        return INVALID_REQUEST_RESPONSE
def update_user(user_id):
    request_json = _try_get_request_json(request)
    if request_json and _is_update_request_data_valid(request_json):
        new_password = request_json['user']['password']
        new_password_hash = security.get_user_password_hash(
            user_id,
            new_password,
            app.config['PASSWORD_SALT']
        )
        if db_access.update_user(
            user_id=user_id,
            password_hash=new_password_hash
        ):
            auditing.audit('Updated user {}'.format(user_id))
            return Response(
                json.dumps({'updated': True}),
                mimetype=JSON_CONTENT_TYPE
            )
        else:
            return USER_NOT_FOUND_RESPONSE
    else:
        return INVALID_REQUEST_RESPONSE
def get_title(title_number):
    """
    Show title (result) if user is logged in, has paid and hasn't viewed before.
    """
    LOGGER.debug("STARTED: get_title title_number: {0}".format(title_number))
    title = _get_register_title(title_number)
    username = _username_from_header(request)

    if title and _user_can_view(username, title_number):
        display_page_number = int(request.args.get('page') or 1)
        search_term = request.args.get('search_term', title_number)
        show_pdf = _should_show_full_title_pdf()
        full_title_data = (
            api_client.get_official_copy_data(title_number) if _should_show_full_title_data() else None
        )

        full_title_data = _strip_delimiters(full_title_data)

        LOGGER.debug("Title number{0}".format(title_number))
        auditing.audit("VIEW REGISTER: Title number {0} was viewed by {1}".format(
            title_number,
            username)
        )
        vat_json = {"date": 'N/A',
                    "address1": 'N/A',
                    "address2": 'N/A',
                    "address3": 'N/A',
                    "address4": 'N/A',
                    "postcode": 'N/A',
                    "title_number": 'N/A',
                    "net_amt": 0,
                    "vat_amt": 0,
                    "fee_amt": 0,
                    "vat_num": 'N/A'}

        transId = request.args.get('transid')
        if transId:
            receiptData = api_client.get_invoice_data(transId)
            receiptText = demjson.decode(receiptData.text)
            vat_json = demjson.decode(receiptText['vat_json'])

        receipt = {
            "trans_id": transId,
            "date": vat_json['date'],
            "address1": vat_json['address1'],
            "address2": vat_json['address2'],
            "address3": vat_json['address3'],
            "address4": vat_json['address4'],
            "postcode": vat_json['postcode'],
            "title_number": title_number,
            "net": "{0:.2f}".format(vat_json['net_amt']),
            "vat": "{0:.2f}".format(vat_json['vat_amt']),
            "total": "{0:.2f}".format(vat_json['fee_amt']),
            "reg_number": vat_json['vat_num']
        }

        LOGGER.debug("ENDED: get_title")

        return _title_details_page(title, search_term, show_pdf, full_title_data, request, receipt)

    else:
        LOGGER.debug("ENDED: get_title")
        abort(404)
def _handle_non_existing_user_auth_request(user_id):
    auditing.audit('Invalid credentials used. username: {}. User does not exist.'.format(user_id))
    return Response(AUTH_FAILURE_RESPONSE_BODY, status=401, mimetype=JSON_CONTENT_TYPE)