Debian Codegraph @

tests/apps/socialaccount/providers/openid/tests.py

raw
1 import urllib.error
2 from http import HTTPStatus
3 from unittest.mock import Mock, patch
4
5 from django.conf import settings
6 from django.contrib.auth import get_user_model
7 from django.test import override_settings
8 from django.urls import reverse
9
10 import pytest
11 from openid import fetchers
12 from openid.consumer import consumer
13 from openid.message import InvalidOpenIDNamespace
14 from pytest_django.asserts import assertTemplateUsed
15
16 from allauth.socialaccount.models import SocialAccount
17 from allauth.socialaccount.providers.openid import views
18 from allauth.socialaccount.providers.openid.utils import AXAttribute
19
20
21 class TestFetcher(fetchers.Urllib2Fetcher):
22 def fetch(self, url, body=None, headers=None):
23 if url == "https://steamcommunity.com/openid":
24 return fetchers.HTTPResponse(
25 final_url="https://steamcommunity.com/openid",
26 status=HTTPStatus.OK,
27 headers={"content-type": "application/xrds+xml;charset=utf-8"},
28 body='<?xml version="1.0" encoding="UTF-8"?>\n<xrds:XRDS xmlns:xrds="xri://$xrds" xmlns="xri://$xrd*($v*2.0)">\n\t<XRD>\n\t\t<Service priority="0">\n\t\t\t<Type>http://specs.openid.net/auth/2.0/server</Type>\t\t\n\t\t\t<URI>https://steamcommunity.com/openid/login</URI>\n\t\t</Service>\n\t</XRD>\n</xrds:XRDS>',
29 )
30 if url == "https://steamcommunity.com/openid/login":
31 return fetchers.HTTPResponse(
32 final_url="https://steamcommunity.com/openid/login",
33 status=HTTPStatus.OK,
34 headers={"content-type": "text/plain;charset=utf-8"},
35 body="ns:http://specs.openid.net/auth/2.0\nerror_code:unsupported-type\nerror:Associations not supported\n",
36 )
37
38 if url == "https://discovery-failure.com/":
39 raise urllib.error.URLError
40 ret = super().fetch(url, body=body, headers=headers)
41 return ret
42
43
44 @pytest.fixture(autouse=True)
45 def setup_fetcher():
46 old_fetcher = fetchers.getDefaultFetcher()
47 fetchers.setDefaultFetcher(TestFetcher())
48 yield
49 fetchers.setDefaultFetcher(old_fetcher)
50
51
52 def test_discovery_failure(client):
53 """
54 This used to generate a server 500:
55 DiscoveryFailure: No usable OpenID services found
56 for http://www.google.com/
57 """
58 resp = client.post(
59 reverse("openid_login"), dict(openid="https://discovery-failure.com/")
60 )
61 assert "openid" in resp.context["form"].errors
62
63
64 def test_login(client, db):
65 # Location: https://s.yimg.com/wm/mbr/html/openid-eol-0.0.1.html
66 resp = client.post(
67 reverse(views.login), dict(openid="https://steamcommunity.com/openid")
68 )
69 assert "steamcommunity.com/openid/login" in resp["location"]
70 with patch(
71 "allauth.socialaccount.providers.openid.views._openid_consumer"
72 ) as consumer_mock:
73 consumer_client = Mock()
74 complete = Mock()
75 consumer_mock.return_value = consumer_client
76 consumer_client.complete = complete
77 complete_response = Mock()
78 complete.return_value = complete_response
79 complete_response.status = consumer.SUCCESS
80 complete_response.identity_url = "http://dummy/john/"
81 with patch(
82 "allauth.socialaccount.providers.openid.utils.SRegResponse"
83 ) as sr_mock:
84 with patch(
85 "allauth.socialaccount.providers.openid.utils.FetchResponse"
86 ) as fr_mock:
87 sreg_mock = Mock()
88 ax_mock = Mock()
89 sr_mock.fromSuccessResponse = sreg_mock
90 fr_mock.fromSuccessResponse = ax_mock
91 sreg_mock.return_value = {}
92 ax_mock.return_value = {AXAttribute.PERSON_FIRST_NAME: ["raymond"]}
93 resp = client.post(reverse("openid_callback"))
94 assert resp["location"] == "/accounts/profile/"
95 get_user_model().objects.get(first_name="raymond")
96 social_account = SocialAccount.objects.get(
97 uid=complete_response.identity_url
98 )
99 account = social_account.get_provider_account()
100 assert account.to_str() == complete_response.identity_url
101
102
103 @override_settings(
104 SOCIALACCOUNT_PROVIDERS={
105 "openid": {
106 "SERVERS": [
107 dict(
108 id="yahoo",
109 name="Yahoo",
110 openid_url="http://me.yahoo.com",
111 extra_attributes=[
112 (
113 "phone",
114 "http://axschema.org/contact/phone/default",
115 True,
116 )
117 ],
118 )
119 ]
120 }
121 }
122 )
123 def test_login_with_extra_attributes(client, db):
124 with patch("allauth.socialaccount.providers.openid.views.QUERY_EMAIL", True):
125 resp = client.post(
126 reverse(views.login), dict(openid="https://steamcommunity.com/openid")
127 )
128 assert "steamcommunity.com/openid/login" in resp["location"]
129 with patch(
130 "allauth.socialaccount.providers.openid.views._openid_consumer"
131 ) as consumer_mock:
132 consumer_client = Mock()
133 complete = Mock()
134 endpoint = Mock()
135 consumer_mock.return_value = consumer_client
136 consumer_client.complete = complete
137 complete_response = Mock()
138 complete.return_value = complete_response
139 complete_response.endpoint = endpoint
140 complete_response.endpoint.server_url = "http://me.yahoo.com"
141 complete_response.status = consumer.SUCCESS
142 complete_response.identity_url = "http://dummy/john/"
143 with patch(
144 "allauth.socialaccount.providers.openid.utils.SRegResponse"
145 ) as sr_mock:
146 with patch(
147 "allauth.socialaccount.providers.openid.utils.FetchResponse"
148 ) as fr_mock:
149 sreg_mock = Mock()
150 ax_mock = Mock()
151 sr_mock.fromSuccessResponse = sreg_mock
152 fr_mock.fromSuccessResponse = ax_mock
153 sreg_mock.return_value = {}
154 ax_mock.return_value = {
155 AXAttribute.CONTACT_EMAIL: ["[email protected]"],
156 AXAttribute.PERSON_FIRST_NAME: ["raymond"],
157 "http://axschema.org/contact/phone/default": ["123456789"],
158 }
159 resp = client.post(reverse("openid_callback"))
160 assert resp["location"] == "/accounts/profile/"
161 socialaccount = SocialAccount.objects.get(user__first_name="raymond")
162 assert socialaccount.extra_data.get("phone") == "123456789"
163
164
165 def test_callback_error(client, db):
166 with patch(
167 "allauth.socialaccount.providers.openid.views._openid_consumer"
168 ) as consumer_mock:
169 consumer_client = Mock()
170 complete = Mock()
171 consumer_mock.return_value = consumer_client
172 consumer_client.complete = complete
173
174 def raise_invalid_openid_namespace(*args, **kwargs):
175 raise InvalidOpenIDNamespace("Invalid OpenID Namespace 'http://evil.com'")
176
177 complete.side_effect = raise_invalid_openid_namespace
178 template_ext = getattr(settings, "ACCOUNT_TEMPLATE_EXTENSION", "html")
179 with patch(
180 "allauth.socialaccount.providers.openid.utils.SRegResponse"
181 ) as sr_mock:
182 with patch(
183 "allauth.socialaccount.providers.openid.utils.FetchResponse"
184 ) as fr_mock:
185 sreg_mock = Mock()
186 ax_mock = Mock()
187 sr_mock.fromSuccessResponse = sreg_mock
188 fr_mock.fromSuccessResponse = ax_mock
189 sreg_mock.return_value = {}
190 ax_mock.return_value = {AXAttribute.PERSON_FIRST_NAME: ["raymond"]}
191 resp = client.post(reverse("openid_callback"))
192 assertTemplateUsed(
193 resp, f"socialaccount/authentication_error.{template_ext}"
194 )