diff --git a/app/main/views/invites.py b/app/main/views/invites.py index 0b31d5d98..b51c8836b 100644 --- a/app/main/views/invites.py +++ b/app/main/views/invites.py @@ -1,6 +1,7 @@ from flask import abort, flash, redirect, render_template, session, url_for from flask_login import current_user from markupsafe import Markup +from notifications_python_client.errors import HTTPError from app import ( invite_api_client, @@ -14,7 +15,14 @@ from app.main import main @main.route("/invitation/") def accept_invite(token): - invited_user = invite_api_client.check_token(token) + try: + invited_user = invite_api_client.check_token(token) + except HTTPError as e: + if e.status_code == 400 and 'invitation' in e.message: + flash(e.message['invitation']) + return redirect(url_for('main.sign_in')) + else: + raise e if not current_user.is_anonymous and current_user.email_address.lower() != invited_user.email_address.lower(): message = Markup(""" diff --git a/tests/app/main/views/test_accept_invite.py b/tests/app/main/views/test_accept_invite.py index 8f8efaa9d..d8e37182c 100644 --- a/tests/app/main/views/test_accept_invite.py +++ b/tests/app/main/views/test_accept_invite.py @@ -1,8 +1,10 @@ -from unittest.mock import ANY +from unittest.mock import ANY, Mock from bs4 import BeautifulSoup from flask import url_for +from notifications_python_client.errors import HTTPError from tests.conftest import mock_check_invite_token as mock_check_token_invite +from tests.conftest import normalize_spaces from tests.conftest import sample_invite as create_sample_invite import app @@ -215,6 +217,36 @@ def test_cancelled_invited_user_accepts_invited_redirect_to_cancelled_invitation assert page.h1.string.strip() == 'The invitation you were sent has been cancelled' +def test_new_user_accept_invite_with_malformed_token( + client, + service_one, + mocker, +): + mocker.patch('app.invite_api_client.check_token', side_effect=HTTPError( + response=Mock( + status_code=400, + json={ + 'result': 'error', + 'message': { + 'invitation': { + 'Something’s wrong with this link. Make sure you’ve copied the whole thing.' + } + } + } + ), + message={'invitation': 'Something’s wrong with this link. Make sure you’ve copied the whole thing.'} + )) + + response = client.get(url_for('main.accept_invite', token='thisisnotarealtoken'), follow_redirects=True) + + assert response.status_code == 200 + page = BeautifulSoup(response.data.decode('utf-8'), 'html.parser') + + assert normalize_spaces( + page.select_one('.banner-dangerous').text + ) == 'Something’s wrong with this link. Make sure you’ve copied the whole thing.' + + def test_new_user_accept_invite_completes_new_registration_redirects_to_verify( client, service_one,