Debian Codegraph @

tests/test_passwordless.py

raw
1 """
2 test_passwordless
3 ~~~~~~~~~~~~~~~~~
4
5 Passwordless tests
6 """
7
8 from datetime import date, timedelta
9 import re
10 from urllib.parse import parse_qsl, urlsplit
11 import warnings
12
13 import pytest
14 from flask import Flask
15 from freezegun import freeze_time
16 from tests.test_utils import (
17 capture_flashes,
18 capture_passwordless_login_requests,
19 logout,
20 )
21
22 from flask_security import Security, UserMixin, login_instructions_sent
23
24 pytestmark = pytest.mark.passwordless()
25
26
27 def test_passwordless_flag(app, client, get_message, outbox):
28 recorded = []
29
30 @login_instructions_sent.connect_via(app)
31 def on_instructions_sent(app, user, login_token):
32 assert isinstance(app, Flask)
33 assert isinstance(user, UserMixin)
34 assert isinstance(login_token, str)
35 recorded.append(user)
36
37 # Test disabled account
38 response = client.post(
39 "/login", data=dict(email="[email protected]"), follow_redirects=True
40 )
41 assert get_message("DISABLED_ACCOUNT") in response.data
42
43 # Test login with json and valid email
44 data = dict(email="[email protected]")
45 response = client.post(
46 "/login", json=data, headers={"Content-Type": "application/json"}
47 )
48 assert response.status_code == 200
49 assert len(recorded) == 1
50 assert len(outbox) == 1
51
52 # Test login with json and invalid email
53 data = dict(email="[email protected]")
54 response = client.post(
55 "/login", json=data, headers={"Content-Type": "application/json"}
56 )
57 assert b"errors" in response.data
58
59 # Test sends email and shows appropriate response
60 with capture_passwordless_login_requests() as requests:
61 response = client.post(
62 "/login", data=dict(email="[email protected]"), follow_redirects=True
63 )
64
65 assert len(recorded) == 2
66 assert len(requests) == 1
67 assert len(outbox) == 2
68 assert "user" in requests[0]
69 assert "login_token" in requests[0]
70
71 user = requests[0]["user"]
72 assert get_message("LOGIN_EMAIL_SENT", email=user.email) in response.data
73
74 token = requests[0]["login_token"]
75 response = client.get("/login/" + token, follow_redirects=True)
76 assert get_message("PASSWORDLESS_LOGIN_SUCCESSFUL") in response.data
77
78 # Test already authenticated
79 response = client.get("/login/" + token, follow_redirects=True)
80 assert get_message("PASSWORDLESS_LOGIN_SUCCESSFUL") not in response.data
81
82 logout(client)
83
84 # Test invalid token
85 response = client.get("/login/bogus", follow_redirects=True)
86 assert get_message("INVALID_LOGIN_TOKEN") in response.data
87
88 # Test login request with invalid email
89 response = client.post("/login", data=dict(email="[email protected]"))
90 assert get_message("USER_DOES_NOT_EXIST") in response.data
91
92
93 def test_passwordless_template(app, client, get_message, outbox):
94 # Check contents of email template - this uses a test template
95 # in order to check all context vars since the default template
96 # doesn't have all of them.
97 with capture_passwordless_login_requests() as requests:
98 client.post("/login", data=dict(email="[email protected]"), follow_redirects=True)
99 assert len(outbox) == 1
100 matcher = re.findall(r"\w+:.*", outbox[0].body, re.IGNORECASE)
101 # should be 4 - link, email, token, config item
102 assert matcher[1].split(":")[1] == "[email protected]"
103 assert matcher[2].split(":")[1] == requests[0]["login_token"]
104 assert matcher[3].split(":")[1] == "True" # register_blueprint
105
106 # check link
107 link = matcher[0].split(":", 1)[1]
108 response = client.get(link, follow_redirects=True)
109 assert get_message("PASSWORDLESS_LOGIN_SUCCESSFUL") in response.data
110
111
112 @pytest.mark.settings(login_within="1 milliseconds")
113 def test_expired_login_token(client, app, get_message):
114 e = "[email protected]"
115 with capture_passwordless_login_requests() as requests:
116 # Note that we need relatively new-ish date since session cookies also expire.
117 with freeze_time(date.today() + timedelta(days=-1)):
118 client.post("/login", data=dict(email=e), follow_redirects=True)
119
120 token = requests[0]["login_token"]
121 user = requests[0]["user"]
122
123 response = client.get("/login/" + token, follow_redirects=True)
124 assert (
125 get_message("LOGIN_EXPIRED", within="1 milliseconds", email=user.email)
126 in response.data
127 )
128
129
130 @pytest.mark.settings(
131 redirect_host="localhost:8081",
132 redirect_behavior="spa",
133 post_login_view="/login-redirect",
134 )
135 def test_spa_get(app, client):
136 """
137 Test 'single-page-application' style redirects
138 This uses json only.
139 """
140 with capture_flashes() as flashes:
141 with capture_passwordless_login_requests() as requests:
142 response = client.post(
143 "/login",
144 json=dict(email="[email protected]"),
145 headers={"Content-Type": "application/json"},
146 )
147 assert response.headers["Content-Type"] == "application/json"
148 token = requests[0]["login_token"]
149
150 response = client.get("/login/" + token)
151 assert response.status_code in [302, 303]
152 split = urlsplit(response.headers["Location"])
153 assert "localhost:8081" == split.netloc
154 assert "/login-redirect" == split.path
155 qparams = dict(parse_qsl(split.query))
156 assert qparams["email"] == "[email protected]"
157 assert len(flashes) == 0
158
159
160 @pytest.mark.settings(
161 login_within="1 milliseconds",
162 redirect_host="localhost:8081",
163 redirect_behavior="spa",
164 login_error_view="/login-error",
165 )
166 def test_spa_get_bad_token(app, client, get_message):
167 """Test expired and invalid token"""
168 with capture_flashes() as flashes:
169 with capture_passwordless_login_requests() as requests:
170 # Note that we need relatively new-ish date since session cookies expire.
171 with freeze_time(date.today() + timedelta(days=-1)):
172 response = client.post(
173 "/login",
174 json=dict(email="[email protected]"),
175 headers={"Content-Type": "application/json"},
176 )
177 assert response.headers["Content-Type"] == "application/json"
178 token = requests[0]["login_token"]
179
180 response = client.get("/login/" + token)
181 assert response.status_code in [302, 303]
182 split = urlsplit(response.headers["Location"])
183 assert "localhost:8081" == split.netloc
184 assert "/login-error" == split.path
185 qparams = dict(parse_qsl(split.query))
186 assert all(k in qparams for k in ["email", "error", "identity"])
187
188 msg = get_message("LOGIN_EXPIRED", within="1 milliseconds", email="[email protected]")
189 assert msg == qparams["error"].encode("utf-8")
190
191 # Test mangled token
192 token = (
193 "WyIxNjQ2MzYiLCIxMzQ1YzBlZmVhM2VhZjYwODgwMDhhZGU2YzU0MzZjMiJd."
194 "BZEw_Q.lQyo3npdPZtcJ_sNHVHP103syjM"
195 "&url_id=fbb89a8328e58c181ea7d064c2987874bc54a23d"
196 )
197 response = client.get("/login/" + token)
198 assert response.status_code in [302, 303]
199 split = urlsplit(response.headers["Location"])
200 assert "localhost:8081" == split.netloc
201 assert "/login-error" == split.path
202 qparams = dict(parse_qsl(split.query))
203 assert len(qparams) == 1
204 assert all(k in qparams for k in ["error"])
205
206 msg = get_message("INVALID_LOGIN_TOKEN")
207 assert msg == qparams["error"].encode("utf-8")
208 assert len(flashes) == 0
209
210
211 def test_deprecated(app, sqlalchemy_datastore):
212 with warnings.catch_warnings(record=True) as w:
213 warnings.simplefilter("always")
214 security = Security()
215 security.init_app(app, sqlalchemy_datastore)
216 assert any("passwordless feature" in str(m.message) for m in w)
217
218
219 def _locked(self, form_error):
220 if self.email == "[email protected]":
221 form_error.append("You are not allowed to do that")
222 return True
223 return False
224
225
226 @pytest.mark.app_settings(TESTING_USER_INJECT=dict(is_locked=_locked))
227 def test_override_user_locked(app, client, get_message):
228 response = client.post("/login", json=dict(email="[email protected]"))
229 assert response.status_code == 400
230 assert response.json["response"]["errors"] == ["You are not allowed to do that"]
231 assert response.json["response"]["field_errors"]["email"] == [
232 "You are not allowed to do that"
233 ]