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=timedelta(days=1))
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 day", email=user.email) in response.data
126 )
127
128
129 @pytest.mark.settings(
130 redirect_host="localhost:8081",
131 redirect_behavior="spa",
132 post_login_view="/login-redirect",
133 )
134 def test_spa_get(app, client):
135 """
136 Test 'single-page-application' style redirects
137 This uses json only.
138 """
139 with capture_flashes() as flashes:
140 with capture_passwordless_login_requests() as requests:
141 response = client.post(
142 "/login",
143 json=dict(email="[email protected]"),
144 headers={"Content-Type": "application/json"},
145 )
146 assert response.headers["Content-Type"] == "application/json"
147 token = requests[0]["login_token"]
148
149 response = client.get("/login/" + token)
150 assert response.status_code in [302, 303]
151 split = urlsplit(response.headers["Location"])
152 assert "localhost:8081" == split.netloc
153 assert "/login-redirect" == split.path
154 qparams = dict(parse_qsl(split.query))
155 assert qparams["email"] == "[email protected]"
156 assert len(flashes) == 0
157
158
159 @pytest.mark.settings(
160 login_within=timedelta(seconds=73),
161 redirect_host="localhost:8081",
162 redirect_behavior="spa",
163 login_error_view="/login-error",
164 )
165 def test_spa_get_bad_token(app, client, get_message):
166 """Test expired and invalid token"""
167 with capture_flashes() as flashes:
168 with capture_passwordless_login_requests() as requests:
169 # Note that we need relatively new-ish date since session cookies expire.
170 with freeze_time(date.today() + timedelta(days=-1)):
171 response = client.post(
172 "/login",
173 json=dict(email="[email protected]"),
174 headers={"Content-Type": "application/json"},
175 )
176 assert response.headers["Content-Type"] == "application/json"
177 token = requests[0]["login_token"]
178
179 response = client.get("/login/" + token)
180 assert response.status_code in [302, 303]
181 split = urlsplit(response.headers["Location"])
182 assert "localhost:8081" == split.netloc
183 assert "/login-error" == split.path
184 qparams = dict(parse_qsl(split.query))
185 assert all(k in qparams for k in ["email", "error", "identity"])
186
187 msg = get_message(
188 "LOGIN_EXPIRED", within="1 minute and 13 seconds", email="[email protected]"
189 )
190 assert msg == qparams["error"].encode("utf-8")
191
192 # Test mangled token
193 token = (
194 "WyIxNjQ2MzYiLCIxMzQ1YzBlZmVhM2VhZjYwODgwMDhhZGU2YzU0MzZjMiJd."
195 "BZEw_Q.lQyo3npdPZtcJ_sNHVHP103syjM"
196 "&url_id=fbb89a8328e58c181ea7d064c2987874bc54a23d"
197 )
198 response = client.get("/login/" + token)
199 assert response.status_code in [302, 303]
200 split = urlsplit(response.headers["Location"])
201 assert "localhost:8081" == split.netloc
202 assert "/login-error" == split.path
203 qparams = dict(parse_qsl(split.query))
204 assert len(qparams) == 1
205 assert all(k in qparams for k in ["error"])
206
207 msg = get_message("INVALID_LOGIN_TOKEN")
208 assert msg == qparams["error"].encode("utf-8")
209 assert len(flashes) == 0
210
211
212 def test_deprecated(app, sqlalchemy_datastore):
213 with warnings.catch_warnings(record=True) as w:
214 warnings.simplefilter("always")
215 security = Security()
216 security.init_app(app, sqlalchemy_datastore)
217 assert any("passwordless feature" in str(m.message) for m in w)
218
219
220 def _locked(self, form_error):
221 if self.email == "[email protected]":
222 form_error.append("You are not allowed to do that")
223 return True
224 return False
225
226
227 @pytest.mark.app_settings(TESTING_USER_INJECT=dict(is_locked=_locked))
228 def test_override_user_locked(app, client, get_message):
229 response = client.post("/login", json=dict(email="[email protected]"))
230 assert response.status_code == 400
231 assert response.json["response"]["errors"] == ["You are not allowed to do that"]
232 assert response.json["response"]["field_errors"]["email"] == [
233 "You are not allowed to do that"
234 ]