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