Debian Codegraph @

tests/test_confirmable.py

raw
1 """
2 test_confirmable
3 ~~~~~~~~~~~~~~~~
4
5 Confirmable tests
6 """
7
8 from datetime import date, timedelta
9 import re
10 from urllib.parse import parse_qsl, urlsplit
11
12 import pytest
13 from flask import Flask
14 from freezegun import freeze_time
15 from wtforms.fields import StringField
16 from wtforms.validators import Length
17
18 from flask_security.core import Security, UserMixin
19 from flask_security.signals import confirm_instructions_sent, user_confirmed
20 from flask_security.forms import SendConfirmationForm
21
22 from tests.test_utils import (
23 authenticate,
24 capture_flashes,
25 capture_registrations,
26 check_location,
27 is_authenticated,
28 logout,
29 populate_data,
30 )
31
32 pytestmark = pytest.mark.confirmable()
33
34
35 @pytest.mark.registerable()
36 def test_confirmable_flag(app, clients, get_message):
37 recorded_confirms = []
38 recorded_instructions_sent = []
39
40 @user_confirmed.connect_via(app)
41 def on_confirmed(app, user):
42 assert isinstance(app, Flask)
43 assert isinstance(user, UserMixin)
44 recorded_confirms.append(user)
45
46 @confirm_instructions_sent.connect_via(app)
47 def on_instructions_sent(app, **kwargs):
48 assert isinstance(app, Flask)
49 assert isinstance(kwargs["user"], UserMixin)
50 assert isinstance(kwargs["token"], str)
51 assert isinstance(kwargs["confirmation_token"], str)
52 recorded_instructions_sent.append(kwargs["user"])
53
54 # Test login before confirmation
55 email = "[email protected]"
56
57 with capture_registrations() as registrations:
58 data = dict(
59 email=email,
60 password="awesome sunset",
61 password_confirm="awesome sunset",
62 next="",
63 )
64 response = clients.post("/register", data=data)
65
66 assert response.status_code in [302, 303]
67
68 response = authenticate(clients, email=email, password="awesome sunset")
69 assert get_message("CONFIRMATION_REQUIRED") in response.data
70
71 # Test invalid token
72 response = clients.get("/confirm/bogus", follow_redirects=True)
73 assert get_message("INVALID_CONFIRMATION_TOKEN") in response.data
74
75 # Test JSON
76 response = clients.post(
77 "/confirm",
78 json=dict(email="[email protected]"),
79 headers={"Content-Type": "application/json"},
80 )
81 assert response.status_code == 200
82 assert response.headers["Content-Type"] == "application/json"
83 assert "user" not in response.json["response"]
84 assert len(recorded_instructions_sent) == 1
85
86 # Test ask for instructions with invalid email
87 response = clients.post("/confirm", data=dict(email="[email protected]"))
88 assert get_message("USER_DOES_NOT_EXIST") in response.data
89
90 # Test resend instructions
91 response = clients.post("/confirm", data=dict(email=email))
92 assert get_message("CONFIRMATION_REQUEST", email=email) in response.data
93 assert len(recorded_instructions_sent) == 2
94
95 # Test confirm
96 token = registrations[0]["confirm_token"]
97 response = clients.get("/confirm/" + token, follow_redirects=False)
98 assert len(recorded_confirms) == 1
99 response = clients.get(response.location)
100 assert get_message("EMAIL_CONFIRMED") in response.data
101 # make sure not logged in
102 assert not is_authenticated(clients, get_message)
103
104 # Test already confirmed
105 response = clients.get("/confirm/" + token, follow_redirects=True)
106 assert get_message("ALREADY_CONFIRMED") in response.data
107 assert len(recorded_instructions_sent) == 2
108
109 # Test already confirmed when asking for confirmation instructions
110 response = clients.get("/confirm")
111 assert response.status_code == 200
112
113 response = clients.post("/confirm", data=dict(email=email))
114 assert get_message("ALREADY_CONFIRMED") in response.data
115
116 # Test if user was deleted before confirmation
117 with capture_registrations() as registrations:
118 data = dict(
119 email="[email protected]",
120 password="awesome sunset",
121 password_confirm="awesome sunset",
122 next="",
123 )
124 clients.post("/register", data=data)
125
126 user = registrations[0]["user"]
127 token = registrations[0]["confirm_token"]
128
129 with app.app_context():
130 app.security.datastore.delete(user)
131 app.security.datastore.commit()
132 if hasattr(app.security.datastore.db, "close_db") and callable(
133 app.security.datastore.db.close_db
134 ):
135 app.security.datastore.db.close_db(None)
136
137 response = clients.get("/confirm/" + token, follow_redirects=True)
138 assert get_message("INVALID_CONFIRMATION_TOKEN") in response.data
139
140
141 @pytest.mark.registerable()
142 @pytest.mark.settings(
143 email_template_confirm="security/email/confirmation_instructions_test",
144 email_html=False,
145 )
146 def test_confirmation_template(app, client, get_message, outbox):
147 # Check contents of email template - this uses a test template
148 # in order to check all context vars since the default template
149 # doesn't have all of them.
150
151 recorded_tokens_sent = []
152
153 @confirm_instructions_sent.connect_via(app)
154 def on_instructions_sent(app, **kwargs):
155 recorded_tokens_sent.append(kwargs["confirmation_token"])
156
157 with capture_registrations() as registrations:
158 data = dict(
159 email="[email protected]",
160 password="awesome sunset",
161 password_confirm="awesome sunset",
162 next="",
163 )
164 # Register - this will use the welcome template
165 client.post("/register", data=data, follow_redirects=True)
166 assert len(outbox) == 1
167 # check registration email
168 matcher = re.findall(r"\w+:.*", outbox[0].body, re.IGNORECASE)
169 # should be 4 - link, email, token, config item
170 assert matcher[1].split(":")[1] == "[email protected]"
171 assert matcher[2].split(":")[1] == registrations[0]["confirm_token"]
172 assert matcher[2].split(":")[1] == registrations[0]["confirmation_token"]
173 assert matcher[3].split(":")[1] == "True" # register_blueprint
174
175 # Explicitly ask for confirmation -
176 # this will use the confirmation_instructions template
177 client.post("/confirm", data=dict(email="[email protected]"))
178 # check confirmation email
179 matcher = re.findall(r"\w+:.*", outbox[1].body, re.IGNORECASE)
180 # should be 5 - link, email, token, config item, within
181 assert matcher[1].split(":")[1] == "[email protected]"
182 assert matcher[2].split(":")[1] == recorded_tokens_sent[0]
183 token = matcher[2].split(":")[1]
184 assert token == recorded_tokens_sent[0]
185 assert matcher[3].split(":")[1] == "True" # register_blueprint
186 assert matcher[4].split(":")[1] == "2 days" # within
187
188 # check link
189 _, link = matcher[0].split(":", 1)
190 response = client.get(link, follow_redirects=True)
191 assert get_message("EMAIL_CONFIRMED") in response.data
192
193 # regular text template is included in the test template
194 assert "This link will expire in 2 days." in outbox[1].body
195
196
197 @pytest.mark.registerable()
198 @pytest.mark.settings(requires_confirmation_error_view="/confirm")
199 def test_requires_confirmation_error_redirect(app, clients):
200 data = dict(
201 email="[email protected]", password="awesome sunset", password_confirm="awesome sunset"
202 )
203 response = clients.post("/register", data=data)
204
205 response = authenticate(
206 clients, email="[email protected]", password="awesome sunset", follow_redirects=True
207 )
208 assert b"send_confirmation_form" in response.data
209 assert b"[email protected]" in response.data
210
211
212 @pytest.mark.registerable()
213 @pytest.mark.settings(confirm_email_within="1 minutes")
214 @pytest.mark.filterwarnings("ignore:.*Non timedelta")
215 def test_expired_confirmation_token(client, get_message):
216 # Note that we need relatively new-ish date since session cookies also expire.
217 with freeze_time(date.today() + timedelta(days=-1)):
218 with capture_registrations() as registrations:
219 data = dict(
220 email="[email protected]",
221 password="awesome sunset",
222 password_confirm="awesome sunset",
223 next="",
224 )
225 client.post("/register", data=data, follow_redirects=True)
226
227 email = registrations[0]["email"]
228 token = registrations[0]["confirm_token"]
229
230 response = client.get("/confirm/" + token, follow_redirects=True)
231 msg = get_message("CONFIRMATION_EXPIRED", within="1 minute", email=email)
232 assert msg in response.data
233
234
235 @pytest.mark.registerable()
236 def test_email_conflict_for_confirmation_token(app, client, get_message):
237 with capture_registrations() as registrations:
238 data = dict(
239 email="[email protected]",
240 password="awesome sunset",
241 password_confirm="awesome sunset",
242 next="",
243 )
244 client.post("/register", data=data, follow_redirects=True)
245
246 user = registrations[0]["user"]
247 token = registrations[0]["confirm_token"]
248
249 # Change the user's email
250 user.email = "[email protected]"
251 with app.app_context():
252 app.security.datastore.put(user)
253 app.security.datastore.commit()
254
255 response = client.get("/confirm/" + token, follow_redirects=True)
256 msg = get_message("INVALID_CONFIRMATION_TOKEN")
257 assert msg in response.data
258
259
260 @pytest.mark.registerable()
261 @pytest.mark.settings(login_without_confirmation=True)
262 def test_login_when_unconfirmed(client, get_message):
263 data = dict(
264 email="[email protected]",
265 password="awesome sunset",
266 password_confirm="awesome sunset",
267 next="",
268 )
269 response = client.post("/register", data=data, follow_redirects=True)
270 assert b"[email protected]" in response.data
271
272
273 @pytest.mark.registerable()
274 @pytest.mark.settings(password_confirm_required=False)
275 def test_no_auth_token(client_nc):
276 """Make sure that register doesn't return Authentication Token
277 if user isn't confirmed.
278 """
279 response = client_nc.post(
280 "/register?include_auth_token",
281 json=dict(email="[email protected]", password="awesome sunset"),
282 headers={"Content-Type": "application/json"},
283 )
284 assert response.status_code == 200
285 user = response.json["response"]["user"]
286 assert len(user) == 2 and all(k in user for k in ["email", "last_update"])
287
288
289 @pytest.mark.registerable()
290 @pytest.mark.settings(login_without_confirmation=True, password_confirm_required=False)
291 def test_auth_token_unconfirmed(client_nc):
292 """Make sure that register returns Authentication Token
293 if user isn't confirmed, but the 'login_without_confirmation' flag is set.
294 """
295 response = client_nc.post(
296 "/register?include_auth_token",
297 json=dict(email="[email protected]", password="awesome sunset"),
298 headers={"Content-Type": "application/json"},
299 )
300 assert response.status_code == 200
301 user = response.json["response"]["user"]
302 assert len(user) == 3 and all(
303 k in user for k in ["email", "last_update", "authentication_token"]
304 )
305
306
307 @pytest.mark.registerable()
308 @pytest.mark.settings(
309 login_without_confirmation=True,
310 auto_login_after_confirm=False,
311 password_confirm_required=False,
312 )
313 def test_confirmation_different_user_when_logged_in_no_auto(client, get_message):
314 """Default - AUTO_LOGIN == false so shouldn't log in second user."""
315 e1 = "[email protected]"
316 e2 = "[email protected]"
317
318 with capture_registrations() as registrations:
319 for e in e1, e2:
320 data = dict(email=e, password="awesome sunset", next="")
321 client.post("/register", data=data)
322 logout(client)
323
324 token1 = registrations[0]["confirm_token"]
325 token2 = registrations[1]["confirm_token"]
326
327 client.get("/confirm/" + token1, follow_redirects=True)
328 logout(client)
329 authenticate(client, email=e1)
330
331 response = client.get("/confirm/" + token2, follow_redirects=True)
332 assert get_message("EMAIL_CONFIRMED") in response.data
333 # should get a login view
334 assert b'<a href="/login">Login</a>' in response.data
335
336
337 @pytest.mark.registerable()
338 @pytest.mark.settings(login_without_confirmation=True)
339 def test_confirmation_different_user_when_logged_in(client, get_message):
340 # with default no-auto-login - first user should get logged out and second
341 # should be properly confirmed (but not logged in)
342 e1 = "[email protected]"
343 e2 = "[email protected]"
344
345 with capture_registrations() as registrations:
346 for e in e1, e2:
347 data = dict(
348 email=e,
349 password="awesome sunset",
350 password_confirm="awesome sunset",
351 next="",
352 )
353 response = client.post("/register", data=data)
354 assert is_authenticated(client, get_message)
355 logout(client)
356
357 token1 = registrations[0]["confirm_token"]
358 token2 = registrations[1]["confirm_token"]
359
360 response = client.get("/confirm/" + token1, follow_redirects=False)
361 assert "/login" in response.location
362 authenticate(client, email=e1, password="awesome sunset")
363 assert is_authenticated(client, get_message)
364
365 response = client.get("/confirm/" + token2, follow_redirects=True)
366 assert get_message("EMAIL_CONFIRMED") in response.data
367
368 # first user should have been logged out
369 assert not is_authenticated(client, get_message)
370
371 authenticate(client, email=e2, password="awesome sunset")
372 assert is_authenticated(client, get_message)
373
374
375 @pytest.mark.registerable()
376 @pytest.mark.settings(recoverable=True, password_confirm_required=False)
377 def test_cannot_reset_password_when_email_is_not_confirmed(client, get_message):
378 email = "[email protected]"
379
380 data = dict(email=email, password="awesome sunset", next="")
381 response = client.post("/register", data=data, follow_redirects=True)
382
383 response = client.post("/reset", data=dict(email=email), follow_redirects=True)
384 assert get_message("CONFIRMATION_REQUIRED") in response.data
385
386
387 @pytest.mark.registerable()
388 @pytest.mark.settings(auto_login_after_confirm=False, password_confirm_required=False)
389 def test_confirm_redirect(client, get_message):
390 with capture_registrations() as registrations:
391 data = dict(email="[email protected]", password="awesome sunset", next="")
392 client.post("/register", data=data, follow_redirects=True)
393
394 token = registrations[0]["confirm_token"]
395
396 response = client.get("/confirm/" + token)
397 assert "location" in response.headers
398 assert "/login" in response.location
399
400 response = client.get(response.location)
401 assert get_message("EMAIL_CONFIRMED") in response.data
402
403
404 @pytest.mark.registerable()
405 @pytest.mark.settings(
406 post_confirm_view="/post_confirm", password_confirm_required=False
407 )
408 def test_confirm_redirect_to_post_confirm(client, get_message):
409 with capture_registrations() as registrations:
410 data = dict(email="[email protected]", password="awesome sunset", next="")
411 client.post("/register", data=data, follow_redirects=True)
412
413 token = registrations[0]["confirm_token"]
414
415 response = client.get("/confirm/" + token, follow_redirects=False)
416 assert "/post_confirm" in response.location
417
418
419 @pytest.mark.registerable()
420 @pytest.mark.settings(
421 redirect_host="localhost:8081",
422 redirect_behavior="spa",
423 post_confirm_view="/confirm-redirect",
424 confirm_error_view="/confirm-error",
425 password_confirm_required=False,
426 )
427 def test_spa_get(app, client, get_message):
428 """
429 Test 'single-page-application' style redirects
430 This uses json only.
431 """
432 with capture_flashes() as flashes:
433 with capture_registrations() as registrations:
434 response = client.post(
435 "/register",
436 json=dict(email="[email protected]", password="awesome sunset"),
437 headers={"Content-Type": "application/json"},
438 )
439 assert response.headers["Content-Type"] == "application/json"
440 token = registrations[0]["confirm_token"]
441
442 response = client.get("/confirm/" + token)
443 assert response.status_code in [302, 303]
444 split = urlsplit(response.headers["Location"])
445 assert "localhost:8081" == split.netloc
446 assert "/confirm-redirect" == split.path
447 qparams = dict(parse_qsl(split.query))
448 assert qparams["email"] == "[email protected]"
449
450 response = client.get("/confirm/" + token)
451 split = urlsplit(response.headers["Location"])
452 qparams = dict(parse_qsl(split.query))
453 assert response.status_code in [302, 303]
454 assert "/confirm-error" in response.location
455 assert "email" not in qparams
456 assert get_message("ALREADY_CONFIRMED") in qparams["info"].encode("utf-8")
457
458 # Arguably for json we shouldn't have any - this is buried in register_user
459 # but really shouldn't be.
460 assert len(flashes) == 1
461
462
463 @pytest.mark.registerable()
464 @pytest.mark.settings(
465 confirm_email_within=timedelta(minutes=300),
466 redirect_host="localhost:8081",
467 redirect_behavior="spa",
468 confirm_error_view="/confirm-error",
469 password_confirm_required=False,
470 )
471 def test_spa_get_bad_token(app, client, get_message):
472 """Test expired and invalid token"""
473 with capture_flashes() as flashes:
474 # Note that we need relatively new-ish date since session cookies also expire.
475 with freeze_time(date.today() + timedelta(days=-1)):
476 with capture_registrations() as registrations:
477 response = client.post(
478 "/register",
479 json=dict(email="[email protected]", password="awesome sunset"),
480 headers={"Content-Type": "application/json"},
481 )
482 assert response.headers["Content-Type"] == "application/json"
483 token = registrations[0]["confirm_token"]
484
485 response = client.get("/confirm/" + token)
486 assert response.status_code in [302, 303]
487 split = urlsplit(response.headers["Location"])
488 assert "localhost:8081" == split.netloc
489 assert "/confirm-error" == split.path
490 qparams = dict(parse_qsl(split.query))
491 assert "email" not in qparams
492 assert "identity" not in qparams
493
494 msg = get_message("CONFIRMATION_EXPIRED", within="5 hours")
495 assert msg == qparams["error"].encode("utf-8")
496
497 # Test mangled token
498 token = (
499 "WyIxNjQ2MzYiLCIxMzQ1YzBlZmVhM2VhZjYwODgwMDhhZGU2YzU0MzZjMiJd."
500 "BZEw_Q.lQyo3npdPZtcJ_sNHVHP103syjM"
501 "&url_id=fbb89a8328e58c181ea7d064c2987874bc54a23d"
502 )
503 response = client.get("/confirm/" + token)
504 assert response.status_code in [302, 303]
505 split = urlsplit(response.headers["Location"])
506 assert "localhost:8081" == split.netloc
507 assert "/confirm-error" == split.path
508 qparams = dict(parse_qsl(split.query))
509 assert len(qparams) == 1
510 assert all(k in qparams for k in ["error"])
511
512 msg = get_message("INVALID_CONFIRMATION_TOKEN")
513 assert msg == qparams["error"].encode("utf-8")
514 assert len(flashes) == 1
515
516
517 @pytest.mark.filterwarnings("ignore")
518 @pytest.mark.registerable()
519 @pytest.mark.settings(auto_login_after_confirm=True, post_login_view="/postlogin")
520 def test_auto_login(app, client, get_message):
521 with capture_registrations() as registrations:
522 data = dict(
523 email="[email protected]",
524 password="password",
525 password_confirm="password",
526 next="",
527 )
528 client.post("/register", data=data, follow_redirects=True)
529
530 assert not is_authenticated(client, get_message)
531
532 token = registrations[0]["confirm_token"]
533 response = client.get("/confirm/" + token, follow_redirects=False)
534 assert check_location(app, response.location, "/postlogin")
535 assert is_authenticated(client, get_message)
536
537
538 @pytest.mark.filterwarnings("ignore")
539 @pytest.mark.two_factor()
540 @pytest.mark.registerable()
541 @pytest.mark.settings(two_factor_required=True, auto_login_after_confirm=True)
542 def test_two_factor(app, client, get_message):
543 """If two-factor is enabled, the confirm shouldn't login, but start the
544 2-factor setup.
545 """
546 with capture_registrations() as registrations:
547 data = dict(
548 email="[email protected]",
549 password="password",
550 password_confirm="password",
551 next="",
552 )
553 client.post("/register", data=data, follow_redirects=True)
554
555 assert not is_authenticated(client, get_message)
556
557 token = registrations[0]["confirm_token"]
558 response = client.get("/confirm/" + token, follow_redirects=False)
559 assert "tf-setup" in response.location
560
561
562 @pytest.mark.filterwarnings("ignore")
563 @pytest.mark.two_factor()
564 @pytest.mark.registerable()
565 @pytest.mark.settings(two_factor_required=True, auto_login_after_confirm=True)
566 def test_two_factor_json(app, client, get_message):
567 with capture_registrations() as registrations:
568 data = dict(
569 email="[email protected]", password="password", password_confirm="password"
570 )
571 response = client.post("/register", content_type="application/json", json=data)
572 assert response.headers["content-type"] == "application/json"
573 assert response.json["meta"]["code"] == 200
574 assert len(response.json["response"]) == 2
575 assert all(k in response.json["response"] for k in ["csrf_token", "user"])
576
577 assert not is_authenticated(client, get_message)
578
579 token = registrations[0]["confirm_token"]
580 response = client.get("/confirm/" + token, headers={"Accept": "application/json"})
581
582 assert response.status_code == 200
583 assert response.json["response"]["tf_required"]
584 assert response.json["response"]["tf_state"] == "setup_from_login"
585
586
587 @pytest.mark.registerable()
588 @pytest.mark.settings(
589 user_identity_attributes=[{"username": {"mapper": lambda x: x}}],
590 username_enable=True,
591 password_confirm_required=False,
592 )
593 def test_email_not_identity(app, client, get_message):
594 # Test that can register/confirm with email even if it isn't an IDENTITY_ATTRIBUTE
595 with capture_registrations() as registrations:
596 data = dict(email="[email protected]", username="mary", password="awesome sunset")
597 response = client.post("/register", data=data, follow_redirects=True)
598 assert b"[email protected]" in response.data
599
600 token = registrations[0]["confirm_token"]
601 response = client.get("/confirm/" + token, headers={"Accept": "application/json"})
602 assert response.status_code in [302, 303]
603 assert not is_authenticated(client, get_message)
604
605 # check that username must be unique
606 data = dict(email="[email protected]", username="mary", password="awesome sunset")
607 response = client.post(
608 "/register", data=data, headers={"Accept": "application/json"}
609 )
610 assert response.status_code == 400
611 assert "is already associated" in response.json["response"]["errors"][0]
612
613 # verify that email field not present
614 response = client.get("/login") # this one has a flash containing 'email confirmed'
615 response = client.get("/login")
616 assert b"email" not in response.data
617 assert b"username" in response.data
618
619 response = client.get("/login", headers={"Content-Type": "application/json"})
620 assert response.json["response"]["identity_attributes"] == ["username"]
621
622 # log in with username
623 response = client.post(
624 "/login",
625 data=dict(username="mary", password="awesome sunset"),
626 follow_redirects=True,
627 )
628 assert b"<p>Welcome mary</p>" in response.data
629
630
631 @pytest.mark.settings(return_generic_responses=True)
632 def test_generic_response(app, client, get_message):
633 # Confirm matt - then an unknown email - both should get the same answer and
634 # JSON should return 200
635 recorded_instructions_sent = []
636
637 @confirm_instructions_sent.connect_via(app)
638 def on_instructions_sent(app, **kwargs):
639 recorded_instructions_sent.append(kwargs["token"])
640
641 response = client.post("/confirm", data=dict(email="[email protected]"))
642 assert len(recorded_instructions_sent) == 1
643 assert get_message("CONFIRMATION_REQUEST", email="[email protected]") in response.data
644 response = client.post("/confirm", json=dict(email="[email protected]"))
645 assert len(recorded_instructions_sent) == 2
646 assert response.status_code == 200
647
648 # actually confirm matt
649 token = recorded_instructions_sent[0]
650 response = client.get("/confirm/" + token, follow_redirects=True)
651 assert get_message("EMAIL_CONFIRMED") in response.data
652
653 # Try to confirm an unknown email - should get SAME message as real email.
654 response = client.post("/confirm", data=dict(email="[email protected]"))
655 assert len(recorded_instructions_sent) == 2
656 assert get_message("CONFIRMATION_REQUEST", email="[email protected]") in response.data
657 response = client.post("/confirm", json=dict(email="[email protected]"))
658 assert len(recorded_instructions_sent) == 2
659 assert response.status_code == 200
660 assert not any(e in response.json["response"].keys() for e in ["error", "errors"])
661
662 # Try to confirm matt again - should ALSO get same response.
663 response = client.post("/confirm", json=dict(email="[email protected]"))
664 assert len(recorded_instructions_sent) == 2
665 assert response.status_code == 200
666
667
668 def test_generic_with_extra(app, sqlalchemy_datastore):
669 # If application adds a field, make sure we properly return errors
670 # even if 'RETURN_GENERIC_RESPONSES' is set.
671 class MySendConfirmationForm(SendConfirmationForm):
672 recaptcha = StringField("Recaptcha", validators=[Length(min=5)])
673
674 app.config["SECURITY_RETURN_GENERIC_RESPONSES"] = True
675 app.config["SECURITY_SEND_CONFIRMATION_TEMPLATE"] = "generic_confirm.html"
676 app.security = Security(
677 app,
678 datastore=sqlalchemy_datastore,
679 send_confirmation_form=MySendConfirmationForm,
680 )
681
682 populate_data(app)
683 client = app.test_client()
684
685 # Test valid user but invalid additional form field
686 # We should get a form error for the extra (invalid) field, no flash
687 bad_data = dict(email="[email protected]", recaptcha="1234")
688 good_data = dict(email="[email protected]", recaptcha="123456")
689
690 with capture_flashes() as flashes:
691 response = client.post("/confirm", data=bad_data)
692 assert b"Field must be at least 5" in response.data
693 assert len(flashes) == 0
694 with capture_flashes() as flashes:
695 response = client.post("/confirm", data=good_data)
696 assert len(flashes) == 1
697
698 # JSON
699 with capture_flashes() as flashes:
700 response = client.post("/confirm", json=bad_data)
701 assert response.status_code == 400
702 assert (
703 "Field must be at least 5"
704 in response.json["response"]["field_errors"]["recaptcha"][0]
705 )
706 assert len(flashes) == 0
707 with capture_flashes() as flashes:
708 response = client.post("/confirm", json=good_data)
709 assert response.status_code == 200
710 assert len(flashes) == 0
711
712 # Try bad email AND bad recaptcha
713 bad_data = dict(email="joe44-lp.com", recaptcha="1234")
714 with capture_flashes() as flashes:
715 response = client.post("/confirm", data=bad_data)
716 assert b"Field must be at least 5" in response.data
717 assert len(flashes) == 0
718 with capture_flashes() as flashes:
719 response = client.post("/confirm", json=bad_data)
720 assert response.status_code == 400
721 assert (
722 "Field must be at least 5"
723 in response.json["response"]["field_errors"]["recaptcha"][0]
724 )
725 assert len(response.json["response"]["errors"]) == 1
726 assert len(flashes) == 0
727
728
729 @pytest.mark.flask_async()
730 @pytest.mark.registerable()
731 def test_confirmable_async(app, client, get_message):
732 recorded_confirms = []
733 recorded_instructions_sent = []
734
735 @user_confirmed.connect_via(app)
736 async def on_confirmed(myapp, user):
737 recorded_confirms.append(user)
738
739 @confirm_instructions_sent.connect_via(app)
740 async def on_instructions_sent(myapp, **kwargs):
741 recorded_instructions_sent.append(kwargs["user"])
742
743 email = "[email protected]"
744
745 with capture_registrations() as registrations:
746 data = dict(
747 email=email,
748 password="awesome sunset",
749 password_confirm="awesome sunset",
750 next="",
751 )
752 response = client.post("/register", data=data)
753 assert response.status_code in [302, 303]
754 client.post(
755 "/confirm",
756 json=dict(email=email),
757 headers={"Content-Type": "application/json"},
758 )
759 assert len(recorded_instructions_sent) == 1
760
761 # Test confirm
762 token = registrations[0]["confirm_token"]
763 client.get("/confirm/" + token, follow_redirects=False)
764 assert len(recorded_confirms) == 1