Debian Codegraph @

tests/apps/headless/socialaccount/test_views.py

raw
1 import json
2 from http import HTTPStatus
3 from unittest.mock import patch
4
5 from django.urls import reverse
6
7 from pytest_django.asserts import assertTemplateUsed
8
9 from allauth.account.models import EmailAddress
10 from allauth.socialaccount.adapter import get_adapter
11 from allauth.socialaccount.models import SocialAccount
12 from allauth.socialaccount.providers.base.constants import AuthProcess
13
14
15 def test_bad_redirect(client, headless_reverse, db, settings):
16 settings.HEADLESS_ONLY = False
17 resp = client.post(
18 headless_reverse("headless:socialaccount:redirect_to_provider"),
19 data={
20 "provider": "dummy",
21 "callback_url": "https://unsafe.org/hack",
22 "process": AuthProcess.LOGIN,
23 },
24 )
25 assertTemplateUsed(resp, "socialaccount/authentication_error.html")
26
27
28 def test_valid_redirect(client, headless_reverse, db):
29 resp = client.post(
30 headless_reverse("headless:socialaccount:redirect_to_provider"),
31 data={
32 "provider": "dummy",
33 "callback_url": "/",
34 "process": AuthProcess.LOGIN,
35 },
36 )
37 assert resp.status_code == HTTPStatus.FOUND
38
39
40 def test_unknown_provider_redirect(client, headless_reverse, db, settings):
41 resp = client.post(
42 headless_reverse("headless:socialaccount:redirect_to_provider"),
43 data={
44 "provider": "unknown",
45 "callback_url": "/",
46 "process": AuthProcess.LOGIN,
47 },
48 )
49 if getattr(settings, "HEADLESS_ONLY", False):
50 assert resp.status_code == HTTPStatus.FOUND
51 else:
52 assert resp.status_code == HTTPStatus.UNAUTHORIZED
53
54
55 def test_manage_providers(auth_client, user, headless_reverse, provider_id):
56 account_to_del = SocialAccount.objects.create(
57 user=user, provider=provider_id, uid="p123"
58 )
59 account_to_keep = SocialAccount.objects.create(
60 user=user, provider=provider_id, uid="p456"
61 )
62 resp = auth_client.get(
63 headless_reverse("headless:socialaccount:manage_providers"),
64 )
65 data = resp.json()
66 assert data["status"] == HTTPStatus.OK
67 assert len(data["data"]) == 2
68 resp = auth_client.delete(
69 headless_reverse("headless:socialaccount:manage_providers"),
70 data={"provider": account_to_del.provider, "account": account_to_del.uid},
71 content_type="application/json",
72 )
73 assert resp.status_code == HTTPStatus.OK
74 assert resp.json() == {
75 "status": HTTPStatus.OK,
76 "data": [
77 {
78 "display": "Unittest Server",
79 "provider": {
80 "client_id": "Unittest client_id",
81 "openid_configuration_url": "https://unittest.example.com/.well-known/openid-configuration",
82 "flows": ["provider_redirect", "provider_token"],
83 "id": provider_id,
84 "name": "Unittest Server",
85 },
86 "uid": "p456",
87 }
88 ],
89 }
90 assert not SocialAccount.objects.filter(pk=account_to_del.pk).exists()
91 assert SocialAccount.objects.filter(pk=account_to_keep.pk).exists()
92
93
94 def test_disconnect_bad_request(auth_client, user, headless_reverse, provider_id):
95 resp = auth_client.delete(
96 headless_reverse("headless:socialaccount:manage_providers"),
97 data={"provider": provider_id, "account": "unknown"},
98 content_type="application/json",
99 )
100 assert resp.status_code == HTTPStatus.BAD_REQUEST
101 assert resp.json() == {
102 "status": HTTPStatus.BAD_REQUEST,
103 "errors": [{"code": "account_not_found", "message": "Unknown account."}],
104 }
105
106
107 def test_disconnect_not_allowed(auth_client, user, headless_reverse, provider_id):
108 user.set_unusable_password()
109 user.save(update_fields=["password"])
110 auth_client.force_login(user)
111 account = SocialAccount.objects.create(user=user, uid="123", provider=provider_id)
112 resp = auth_client.delete(
113 headless_reverse("headless:socialaccount:manage_providers"),
114 data={"provider": provider_id, "account": account.uid},
115 content_type="application/json",
116 )
117 assert resp.status_code == HTTPStatus.BAD_REQUEST
118 assert resp.json() == {
119 "status": HTTPStatus.BAD_REQUEST,
120 "errors": [
121 {"code": "no_password", "message": "Your account has no password set up."}
122 ],
123 }
124
125
126 def test_valid_token(client, headless_reverse, db):
127 id_token = json.dumps(
128 {
129 "id": 123,
130 "email": "[email protected]",
131 "email_verified": True,
132 }
133 )
134 resp = client.post(
135 headless_reverse("headless:socialaccount:provider_token"),
136 data={
137 "provider": "dummy",
138 "token": {
139 "id_token": id_token,
140 },
141 "process": AuthProcess.LOGIN,
142 },
143 content_type="application/json",
144 )
145 assert resp.status_code == HTTPStatus.OK
146 assert EmailAddress.objects.filter(email="[email protected]", verified=True).exists()
147
148
149 def test_invalid_token(client, headless_reverse, db, google_provider_settings):
150 resp = client.post(
151 headless_reverse("headless:socialaccount:provider_token"),
152 data={
153 "provider": "google",
154 "token": {
155 "id_token": "dummy",
156 "client_id": google_provider_settings["APPS"][0]["client_id"],
157 },
158 "process": AuthProcess.LOGIN,
159 },
160 content_type="application/json",
161 )
162 assert resp.status_code == HTTPStatus.BAD_REQUEST
163 data = resp.json()
164 assert data == {
165 "status": HTTPStatus.BAD_REQUEST,
166 "errors": [
167 {"message": "Invalid token.", "code": "invalid_token", "param": "token"}
168 ],
169 }
170
171
172 def test_valid_token_multiple_apps(
173 client, headless_reverse, db, google_provider_settings, settings, user_factory
174 ):
175 settings.ACCOUNT_EMAIL_VERIFICATION = "mandatory"
176 google_provider_settings["APPS"].append(
177 {"client_id": "client_id2", "secret": "secret2"}
178 )
179 id_token = {"sub": "uid-from-id-token", "email": "[email protected]", "email_verified": True}
180 with patch(
181 "allauth.socialaccount.providers.google.views._verify_and_decode",
182 return_value=id_token,
183 ):
184 resp = client.post(
185 headless_reverse("headless:socialaccount:provider_token"),
186 data={
187 "provider": "google",
188 "token": {
189 "id_token": "dummy",
190 "client_id": google_provider_settings["APPS"][0]["client_id"],
191 },
192 "process": AuthProcess.LOGIN,
193 },
194 content_type="application/json",
195 )
196 assert resp.status_code == HTTPStatus.OK
197
198
199 def test_auth_error_no_headless_request(client, db, google_provider_settings, settings):
200 """Authentication errors use the regular "Third-Party Login Failure"
201 template if headless is not used.
202 """
203 settings.HEADLESS_ONLY = False
204 resp = client.get(reverse("google_callback"))
205 assertTemplateUsed(resp, "socialaccount/authentication_error.html")
206
207
208 def test_auth_error_headless_request(
209 client, db, google_provider_settings, sociallogin_setup_state
210 ):
211 """Authentication errors redirect to the next URL with ?error params for
212 headless requests.
213 """
214 state = sociallogin_setup_state(client, headless=True, next="/foo")
215 resp = client.get(f"{reverse('google_callback')}?state={state}")
216 assert resp["location"] == "/foo?error=unknown&error_process=login"
217
218
219 def test_auth_error_no_headless_state_request_headless_only(
220 settings, client, db, google_provider_settings
221 ):
222 """Authentication errors redirect to a fallback error URL for headless-only,
223 in case no next can be recovered from the state.
224 """
225 settings.HEADLESS_ONLY = True
226 settings.HEADLESS_FRONTEND_URLS = {"socialaccount_login_error": "/3rdparty/failure"}
227 resp = client.get(reverse("google_callback"))
228 assert (
229 resp["location"]
230 == "http://testserver/3rdparty/failure?error=unknown&error_process=login"
231 )
232
233
234 def test_auth_error_headless_state_request_headless_only(
235 settings, client, db, google_provider_settings, sociallogin_setup_state
236 ):
237 """Authentication errors redirect to a fallback error URL for headless-only,
238 in case no next can be recovered from the state.
239 """
240 state = sociallogin_setup_state(client, headless=True, next="/foo")
241 settings.HEADLESS_ONLY = True
242 settings.HEADLESS_FRONTEND_URLS = {"socialaccount_login_error": "/3rdparty/failure"}
243 resp = client.get(f"{reverse('google_callback')}?state={state}")
244 assert resp["location"] == "/foo?error=unknown&error_process=login"
245
246
247 def test_token_signup_closed(client, headless_reverse, db):
248 id_token = json.dumps(
249 {
250 "id": 123,
251 "email": "[email protected]",
252 "email_verified": True,
253 }
254 )
255 with patch(
256 "allauth.socialaccount.adapter.DefaultSocialAccountAdapter.is_open_for_signup"
257 ) as iofs:
258 iofs.return_value = False
259 resp = client.post(
260 headless_reverse("headless:socialaccount:provider_token"),
261 data={
262 "provider": "dummy",
263 "token": {
264 "id_token": id_token,
265 },
266 "process": AuthProcess.LOGIN,
267 },
268 content_type="application/json",
269 )
270 assert resp.status_code == HTTPStatus.FORBIDDEN
271 assert not EmailAddress.objects.filter(email="[email protected]", verified=True).exists()
272
273
274 def test_provider_signup(client, headless_reverse, db, settings):
275 settings.ACCOUNT_EMAIL_VERIFICATION = "mandatory"
276 settings.ACCOUNT_EMAIL_REQUIRED = True
277 settings.ACCOUNT_USERNAME_REQUIRED = False
278 account_uid = "123"
279 id_token = json.dumps(
280 {
281 "id": account_uid,
282 }
283 )
284 resp = client.post(
285 headless_reverse("headless:socialaccount:provider_token"),
286 data={
287 "provider": "dummy",
288 "token": {
289 "id_token": id_token,
290 },
291 "process": AuthProcess.LOGIN,
292 },
293 content_type="application/json",
294 )
295 assert resp.status_code == HTTPStatus.UNAUTHORIZED
296 pending_flow = [f for f in resp.json()["data"]["flows"] if f.get("is_pending")][0]
297 assert pending_flow["id"] == "provider_signup"
298
299 resp = client.get(headless_reverse("headless:socialaccount:provider_signup"))
300 assert resp.status_code == HTTPStatus.OK
301 assert resp.json() == {
302 "data": {
303 "email": [],
304 "account": {
305 "display": "Dummy",
306 "provider": {
307 "flows": ["provider_redirect", "provider_token"],
308 "id": "dummy",
309 "name": "Dummy",
310 },
311 "uid": account_uid,
312 },
313 "user": {"display": "user", "has_usable_password": False},
314 },
315 "status": HTTPStatus.OK,
316 }
317
318 resp = client.post(
319 headless_reverse("headless:socialaccount:provider_signup"),
320 data={
321 "email": "[email protected]",
322 },
323 content_type="application/json",
324 )
325 assert resp.status_code == HTTPStatus.UNAUTHORIZED
326 pending_flow = [f for f in resp.json()["data"]["flows"] if f.get("is_pending")][0]
327 assert pending_flow["id"] == "verify_email"
328 assert EmailAddress.objects.filter(email="[email protected]").exists()
329
330
331 def test_signup_closed(client, headless_reverse, db, settings):
332 settings.ACCOUNT_EMAIL_VERIFICATION = "mandatory"
333 settings.ACCOUNT_EMAIL_REQUIRED = True
334 settings.ACCOUNT_USERNAME_REQUIRED = False
335 id_token = json.dumps(
336 {
337 "id": 123,
338 }
339 )
340 resp = client.post(
341 headless_reverse("headless:socialaccount:provider_token"),
342 data={
343 "provider": "dummy",
344 "token": {
345 "id_token": id_token,
346 },
347 "process": AuthProcess.LOGIN,
348 },
349 content_type="application/json",
350 )
351 assert resp.status_code == HTTPStatus.UNAUTHORIZED
352 pending_flow = [f for f in resp.json()["data"]["flows"] if f.get("is_pending")][0]
353 assert pending_flow["id"] == "provider_signup"
354 with patch(
355 "allauth.socialaccount.adapter.DefaultSocialAccountAdapter.is_open_for_signup"
356 ) as iofs:
357 iofs.return_value = False
358 resp = client.post(
359 headless_reverse("headless:socialaccount:provider_signup"),
360 data={
361 "email": "[email protected]",
362 },
363 content_type="application/json",
364 )
365 assert resp.status_code == HTTPStatus.FORBIDDEN
366
367
368 def test_connect(user, auth_client, sociallogin_setup_state, headless_reverse, db):
369 state = sociallogin_setup_state(
370 auth_client, process="connect", next="/foo", headless=True
371 )
372 resp = auth_client.post(
373 f"{reverse('dummy_authenticate')}?state={state}",
374 data={
375 "id": 123,
376 },
377 )
378 assert resp.status_code == HTTPStatus.FOUND
379 assert resp["location"] == "/foo"
380 assert SocialAccount.objects.filter(user=user, provider="dummy", uid="123").exists()
381
382
383 def test_connect_reauthentication_required(
384 user, auth_client, sociallogin_setup_state, headless_reverse, db, settings
385 ):
386 settings.ACCOUNT_REAUTHENTICATION_REQUIRED = True
387
388 state = sociallogin_setup_state(
389 auth_client, process="connect", next="/foo", headless=True
390 )
391 resp = auth_client.post(
392 f"{reverse('dummy_authenticate')}?state={state}",
393 data={
394 "id": 123,
395 },
396 )
397 assert resp.status_code == HTTPStatus.FOUND
398 assert (
399 resp["location"] == "/foo?error=reauthentication_required&error_process=connect"
400 )
401
402
403 def test_connect_already_connected(
404 user, user_factory, auth_client, sociallogin_setup_state, headless_reverse, db
405 ):
406 # The other user already connected the account.
407 other_user = user_factory()
408 SocialAccount.objects.create(user=other_user, uid="123", provider="dummy")
409 # Then, this user tries to connect...
410 state = sociallogin_setup_state(
411 auth_client, process=AuthProcess.CONNECT, next="/foo", headless=True
412 )
413 resp = auth_client.post(
414 f"{reverse('dummy_authenticate')}?state={state}",
415 data={
416 "id": 123,
417 },
418 )
419 # We're redirected, and an error code is shown.
420 assert resp.status_code == HTTPStatus.FOUND
421 assert resp["location"] == "/foo?error=connected_other&error_process=connect"
422 assert not SocialAccount.objects.filter(
423 user=user, provider="dummy", uid="123"
424 ).exists()
425
426
427 def test_token_connect(user, auth_client, headless_reverse, db):
428 id_token = json.dumps(
429 {
430 "id": 123,
431 "email": "[email protected]",
432 "email_verified": True,
433 }
434 )
435 resp = auth_client.post(
436 headless_reverse("headless:socialaccount:provider_token"),
437 data={
438 "provider": "dummy",
439 "token": {
440 "id_token": id_token,
441 },
442 "process": AuthProcess.CONNECT,
443 },
444 content_type="application/json",
445 )
446 assert resp.status_code == HTTPStatus.OK
447 assert SocialAccount.objects.filter(uid="123", user=user).exists()
448
449
450 def test_token_connect_already_connected(
451 user, auth_client, headless_reverse, db, user_factory
452 ):
453 # The other user already connected the account.
454 other_user = user_factory()
455 SocialAccount.objects.create(user=other_user, uid="123", provider="dummy")
456 id_token = json.dumps(
457 {
458 "id": 123,
459 "email": "[email protected]",
460 "email_verified": True,
461 }
462 )
463 resp = auth_client.post(
464 headless_reverse("headless:socialaccount:provider_token"),
465 data={
466 "provider": "dummy",
467 "token": {
468 "id_token": id_token,
469 },
470 "process": AuthProcess.CONNECT,
471 },
472 content_type="application/json",
473 )
474 assert not SocialAccount.objects.filter(uid="123", user=user).exists()
475 assert resp.status_code == HTTPStatus.BAD_REQUEST
476 assert resp.json() == {
477 "status": HTTPStatus.BAD_REQUEST,
478 "errors": [
479 {
480 "code": "connected_other",
481 "message": "The third-party account is already connected to a different account.",
482 }
483 ],
484 }
485
486
487 def test_provider_signup_not_pending(client, headless_reverse, db, settings):
488 resp = client.post(
489 headless_reverse("headless:socialaccount:provider_signup"),
490 data={
491 "email": "[email protected]",
492 },
493 content_type="application/json",
494 )
495 assert resp.status_code == HTTPStatus.CONFLICT
496
497
498 def test_valid_openid_connect_token(
499 client, headless_reverse, db, openid_connect_provider_id
500 ):
501 provider = get_adapter().get_provider(None, openid_connect_provider_id)
502 id_token = json.dumps(
503 {
504 "id": 123,
505 "email": "[email protected]",
506 "email_verified": True,
507 }
508 )
509 with patch(
510 "allauth.socialaccount.providers.openid_connect.views.OpenIDConnectOAuth2Adapter.openid_config"
511 ):
512 with patch("allauth.socialaccount.internal.jwtkit.verify_and_decode") as vad:
513 vad.return_value = {"sub": "123"}
514 resp = client.post(
515 headless_reverse("headless:socialaccount:provider_token"),
516 data={
517 "provider": openid_connect_provider_id,
518 "token": {
519 "client_id": provider.app.client_id,
520 "id_token": id_token,
521 },
522 "process": AuthProcess.LOGIN,
523 },
524 content_type="application/json",
525 )
526 assert resp.status_code == HTTPStatus.OK
527 assert SocialAccount.objects.filter(uid="123").exists()