Debian Codegraph @

allauth/socialaccount/adapter.py

raw
1 from __future__ import annotations
2
3 import functools
4 import warnings
5 from typing import TYPE_CHECKING
6
7 from django.contrib.auth.models import AbstractUser
8 from django.core.exceptions import ImproperlyConfigured, MultipleObjectsReturned
9 from django.db.models import Q
10 from django.http import HttpRequest
11 from django.urls import reverse
12 from django.utils.crypto import get_random_string
13 from django.utils.translation import gettext_lazy as _
14
15
16 if TYPE_CHECKING:
17 from allauth.socialaccount.models import SocialLogin, SocialApp
18 from allauth.socialaccount.providers.base.provider import Provider
19
20 from django.utils.module_loading import import_string
21
22 from allauth.account.adapter import get_adapter as get_account_adapter
23 from allauth.account.internal.emailkit import valid_email_or_none
24 from allauth.account.utils import (
25 filter_users_by_email,
26 user_email,
27 user_field,
28 user_username,
29 )
30 from allauth.core.internal.adapter import BaseAdapter
31 from allauth.core.internal.modelkit import deserialize_instance, serialize_instance
32
33 from . import app_settings
34
35
36 def _build_apps_from_settings(
37 *, provider=None, client_id=None
38 ) -> dict[str, list[SocialApp]]:
39 """Build the ``provider -> [SocialApp]`` map from
40 ``settings.SOCIALACCOUNT_PROVIDERS``. Performs no database I/O. The optional
41 ``provider``/``client_id`` arguments restrict the result to apps whose
42 ``provider_id`` or ``provider`` matches ``provider``, and whose
43 ``client_id`` matches ``client_id``.
44 """
45 from allauth.socialaccount.models import SocialApp
46
47 provider_to_apps: dict[str, list[SocialApp]] = {}
48 for p, pcfg in app_settings.PROVIDERS.items():
49 app_configs = pcfg.get("APPS")
50 if app_configs is None:
51 app_config = pcfg.get("APP")
52 if app_config is None:
53 continue
54 app_configs = [app_config]
55
56 for config in app_configs:
57 app = SocialApp(provider=p)
58 for field in [
59 "name",
60 "provider_id",
61 "client_id",
62 "secret",
63 "key",
64 "settings",
65 ]:
66 if field in config:
67 setattr(app, field, config[field])
68 if "certificate_key" in config:
69 warnings.warn("'certificate_key' should be moved into app.settings")
70 app.settings["certificate_key"] = config["certificate_key"]
71 if client_id and app.client_id != client_id:
72 continue
73 if provider and app.provider_id != provider and app.provider != provider:
74 continue
75 provider_to_apps.setdefault(p, []).append(app)
76 return provider_to_apps
77
78
79 class DefaultSocialAccountAdapter(BaseAdapter):
80 """The adapter class allows you to override various functionality of the
81 ``allauth.socialaccount`` app. To do so, point ``settings.SOCIALACCOUNT_ADAPTER`` to
82 your own class that derives from ``DefaultSocialAccountAdapter`` and override the
83 behavior by altering the implementation of the methods according to your own
84 needs.
85 """
86
87 error_messages = {
88 "email_taken": _(
89 "An account already exists with this email address."
90 " Please sign in to that account first, then connect"
91 " your %s account."
92 ),
93 "invalid_token": _("Invalid token."),
94 "no_password": _("Your account has no password set up."),
95 "no_verified_email": _("Your account has no verified email address."),
96 "disconnect_last": _(
97 "You cannot disconnect your last remaining third-party account."
98 ),
99 "connected_other": _(
100 "The third-party account is already connected to a different account."
101 ),
102 }
103
104 def pre_social_login(self, request: HttpRequest, sociallogin: SocialLogin) -> None:
105 """
106 Invoked just after a user successfully authenticates via a
107 social provider, but before the login is actually processed
108 (and before the pre_social_login signal is emitted).
109
110 You can use this hook to intervene, e.g. abort the login by
111 raising an ImmediateHttpResponse
112
113 Why both an adapter hook and the signal? Intervening in
114 e.g. the flow from within a signal handler is bad -- multiple
115 handlers may be active and are executed in undetermined order.
116 """
117 pass
118
119 def on_authentication_error(
120 self,
121 request: HttpRequest,
122 provider,
123 error=None,
124 exception=None,
125 extra_context=None,
126 ) -> None:
127 """
128 Invoked when there is an error in the authentication cycle. In this
129 case, pre_social_login will not be reached.
130
131 You can use this hook to intervene, e.g. redirect to an
132 educational flow by raising an ImmediateHttpResponse.
133 """
134 if hasattr(self, "authentication_error"):
135 warnings.warn(
136 "adapter.authentication_error() is deprecated, use adapter.on_authentication_error()"
137 )
138
139 self.authentication_error(
140 request,
141 provider.id,
142 error=error,
143 exception=exception,
144 extra_context=extra_context,
145 )
146
147 def new_user(self, request: HttpRequest, sociallogin: SocialLogin):
148 """
149 Instantiates a new User instance.
150 """
151 return get_account_adapter().new_user(request)
152
153 def save_user(self, request: HttpRequest, sociallogin: SocialLogin, form=None):
154 """
155 Saves a newly signed up social login. In case of auto-signup,
156 the signup form is not available.
157 """
158 u = sociallogin.user
159 assert u # nosec
160 u.set_unusable_password()
161 account_adapter = get_account_adapter()
162 if form:
163 account_adapter.save_user(request, u, form)
164 else:
165 account_adapter.populate_username(request, u)
166 sociallogin.save(request)
167 return u
168
169 def populate_user(self, request: HttpRequest, sociallogin: SocialLogin, data):
170 """
171 Hook that can be used to further populate the user instance.
172
173 For convenience, we populate several common fields.
174
175 Note that the user instance being populated represents a
176 suggested User instance that represents the social user that is
177 in the process of being logged in.
178
179 The User instance need not be completely valid and conflict
180 free. For example, verifying whether or not the username
181 already exists, is not a responsibility.
182 """
183 username = data.get("username")
184 first_name = data.get("first_name")
185 last_name = data.get("last_name")
186 email = data.get("email")
187 name = data.get("name")
188 user = sociallogin.user
189 assert user # nosec
190 user_username(user, username or "")
191 user_email(user, valid_email_or_none(email) or "")
192 name_parts = (name or "").partition(" ")
193 user_field(user, "first_name", first_name or name_parts[0])
194 user_field(user, "last_name", last_name or name_parts[2])
195 return user
196
197 def get_connect_redirect_url(self, request: HttpRequest, socialaccount) -> str:
198 """
199 Returns the default URL to redirect to after successfully
200 connecting a social account.
201 """
202 url = reverse("socialaccount_connections")
203 return url
204
205 def validate_disconnect(self, account, accounts) -> None:
206 """
207 Validate whether or not the socialaccount account can be
208 safely disconnected.
209 """
210 pass
211
212 def is_auto_signup_allowed(
213 self, request: HttpRequest, sociallogin: SocialLogin
214 ) -> bool:
215 # If email is specified, check for duplicate and if so, no auto signup.
216 auto_signup = app_settings.AUTO_SIGNUP
217 return auto_signup
218
219 def is_open_for_signup(
220 self, request: HttpRequest, sociallogin: SocialLogin
221 ) -> bool:
222 """
223 Checks whether or not the site is open for signups.
224
225 Next to simply returning True/False you can also intervene the
226 regular flow by raising an ImmediateHttpResponse
227 """
228 return get_account_adapter(request).is_open_for_signup(request)
229
230 def get_signup_form_initial_data(self, sociallogin: SocialLogin) -> dict:
231 user = sociallogin.user
232 assert user # nosec
233 email = user_email(user)
234 if not email and len(sociallogin.email_addresses) > 0:
235 email = sociallogin.email_addresses[0].email
236 initial = {
237 "email": email or "",
238 "username": user_username(user) or "",
239 "first_name": user_field(user, "first_name") or "",
240 "last_name": user_field(user, "last_name") or "",
241 }
242 return initial
243
244 def deserialize_instance(self, model, data):
245 return deserialize_instance(model, data)
246
247 def serialize_instance(self, instance):
248 return serialize_instance(instance)
249
250 def list_providers(self, request: HttpRequest) -> list[Provider]:
251 from allauth.socialaccount.providers import registry
252
253 ret = []
254 provider_classes = registry.get_class_list()
255 apps = self.list_apps(request)
256 apps_map: dict = {}
257 for app in apps:
258 apps_map.setdefault(app.provider, []).append(app)
259 for provider_class in provider_classes:
260 provider_apps = apps_map.get(provider_class.id, [])
261 if not provider_apps:
262 if provider_class.uses_apps:
263 continue
264 provider_apps = [None]
265 for app in provider_apps:
266 provider = provider_class(request=request, app=app)
267 ret.append(provider)
268 return ret
269
270 def get_provider(self, request: HttpRequest, provider, client_id=None):
271 """Looks up a `provider`, supporting subproviders by looking up by
272 `provider_id`.
273 """
274 from allauth.socialaccount.providers import registry
275
276 provider_class = registry.get_class(provider)
277 if provider_class is None or provider_class.uses_apps:
278 app = self.get_app(request, provider=provider, client_id=client_id)
279 if not provider_class:
280 # In this case, the `provider` argument passed was a
281 # `provider_id`.
282 provider_class = registry.get_class(app.provider)
283 if not provider_class:
284 raise ImproperlyConfigured(f"unknown provider: {app.provider}")
285 return provider_class(request, app=app)
286 elif provider_class:
287 assert not provider_class.uses_apps # nosec
288 return provider_class(request, app=None)
289 else:
290 raise ImproperlyConfigured(f"unknown provider: {provider}")
291
292 def list_apps(
293 self, request: HttpRequest, provider=None, client_id=None
294 ) -> list[SocialApp]:
295 """SocialApp's can be setup in the database, or, via
296 `settings.SOCIALACCOUNT_PROVIDERS`. This methods returns a uniform list
297 of all known apps matching the specified criteria, and blends both
298 (db/settings) sources of data.
299 """
300 # NOTE: Avoid loading models at top due to registry boot...
301 from allauth.socialaccount.models import SocialApp
302
303 # Map provider to the list of apps.
304 provider_to_apps: dict = {}
305
306 # First, populate it with the DB backed apps.
307 if request:
308 db_apps = SocialApp.objects.on_site(request)
309 else:
310 db_apps = SocialApp.objects.all()
311 if provider:
312 db_apps = db_apps.filter(Q(provider=provider) | Q(provider_id=provider))
313 if client_id:
314 db_apps = db_apps.filter(client_id=client_id)
315 for app in db_apps:
316 apps = provider_to_apps.setdefault(app.provider, [])
317 apps.append(app)
318
319 # Then, extend it with the settings backed apps.
320 settings_apps = _build_apps_from_settings(
321 provider=provider, client_id=client_id
322 )
323 for p, apps in settings_apps.items():
324 provider_to_apps.setdefault(p, []).extend(apps)
325
326 # Flatten the list of apps.
327 apps = []
328 for provider_apps in provider_to_apps.values():
329 apps.extend(provider_apps)
330 return apps
331
332 def get_app(self, request: HttpRequest, provider, client_id=None):
333 from allauth.socialaccount.models import SocialApp
334
335 apps = self.list_apps(request, provider=provider, client_id=client_id)
336 if len(apps) > 1:
337 visible_apps = [app for app in apps if not app.settings.get("hidden")]
338 if len(visible_apps) != 1:
339 raise MultipleObjectsReturned
340 apps = visible_apps
341 elif len(apps) == 0:
342 raise SocialApp.DoesNotExist()
343 return apps[0]
344
345 def send_notification_mail(self, *args, **kwargs) -> None:
346 return get_account_adapter().send_notification_mail(*args, **kwargs)
347
348 def get_requests_session(self):
349 import requests
350
351 session = requests.Session()
352 session.request = functools.partial(
353 session.request, timeout=app_settings.REQUESTS_TIMEOUT
354 )
355 return session
356
357 def is_email_verified(self, provider, email) -> bool:
358 """
359 Returns ``True`` iff the given email encountered during a social
360 login for the given provider is to be assumed verified.
361
362 This can be configured with a ``"verified_email"`` key in the provider
363 app settings, or a ``"VERIFIED_EMAIL"`` in the global provider settings
364 (``SOCIALACCOUNT_PROVIDERS``). Both can be set to ``False`` or
365 ``True``, or, a list of domains to match email addresses against.
366 """
367 verified_email = None
368 if provider.app:
369 verified_email = provider.app.settings.get("verified_email")
370 if verified_email is None:
371 settings = provider.get_settings()
372 verified_email = settings.get("VERIFIED_EMAIL", False)
373 if isinstance(verified_email, bool):
374 pass
375 elif isinstance(verified_email, list):
376 email_domain = email.partition("@")[2].lower()
377 verified_domains = [d.lower() for d in verified_email]
378 verified_email = email_domain in verified_domains
379 else:
380 raise ImproperlyConfigured("verified_email wrongly configured")
381 return verified_email
382
383 def can_authenticate_by_email(self, login: SocialLogin, email: str) -> bool:
384 """
385 Returns ``True`` if authentication by email is active for this login/email.
386
387 This can be configured with a ``"email_authentication"`` key in the provider
388 app settings, or a ``"EMAIL_AUTHENTICATION"`` in the global provider settings
389 (``SOCIALACCOUNT_PROVIDERS``).
390 """
391 ret: bool | None = None
392 provider = login.provider
393 if provider.app:
394 ret = provider.app.settings.get("email_authentication")
395 if ret is None:
396 ret = app_settings.EMAIL_AUTHENTICATION or provider.get_settings().get(
397 "EMAIL_AUTHENTICATION", False
398 )
399 return ret or False
400
401 def authenticate_by_email(
402 self, sociallogin: SocialLogin
403 ) -> tuple[AbstractUser, str] | None:
404 """
405 Attempts to authenticate an existing user by matching verified email
406 addresses from the social login against local accounts.
407
408 Returns a tuple of ``(user, email)`` if a match is found, or ``None``
409 if authentication by email is not possible.
410 """
411 emails = [e.email for e in sociallogin.email_addresses if e.verified]
412 for email in emails:
413 if not self.can_authenticate_by_email(sociallogin, email):
414 continue
415 users = filter_users_by_email(email, prefer_verified=True)
416 if users:
417 return users[0], email
418 return None
419
420 def generate_state_param(self, state: dict) -> str:
421 """
422 To preserve certain state before the handshake with the provider
423 takes place, and be able to verify/use that state later on, a `state`
424 parameter is typically passed to the provider. By default, a random
425 string sufficies as the state parameter value is actually just a
426 reference/pointer to the actual state. You can use this adapter method
427 to alter the generation of the `state` parameter.
428 """
429 from allauth.socialaccount.internal.statekit import STATE_ID_LENGTH
430
431 return get_random_string(STATE_ID_LENGTH)
432
433
434 def get_adapter(request: HttpRequest | None = None) -> DefaultSocialAccountAdapter:
435 return import_string(app_settings.ADAPTER)(request)