| 1 |
import json |
| 2 |
import time |
| 3 |
from http import HTTPStatus |
| 4 |
from importlib import import_module |
| 5 |
from unittest.mock import Mock, patch |
| 6 |
|
| 7 |
from django.conf import settings |
| 8 |
from django.contrib.auth.models import User |
| 9 |
from django.core import mail |
| 10 |
from django.test import TestCase |
| 11 |
from django.test.client import RequestFactory |
| 12 |
from django.test.utils import override_settings |
| 13 |
from django.urls import reverse |
| 14 |
|
| 15 |
import pytest |
| 16 |
|
| 17 |
from allauth.account import app_settings as account_settings |
| 18 |
from allauth.account.adapter import get_adapter as get_account_adapter |
| 19 |
from allauth.account.models import EmailAddress, EmailConfirmation |
| 20 |
from allauth.account.signals import user_signed_up |
| 21 |
from allauth.socialaccount.adapter import get_adapter |
| 22 |
from allauth.socialaccount.models import SocialAccount, SocialToken |
| 23 |
from allauth.socialaccount.providers.apple.client import jwt_encode |
| 24 |
from allauth.socialaccount.providers.google.provider import GoogleProvider |
| 25 |
from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter |
| 26 |
from tests.apps.socialaccount.base import OAuth2TestsMixin |
| 27 |
from tests.mocking import mocked_response |
| 28 |
|
| 29 |
|
| 30 |
@pytest.fixture |
| 31 |
def settings_with_google_provider(settings): |
| 32 |
settings.SOCIALACCOUNT_PROVIDERS = { |
| 33 |
"google": { |
| 34 |
"APP": { |
| 35 |
"client_id": "app123id", |
| 36 |
"key": "google", |
| 37 |
"secret": "dummy", |
| 38 |
} |
| 39 |
} |
| 40 |
} |
| 41 |
return settings |
| 42 |
|
| 43 |
|
| 44 |
@override_settings( |
| 45 |
SOCIALACCOUNT_AUTO_SIGNUP=True, |
| 46 |
ACCOUNT_SIGNUP_FORM_CLASS=None, |
| 47 |
ACCOUNT_EMAIL_VERIFICATION=account_settings.EmailVerificationMethod.MANDATORY, |
| 48 |
) |
| 49 |
class GoogleTests(OAuth2TestsMixin, TestCase): |
| 50 |
provider_id = GoogleProvider.id |
| 51 |
|
| 52 |
def setUp(self): |
| 53 |
super().setUp() |
| 54 |
self.email = "[email protected]" |
| 55 |
self.identity_overwrites = {} |
| 56 |
|
| 57 |
def get_expected_to_str(self): |
| 58 |
return "[email protected]" |
| 59 |
|
| 60 |
def get_google_id_token_payload(self): |
| 61 |
now = int(time.time()) |
| 62 |
client_id = "app123id" # Matches `setup_app` |
| 63 |
payload = { |
| 64 |
"iss": "https://accounts.google.com", |
| 65 |
"azp": client_id, |
| 66 |
"aud": client_id, |
| 67 |
"sub": "108204268033311374519", |
| 68 |
"hd": "example.com", |
| 69 |
"email": self.email, |
| 70 |
"email_verified": True, |
| 71 |
"at_hash": "HK6E_P6Dh8Y93mRNtsDB1Q", |
| 72 |
"name": "Raymond Penners", |
| 73 |
"picture": "https://lh5.googleusercontent.com/photo.jpg", |
| 74 |
"given_name": "Raymond", |
| 75 |
"family_name": "Penners", |
| 76 |
"locale": "en", |
| 77 |
"iat": now, |
| 78 |
"exp": now + 60 * 60, |
| 79 |
} |
| 80 |
payload.update(self.identity_overwrites) |
| 81 |
return payload |
| 82 |
|
| 83 |
def get_login_response_json(self, with_refresh_token=True): |
| 84 |
data = { |
| 85 |
"access_token": "testac", |
| 86 |
"expires_in": 3600, |
| 87 |
"scope": "https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile openid", |
| 88 |
"token_type": "Bearer", |
| 89 |
"id_token": jwt_encode(self.get_google_id_token_payload(), "secret"), |
| 90 |
} |
| 91 |
return json.dumps(data) |
| 92 |
|
| 93 |
@override_settings(SOCIALACCOUNT_AUTO_SIGNUP=False) |
| 94 |
def test_login(self): |
| 95 |
resp = self.login(resp_mock=None) |
| 96 |
self.assertRedirects(resp, reverse("socialaccount_signup")) |
| 97 |
|
| 98 |
def test_wrong_id_token_claim_values(self): |
| 99 |
wrong_claim_values = { |
| 100 |
"iss": "not-google", |
| 101 |
"exp": time.time() - 1, |
| 102 |
"aud": "foo", |
| 103 |
} |
| 104 |
template_ext = getattr(settings, "ACCOUNT_TEMPLATE_EXTENSION", "html") |
| 105 |
for key, value in wrong_claim_values.items(): |
| 106 |
with self.subTest(key): |
| 107 |
self.identity_overwrites = {key: value} |
| 108 |
resp = self.login(resp_mock=None) |
| 109 |
self.assertTemplateUsed( |
| 110 |
resp, f"socialaccount/authentication_error.{template_ext}" |
| 111 |
) |
| 112 |
|
| 113 |
def test_username_based_on_email(self): |
| 114 |
self.identity_overwrites = {"given_name": "明", "family_name": "小"} |
| 115 |
self.login(resp_mock=None) |
| 116 |
user = User.objects.get(email=self.email) |
| 117 |
self.assertEqual(user.username, "raymond.penners") |
| 118 |
|
| 119 |
def test_email_verified(self): |
| 120 |
self.identity_overwrites = {"email_verified": True} |
| 121 |
self.login(resp_mock=None) |
| 122 |
email_address = EmailAddress.objects.get(email=self.email, verified=True) |
| 123 |
self.assertFalse( |
| 124 |
EmailConfirmation.objects.filter(email_address__email=self.email).exists() |
| 125 |
) |
| 126 |
account = email_address.user.socialaccount_set.all()[0] |
| 127 |
self.assertEqual(account.extra_data["given_name"], "Raymond") |
| 128 |
|
| 129 |
def test_user_signed_up_signal(self): |
| 130 |
sent_signals = [] |
| 131 |
|
| 132 |
def on_signed_up(sender, request, user, **kwargs): |
| 133 |
sociallogin = kwargs["sociallogin"] |
| 134 |
self.assertEqual(sociallogin.account.provider, GoogleProvider.id) |
| 135 |
self.assertEqual(sociallogin.account.user, user) |
| 136 |
sent_signals.append(sender) |
| 137 |
|
| 138 |
user_signed_up.connect(on_signed_up) |
| 139 |
self.login(resp_mock=None) |
| 140 |
self.assertTrue(len(sent_signals) > 0) |
| 141 |
user_signed_up.disconnect(on_signed_up) |
| 142 |
|
| 143 |
@override_settings(ACCOUNT_EMAIL_CONFIRMATION_HMAC=False) |
| 144 |
def test_email_unverified(self): |
| 145 |
self.identity_overwrites = {"email_verified": False} |
| 146 |
resp = self.login(resp_mock=None) |
| 147 |
email_address = EmailAddress.objects.get(email=self.email) |
| 148 |
self.assertFalse(email_address.verified) |
| 149 |
self.assertTrue( |
| 150 |
EmailConfirmation.objects.filter(email_address__email=self.email).exists() |
| 151 |
) |
| 152 |
self.assertTemplateUsed( |
| 153 |
resp, "account/email/email_confirmation_signup_subject.txt" |
| 154 |
) |
| 155 |
|
| 156 |
def test_email_verified_stashed(self): |
| 157 |
# http://slacy.com/blog/2012/01/how-to-set-session-variables-in-django-unit-tests/ |
| 158 |
engine = import_module(settings.SESSION_ENGINE) |
| 159 |
store = engine.SessionStore() |
| 160 |
store.save() |
| 161 |
self.client.cookies[settings.SESSION_COOKIE_NAME] = store.session_key |
| 162 |
request = RequestFactory().get("/") |
| 163 |
request.session = self.client.session |
| 164 |
adapter = get_account_adapter() |
| 165 |
adapter.stash_verified_email(request, self.email) |
| 166 |
request.session.save() |
| 167 |
|
| 168 |
self.identity_overwrites = {"email_verified": False} |
| 169 |
self.login(resp_mock=None) |
| 170 |
email_address = EmailAddress.objects.get(email=self.email) |
| 171 |
self.assertTrue(email_address.verified) |
| 172 |
self.assertFalse( |
| 173 |
EmailConfirmation.objects.filter(email_address__email=self.email).exists() |
| 174 |
) |
| 175 |
|
| 176 |
def test_account_connect(self): |
| 177 |
email = "[email protected]" |
| 178 |
user = User.objects.create(username="user", is_active=True, email=email) |
| 179 |
user.set_password("test") |
| 180 |
user.save() |
| 181 |
EmailAddress.objects.create(user=user, email=email, primary=True, verified=True) |
| 182 |
self.client.login(username=user.username, password="test") |
| 183 |
self.identity_overwrites = {"email": email, "email_verified": True} |
| 184 |
self.login(resp_mock=None, process="connect") |
| 185 |
# Check if we connected... |
| 186 |
self.assertTrue( |
| 187 |
SocialAccount.objects.filter(user=user, provider=GoogleProvider.id).exists() |
| 188 |
) |
| 189 |
# For now, we do not pick up any new email addresses on connect |
| 190 |
self.assertEqual(EmailAddress.objects.filter(user=user).count(), 1) |
| 191 |
self.assertEqual(EmailAddress.objects.filter(user=user, email=email).count(), 1) |
| 192 |
|
| 193 |
@override_settings( |
| 194 |
ACCOUNT_EMAIL_VERIFICATION=account_settings.EmailVerificationMethod.MANDATORY, |
| 195 |
SOCIALACCOUNT_EMAIL_VERIFICATION=account_settings.EmailVerificationMethod.NONE, |
| 196 |
) |
| 197 |
def test_social_email_verification_skipped(self): |
| 198 |
self.identity_overwrites = {"email_verified": False} |
| 199 |
self.login(resp_mock=None) |
| 200 |
email_address = EmailAddress.objects.get(email=self.email) |
| 201 |
self.assertFalse(email_address.verified) |
| 202 |
self.assertFalse( |
| 203 |
EmailConfirmation.objects.filter(email_address__email=self.email).exists() |
| 204 |
) |
| 205 |
|
| 206 |
@override_settings( |
| 207 |
ACCOUNT_EMAIL_VERIFICATION=account_settings.EmailVerificationMethod.OPTIONAL, |
| 208 |
SOCIALACCOUNT_EMAIL_VERIFICATION=account_settings.EmailVerificationMethod.OPTIONAL, |
| 209 |
) |
| 210 |
def test_social_email_verification_optional(self): |
| 211 |
self.identity_overwrites = {"email_verified": False} |
| 212 |
self.login(resp_mock=None) |
| 213 |
self.assertEqual(len(mail.outbox), 1) |
| 214 |
self.login(resp_mock=None) |
| 215 |
self.assertEqual(len(mail.outbox), 1) |
| 216 |
|
| 217 |
|
| 218 |
@override_settings( |
| 219 |
SOCIALACCOUNT_PROVIDERS={ |
| 220 |
"google": { |
| 221 |
"APP": { |
| 222 |
"client_id": "app123id", |
| 223 |
"key": "google", |
| 224 |
"secret": "dummy", |
| 225 |
} |
| 226 |
} |
| 227 |
} |
| 228 |
) |
| 229 |
class AppInSettingsTests(GoogleTests): |
| 230 |
""" |
| 231 |
Run the same set of tests but without having a SocialApp entry. |
| 232 |
""" |
| 233 |
|
| 234 |
pass |
| 235 |
|
| 236 |
|
| 237 |
def test_login_by_token(db, client, settings_with_google_provider): |
| 238 |
client.cookies.load({"g_csrf_token": "csrf"}) |
| 239 |
with patch("jwt.get_unverified_header") as g_u_h: |
| 240 |
with mocked_response({"dummykid": "-----BEGIN CERTIFICATE-----"}): |
| 241 |
with patch("cryptography.x509.load_pem_x509_certificate") as load_pem: |
| 242 |
with patch("jwt.decode") as decode: |
| 243 |
decode.return_value = { |
| 244 |
"iss": "https://accounts.google.com", |
| 245 |
"aud": "client_id", |
| 246 |
"sub": "123sub", |
| 247 |
"hd": "example.com", |
| 248 |
"email": "[email protected]", |
| 249 |
"email_verified": True, |
| 250 |
"at_hash": "HK6E_P6Dh8Y93mRNtsDB1Q", |
| 251 |
"name": "Raymond Penners", |
| 252 |
"picture": "https://lh5.googleusercontent.com/photo.jpg", |
| 253 |
"given_name": "Raymond", |
| 254 |
"family_name": "Penners", |
| 255 |
"locale": "en", |
| 256 |
"iat": 123, |
| 257 |
"exp": 456, |
| 258 |
} |
| 259 |
g_u_h.return_value = { |
| 260 |
"alg": "RS256", |
| 261 |
"kid": "dummykid", |
| 262 |
"typ": "JWT", |
| 263 |
} |
| 264 |
pem = Mock() |
| 265 |
load_pem.return_value = pem |
| 266 |
pem.public_key.return_value = "key" |
| 267 |
resp = client.post( |
| 268 |
reverse("google_login_by_token"), |
| 269 |
{"credential": "dummy", "g_csrf_token": "csrf"}, |
| 270 |
) |
| 271 |
assert resp.status_code == HTTPStatus.FOUND |
| 272 |
socialaccount = SocialAccount.objects.get(uid="123sub") |
| 273 |
assert socialaccount.user.email == "[email protected]" |
| 274 |
|
| 275 |
|
| 276 |
@pytest.mark.parametrize( |
| 277 |
"id_key,verified_key", |
| 278 |
[ |
| 279 |
("id", "email_verified"), |
| 280 |
("sub", "verified_email"), |
| 281 |
], |
| 282 |
) |
| 283 |
@pytest.mark.parametrize("verified", [False, True]) |
| 284 |
def test_extract_data( |
| 285 |
id_key, verified_key, verified, settings_with_google_provider, db |
| 286 |
): |
| 287 |
data = { |
| 288 |
"email": "[email protected]", |
| 289 |
} |
| 290 |
data[id_key] = "123" |
| 291 |
data[verified_key] = verified |
| 292 |
provider = get_adapter().get_provider(None, GoogleProvider.id) |
| 293 |
assert provider.extract_uid(data) == "123" |
| 294 |
emails = provider.extract_email_addresses(data) |
| 295 |
assert len(emails) == 1 |
| 296 |
assert emails[0].verified == verified |
| 297 |
assert emails[0].email == "[email protected]" |
| 298 |
|
| 299 |
|
| 300 |
@pytest.mark.parametrize( |
| 301 |
"fetch_userinfo,id_token_has_picture,response,expected_uid, expected_picture", |
| 302 |
[ |
| 303 |
(True, True, {"id_token": "123"}, "uid-from-id-token", "pic-from-id-token"), |
| 304 |
(True, False, {"id_token": "123"}, "uid-from-id-token", "pic-from-userinfo"), |
| 305 |
(True, True, {"access_token": "123"}, "uid-from-userinfo", "pic-from-userinfo"), |
| 306 |
], |
| 307 |
) |
| 308 |
@pytest.mark.parametrize("did_fetch_access_token", [False, True]) |
| 309 |
def test_complete_login_variants( |
| 310 |
response, |
| 311 |
settings_with_google_provider, |
| 312 |
db, |
| 313 |
fetch_userinfo, |
| 314 |
expected_uid, |
| 315 |
expected_picture, |
| 316 |
id_token_has_picture, |
| 317 |
did_fetch_access_token, |
| 318 |
): |
| 319 |
with patch.object( |
| 320 |
GoogleOAuth2Adapter, |
| 321 |
"_fetch_user_info", |
| 322 |
return_value={ |
| 323 |
"id": "uid-from-userinfo", |
| 324 |
"picture": "pic-from-userinfo", |
| 325 |
}, |
| 326 |
): |
| 327 |
id_token = {"sub": "uid-from-id-token"} |
| 328 |
if id_token_has_picture: |
| 329 |
id_token["picture"] = "pic-from-id-token" |
| 330 |
with patch( |
| 331 |
"allauth.socialaccount.providers.google.views._verify_and_decode", |
| 332 |
return_value=id_token, |
| 333 |
) as decode_mock: |
| 334 |
request = None |
| 335 |
app = None |
| 336 |
adapter = GoogleOAuth2Adapter(request) |
| 337 |
adapter.did_fetch_access_token = did_fetch_access_token |
| 338 |
adapter.fetch_userinfo = fetch_userinfo |
| 339 |
token = SocialToken() |
| 340 |
login = adapter.complete_login(request, app, token, response=response) |
| 341 |
assert login.account.uid == expected_uid |
| 342 |
assert login.account.extra_data["picture"] == expected_picture |
| 343 |
if not response.get("id_token"): |
| 344 |
assert not decode_mock.called |
| 345 |
else: |
| 346 |
assert decode_mock.call_args[1]["verify_signature"] == ( |
| 347 |
not did_fetch_access_token |
| 348 |
) |