Debian Codegraph @

tests/test_change_username.py

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