Debian Codegraph @

tests/test_change_username.py

raw
1 """
2 test_change_username
3 ~~~~~~~~~~~~~~~~~~~~
4
5 Change username tests
6
7 :copyright: (c) 2025-2025 by J. Christopher Wagner (jwag).
8 :license: MIT, see LICENSE for more details.
9 """
10
11 import pytest
12 from flask import Flask
13 import markupsafe
14
15 from flask_security import UsernameUtil, UserMixin, username_changed
16 from flask_security.forms import _default_field_labels
17 from flask_security.utils import localize_callback
18 from tests.test_utils import (
19 authenticate,
20 check_location,
21 check_xlation,
22 get_form_input_value,
23 init_app_with_options,
24 is_authenticated,
25 logout,
26 )
27
28 pytestmark = pytest.mark.change_username()
29
30
31 @pytest.mark.settings(
32 post_change_username_view="/post_change_username", username_enable=True
33 )
34 def test_cu(app, clients, get_message, outbox):
35 recorded = []
36
37 @username_changed.connect_via(app)
38 def on_username_changed(app, user, old_username):
39 assert isinstance(app, Flask)
40 assert isinstance(user, UserMixin)
41 recorded.append((user, old_username))
42
43 authenticate(clients)
44
45 # Test change view
46 response = clients.get("/change-username", follow_redirects=True)
47 assert b"Change Username" in response.data
48
49 # test length validation
50 response = clients.post(
51 "/change-username",
52 data={"username": "me"},
53 follow_redirects=True,
54 )
55 assert get_message("USERNAME_INVALID_LENGTH", min=4, max=32) in response.data
56
57 # Test successful submit sends email notification
58 response = clients.post(
59 "/change-username",
60 data={"username": "memynewusername"},
61 follow_redirects=True,
62 )
63
64 assert get_message("USERNAME_CHANGE") in response.data
65 assert b"Post Change Username" in response.data
66 assert len(recorded) == 1
67 assert len(outbox) == 1
68 assert "Your username has been changed" in outbox[0].body
69 response = clients.get("/change-username", follow_redirects=True)
70 assert b"memynewusername" in response.data
71
72 # authenticate with new username
73 logout(clients)
74 clients.post("/login", data=dict(username="memynewusername", password="password"))
75 assert is_authenticated(clients, get_message)
76
77 # Test same as previous
78 response = clients.post(
79 "/change-username",
80 data={"username": "memynewusername"},
81 follow_redirects=True,
82 )
83 assert (
84 get_message("USERNAME_ALREADY_ASSOCIATED", username="memynewusername")
85 in response.data
86 )
87
88 # since username isn't required - change it to nothing
89 response = clients.post(
90 "/change-username",
91 data={"username": ""},
92 follow_redirects=True,
93 )
94
95 assert get_message("USERNAME_CHANGE") in response.data
96 assert b"Post Change Username" in response.data
97 assert len(recorded) == 2
98 assert len(outbox) == 2
99 assert "Your username has been changed" in outbox[1].body
100
101 # shouldn't be able to log in with username
102 logout(clients)
103 clients.post("/login", data=dict(username="memynewusername", password="password"))
104 assert not is_authenticated(clients, get_message)
105
106
107 @pytest.mark.settings(
108 post_change_username_view="/post_change_username", username_enable=True
109 )
110 def test_cu_json(app, clients, get_message):
111 # Test JSON
112 recorded = []
113
114 @username_changed.connect_via(app)
115 def on_username_changed(app, user, old_username):
116 recorded.append((user, old_username))
117
118 response = clients.get("/change-username", content_type="application/json")
119 assert response.status_code == 401
120
121 authenticate(clients)
122 response = clients.get("/change-username", content_type="application/json")
123 assert response.json["response"]["current_username"] == "matt"
124
125 response = clients.post("/change-username", json={"username": "memyjsonusername"})
126 assert response.status_code == 200
127 assert response.headers["Content-Type"] == "application/json"
128 assert len(recorded) == 1
129 user, old = recorded[0]
130 assert old == "matt"
131
132 # Test JSON errors
133 response = clients.post("/change-username", json={"username": "my"})
134 assert response.status_code == 400
135 assert response.json["response"]["field_errors"]["username"] == [
136 "Username must be at least 4 characters and less than 32 characters"
137 ]
138
139 # authenticate with old username
140 logout(clients)
141 clients.post("/login", json=dict(username="matt", password="password"))
142 assert not is_authenticated(clients, get_message)
143
144 # authenticate with new username
145 logout(clients)
146 clients.post("/login", json=dict(username="memyjsonusername", password="password"))
147 assert is_authenticated(clients, get_message)
148
149
150 @pytest.mark.settings(username_enable=True, username_required=True)
151 def test_cu_required(app, client, get_message):
152 client.post("/login", json=dict(username="matt", password="password"))
153
154 response = client.post("/change-username", json={"username": ""})
155 assert (
156 get_message("USERNAME_NOT_PROVIDED")
157 == response.json["response"]["field_errors"]["username"][0].encode()
158 )
159
160
161 @pytest.mark.app_settings(babel_default_locale="fr_FR", SECURITY_CHANGEABLE=True)
162 @pytest.mark.babel()
163 def test_xlation(app, client, get_message_local, outbox):
164 # Test form and email translation
165 assert check_xlation(app, "fr_FR"), "You must run python setup.py compile_catalog"
166
167 authenticate(client)
168
169 response = client.get("/change", follow_redirects=True)
170 with app.test_request_context():
171 # Check header
172 assert b"<h1>Changer le mot de passe</h1>" in response.data
173 submit = localize_callback(_default_field_labels["change_password"])
174 assert f'value="{submit}"'.encode() in response.data
175
176 response = client.post(
177 "/change",
178 data={
179 "password": "password",
180 "new_password": "new strong password",
181 "new_password_confirm": "new strong password",
182 },
183 follow_redirects=True,
184 )
185
186 with app.test_request_context():
187 assert get_message_local("PASSWORD_CHANGE").encode("utf-8") in response.data
188 assert b"Home Page" in response.data
189 assert len(outbox) == 1
190 assert (
191 localize_callback(
192 app.config["SECURITY_EMAIL_SUBJECT_PASSWORD_CHANGE_NOTICE"]
193 )
194 in outbox[0].subject
195 )
196 assert (
197 str(markupsafe.escape(localize_callback("Your password has been changed.")))
198 in outbox[0].alts["html"]
199 )
200 assert localize_callback("Your password has been changed") in outbox[0].body
201
202
203 @pytest.mark.settings(change_username_url="/custom-change-username")
204 def test_custom_change_url(client):
205 authenticate(client)
206 response = client.get("/custom-change-username")
207 assert response.status_code == 200
208 assert b"Change Username" in response.data
209
210
211 @pytest.mark.settings(change_username_template="custom_security/change_username.html")
212 def test_custom_change_template(client):
213 authenticate(client)
214 response = client.get("/change-username")
215 assert b"CUSTOM CHANGE USERNAME" in response.data
216
217
218 @pytest.mark.settings(send_username_change_email=False)
219 def test_disable_change_emails(app, client, outbox):
220 authenticate(client)
221 response = client.post(
222 "/change-username",
223 json={"username": "mynewusername"},
224 follow_redirects=True,
225 )
226 assert response.status_code == 200
227 assert len(outbox) == 0
228
229
230 @pytest.mark.settings(post_change_username_view="/profile")
231 def test_custom_post_change_view(client):
232 authenticate(client)
233 response = client.post(
234 "/change-username",
235 data={"username": "mynewusername"},
236 follow_redirects=True,
237 )
238
239 assert b"Profile Page" in response.data
240
241
242 def test_my_validator(app, sqlalchemy_datastore):
243 class MyUsernameUtil(UsernameUtil):
244 def check_username(self, username):
245 if username == "nowayjose":
246 return "Are you crazy?"
247
248 init_app_with_options(
249 app,
250 sqlalchemy_datastore,
251 **{"security_args": {"username_util_cls": MyUsernameUtil}},
252 )
253 tcl = app.test_client()
254 authenticate(tcl)
255
256 response = tcl.post("/change-username", json=dict(username="nowayjose"))
257 assert response.status_code == 400
258 assert "Are you crazy" in response.json["response"]["errors"][0]
259
260
261 @pytest.mark.settings(username_enable=True)
262 def test_username_normalize(app, client):
263 """Verify that can log in with both original and normalized username"""
264 authenticate(client)
265 response = client.post(
266 "/change-username", json=dict(username="newusername\N{ROMAN NUMERAL ONE}")
267 )
268 assert response.status_code == 200
269 logout(client)
270
271 # use original typed-in username
272 response = client.post(
273 "/login",
274 json=dict(username="newusername\N{ROMAN NUMERAL ONE}", password="password"),
275 )
276 assert response.status_code == 200
277 logout(client)
278
279 # try with normalized username
280 response = client.post(
281 "/login",
282 json=dict(
283 username="newusername\N{LATIN CAPITAL LETTER I}",
284 password="password",
285 ),
286 )
287 assert response.status_code == 200
288
289
290 @pytest.mark.settings(username_normalize_form=None, username_enable=True)
291 def test_username_no_normalize(app, client):
292 """Verify that can log in with original but not normalized if have
293 disabled normalization
294 """
295 authenticate(client)
296 response = client.post(
297 "/change-username", json=dict(username="newusername\N{ROMAN NUMERAL ONE}")
298 )
299 assert response.status_code == 200
300 logout(client)
301
302 # try with normalized password - should fail
303 response = client.post(
304 "/login",
305 json=dict(
306 username="newusername\N{LATIN CAPITAL LETTER I}", password="password"
307 ),
308 )
309 assert response.status_code == 400
310
311 # use original typed-in username
312 response = client.post(
313 "/login",
314 json=dict(username="newusername\N{ROMAN NUMERAL ONE}", password="password"),
315 )
316 assert response.status_code == 200
317
318
319 @pytest.mark.csrf(ignore_unauth=True)
320 @pytest.mark.settings(post_change_username_view="/post_change_username_view")
321 def test_csrf(app, client):
322 # enable CSRF, make sure template shows CSRF errors.
323 authenticate(client)
324 data = {
325 "username": "mynewusername",
326 }
327 response = client.post("/change-username", data=data)
328 assert b"The CSRF token is missing" in response.data
329 # Note that we get a CSRF token EVEN for errors - this seems odd
330 # but can't find anything that says its a security issue
331 csrf_token = get_form_input_value(response, "csrf_token")
332
333 data["csrf_token"] = csrf_token
334 response = client.post("/change-username", data=data)
335 assert check_location(app, response.location, "/post_change_username_view")
336
337
338 @pytest.mark.csrf(ignore_unauth=True, csrfprotect=True)
339 def test_csrf_json(app, client):
340 # This tests the handle_csrf code path - especially the JSON code path
341 # that should return a JSON response!
342 authenticate(client)
343 response = client.post("/change-username", json=dict(username="mynewusername"))
344 assert response.status_code == 400
345 assert response.json["response"]["errors"][0] == "The CSRF token is missing."
346
347 response = client.get("/change-username", content_type="application/json")
348 csrf_token = response.json["response"]["csrf_token"]
349 response = client.post(
350 "/change-username",
351 json=dict(username="mynewusername"),
352 headers={"X-CSRF-Token": csrf_token},
353 )
354 assert response.status_code == 200