Debian Codegraph @

tests/test_change_email.py

raw
1 """
2 test_change_email
3 ~~~~~~~~~~~~~~~~~
4
5 Change email functionality tests
6
7 :copyright: (c) 2024-2026 by J. Christopher Wagner (jwag).
8 :license: MIT, see LICENSE for more details.
9 """
10
11 from contextlib import contextmanager
12 from datetime import date, timedelta
13 import re
14 from urllib.parse import urlsplit
15
16 import pytest
17 from freezegun import freeze_time
18 from tests.test_utils import (
19 authenticate,
20 capture_flashes,
21 is_authenticated,
22 json_authenticate,
23 logout,
24 )
25 from flask_security import hash_password
26 from flask_security.signals import (
27 change_email_instructions_sent,
28 change_email_confirmed,
29 )
30
31 pytestmark = pytest.mark.change_email()
32
33
34 @contextmanager
35 def capture_change_email_requests():
36 change_email_requests = []
37
38 def _on(app, **data):
39 change_email_requests.append(data)
40
41 change_email_instructions_sent.connect(_on)
42
43 try:
44 yield change_email_requests
45 finally:
46 change_email_instructions_sent.disconnect(_on)
47
48
49 @pytest.mark.settings(
50 change_email_error_view="/change-email", change_email_within=timedelta(seconds=67)
51 )
52 def test_ce(app, clients, get_message, outbox):
53 @change_email_confirmed.connect_via(app)
54 def _on(app, **kwargs):
55 assert kwargs["old_email"] == "[email protected]"
56 assert kwargs["user"].email == "[email protected]"
57
58 authenticate(clients, email="[email protected]")
59
60 with capture_change_email_requests() as ce_requests:
61 response = clients.post("/change-email", data={"email": "<EMAIL>"})
62 assert get_message("INVALID_EMAIL_ADDRESS") in response.data
63 assert len(outbox) == 0
64
65 response = clients.post("/change-email", data=dict(email="[email protected]"))
66 msg = get_message("CHANGE_EMAIL_SENT", email="[email protected]")
67 assert msg in response.data
68 assert "[email protected]" == ce_requests[0]["new_email"]
69 token = ce_requests[0]["token"]
70 assert len(outbox) == 1
71 assert "1 minute and 7 seconds" in outbox[0].body
72
73 response = clients.get("/change-email/" + token, follow_redirects=True)
74 assert get_message("CHANGE_EMAIL_CONFIRMED") in response.data
75 assert is_authenticated(clients, get_message)
76
77 logout(clients)
78 authenticate(clients, email="[email protected]")
79 assert is_authenticated(clients, get_message)
80
81 # try using link again - should fail
82 with capture_flashes() as flashes:
83 clients.get("/change-email/" + token, follow_redirects=True)
84 assert flashes[0]["message"].encode("utf-8") == get_message("API_ERROR")
85
86
87 def test_ce_json(app, client, get_message, outbox):
88 headers = {"Accept": "application/json", "Content-Type": "application/json"}
89
90 @change_email_confirmed.connect_via(app)
91 def _on(app, **kwargs):
92 assert kwargs["old_email"] == "[email protected]"
93 assert kwargs["user"].email == "[email protected]"
94
95 json_authenticate(client, email="[email protected]")
96
97 with capture_change_email_requests() as ce_requests:
98 response = client.post("/change-email", json={"email": "<EMAIL>"})
99 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
100 "INVALID_EMAIL_ADDRESS"
101 )
102 assert len(outbox) == 0
103
104 response = client.post("/change-email", json=dict(email="[email protected]"))
105 assert response.status_code == 200
106 assert response.json["response"]["current_email"] == "[email protected]"
107 assert "[email protected]" == ce_requests[0]["new_email"]
108 token = ce_requests[0]["token"]
109 assert len(outbox) == 1
110
111 response = client.get(
112 "/change-email/" + token, headers=headers, follow_redirects=True
113 )
114 assert get_message("CHANGE_EMAIL_CONFIRMED") in response.data
115 assert is_authenticated(client, get_message)
116
117 logout(client)
118 authenticate(client, email="[email protected]")
119 assert is_authenticated(client, get_message)
120
121
122 @pytest.mark.settings(
123 change_email_within=timedelta(minutes=36), change_email_error_view="/change-email"
124 )
125 def test_expired_token(client, get_message):
126 # Note that we need relatively new-ish date since session cookies also expire.
127 with freeze_time(date.today() + timedelta(days=-1)):
128 authenticate(client, email="[email protected]")
129 with capture_change_email_requests() as ce_requests:
130 client.post("/change-email", data=dict(email="[email protected]"))
131
132 assert "[email protected]" == ce_requests[0]["new_email"]
133 token = ce_requests[0]["token"]
134
135 response = client.get("/change-email/" + token, follow_redirects=True)
136 msg = get_message("CHANGE_EMAIL_EXPIRED", within="36 minutes")
137 assert msg in response.data
138
139
140 @pytest.mark.settings(
141 change_email_within=timedelta(minutes=90),
142 change_email_email_template="security/email/change_email_instructions_test",
143 email_html=False,
144 )
145 def test_template(app, client, get_message, outbox):
146 # Check contents of email template - this uses a test template
147 # to check all context vars since the default template
148 # doesn't have all of them.
149
150 authenticate(client, email="[email protected]")
151 with capture_change_email_requests() as ce_requests:
152 client.post("/change-email", data=dict(email="[email protected]"))
153 # check email
154 assert outbox[0].recipients[0] == "[email protected]"
155 matcher = re.findall(r"\w+:.*", outbox[0].body, re.IGNORECASE)
156 # should be 5 - link, email, token, config item, within
157 assert matcher[1].split(":")[1] == "[email protected]"
158 assert matcher[2].split(":")[1] == ce_requests[0]["token"]
159 assert matcher[3].split(":")[1] == "True" # register_blueprint
160 assert matcher[4].split(":")[1] == "1 hour and 30 minutes" # within
161 # entire original template is included in this test one
162 assert "This link will expire in 1 hour and 30 minutes." in outbox[0].body
163
164 # check link
165 _, link = matcher[0].split(":", 1)
166 response = client.get(link, follow_redirects=True)
167 assert get_message("CHANGE_EMAIL_CONFIRMED") in response.data
168
169
170 @pytest.mark.settings(
171 change_email_email_template="security/email/change_email_instructions_test",
172 email_html=False,
173 )
174 @pytest.mark.parametrize("humanizer", ["fr_FR"], indirect=["humanizer"])
175 def test_template_fr(app, client, get_message, outbox, humanizer):
176 # Check contents of email template - with humanize xlation of within
177 authenticate(client, email="[email protected]")
178 with capture_change_email_requests():
179 client.post("/change-email", data=dict(email="[email protected]"))
180 # check email
181 assert outbox[0].recipients[0] == "[email protected]"
182 matcher = re.findall(r"\w+:.*", outbox[0].body, re.IGNORECASE)
183 assert matcher[4].split(":")[1] == "2 heures"
184
185
186 @pytest.mark.settings(return_generic_responses=True)
187 def test_generic_response(app, client, get_message, outbox):
188 authenticate(client, email="[email protected]")
189 with capture_change_email_requests():
190 # first try bad formatted email - should get detailed error
191 response = client.post("/change-email", json={"email": "<EMAIL>"})
192 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
193 "INVALID_EMAIL_ADDRESS"
194 )
195
196 # try existing email - should get same response as if it 'worked'
197 response = client.post("/change-email", data=dict(email="[email protected]"))
198 msg = get_message("CHANGE_EMAIL_SENT", email="[email protected]")
199 assert msg in response.data
200 # but no email was actually sent
201 assert len(outbox) == 0
202
203
204 @pytest.mark.settings(
205 redirect_host="myui.com:8090",
206 redirect_behavior="spa",
207 post_change_email_view="/change-email-redirect",
208 change_email_error_view="/change-email-error",
209 )
210 def test_spa_get(app, client, get_message):
211 json_authenticate(client, email="[email protected]")
212
213 with capture_change_email_requests() as ce_requests:
214 response = client.post("/change-email", data=dict(email="[email protected]"))
215 msg = get_message("CHANGE_EMAIL_SENT", email="[email protected]")
216 assert msg in response.data
217 assert "[email protected]" == ce_requests[0]["new_email"]
218 token = ce_requests[0]["token"]
219 response = client.get("/change-email/" + token, follow_redirects=False)
220 assert response.status_code in [302, 303]
221 split = urlsplit(response.headers["Location"])
222 assert "myui.com:8090" == split.netloc
223 assert "/change-email-redirect" == split.path
224
225 # again - should be an error
226 response = client.get("/change-email/" + token, follow_redirects=False)
227 assert response.status_code in [302, 303]
228 split = urlsplit(response.headers["Location"])
229 assert "myui.com:8090" == split.netloc
230 assert "/change-email-error" == split.path
231
232
233 @pytest.mark.settings(change_email_error_view="/change-email")
234 def test_ce_race(app, client, get_message):
235 # test that if an email is taken between the link being sent and
236 # the user confirming - they get an error
237
238 authenticate(client, email="[email protected]")
239
240 with capture_change_email_requests() as ce_requests:
241 client.post("/change-email", data=dict(email="[email protected]"))
242 token = ce_requests[0]["token"]
243
244 with app.app_context():
245 app.security.datastore.create_user(
246 email="[email protected]",
247 password=hash_password("password"),
248 )
249 app.security.datastore.commit()
250 with capture_flashes() as flashes:
251 client.get("/change-email/" + token, follow_redirects=True)
252 assert flashes[0]["message"].encode("utf-8") == get_message("API_ERROR")