| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from typing import Any |
| 4 |
|
| 5 |
from django.core.exceptions import ( |
| 6 |
ImproperlyConfigured, |
| 7 |
PermissionDenied, |
| 8 |
ValidationError, |
| 9 |
) |
| 10 |
from django.http import HttpRequest, HttpResponse |
| 11 |
|
| 12 |
from allauth.account.adapter import get_adapter as get_account_adapter |
| 13 |
from allauth.account.internal.emailkit import valid_email_or_none |
| 14 |
from allauth.account.utils import get_next_redirect_url, get_request_param |
| 15 |
from allauth.core import context |
| 16 |
from allauth.socialaccount import app_settings |
| 17 |
from allauth.socialaccount.adapter import get_adapter |
| 18 |
from allauth.socialaccount.internal import statekit |
| 19 |
from allauth.socialaccount.providers.base.constants import AuthProcess |
| 20 |
|
| 21 |
|
| 22 |
class ProviderException(Exception): |
| 23 |
pass |
| 24 |
|
| 25 |
|
| 26 |
class Provider: |
| 27 |
name: str # Provided by subclasses |
| 28 |
id: str # Provided by subclasses |
| 29 |
slug: str | None = None # Provided by subclasses |
| 30 |
|
| 31 |
uses_apps = True |
| 32 |
supports_redirect = False |
| 33 |
# Indicates whether or not this provider supports logging in by posting an |
| 34 |
# access/id-token. |
| 35 |
supports_token_authentication = False |
| 36 |
|
| 37 |
def __init__(self, request: HttpRequest, app=None) -> None: |
| 38 |
self.request = request |
| 39 |
if self.uses_apps and app is None: |
| 40 |
raise ValueError("missing: app") |
| 41 |
self.app = app |
| 42 |
|
| 43 |
def __str__(self) -> str: |
| 44 |
return self.name |
| 45 |
|
| 46 |
@classmethod |
| 47 |
def get_slug(cls) -> str: |
| 48 |
return cls.slug or cls.id |
| 49 |
|
| 50 |
def get_login_url(self, request: HttpRequest, **kwargs) -> str: |
| 51 |
""" |
| 52 |
Builds the URL to redirect to when initiating a login for this |
| 53 |
provider. |
| 54 |
""" |
| 55 |
raise NotImplementedError(f"get_login_url() for {self.name}") |
| 56 |
|
| 57 |
def redirect_from_request(self, request: HttpRequest) -> HttpResponse: |
| 58 |
kwargs = self.get_redirect_from_request_kwargs(request) |
| 59 |
return self.redirect(request, **kwargs) |
| 60 |
|
| 61 |
def get_redirect_from_request_kwargs(self, request: HttpRequest) -> dict: |
| 62 |
kwargs = {} |
| 63 |
next_url = get_next_redirect_url(request) |
| 64 |
if next_url: |
| 65 |
kwargs["next_url"] = next_url |
| 66 |
kwargs["process"] = get_request_param(request, "process", AuthProcess.LOGIN) |
| 67 |
return kwargs |
| 68 |
|
| 69 |
def redirect( |
| 70 |
self, request: HttpRequest, process, next_url=None, data=None, **kwargs |
| 71 |
) -> HttpResponse: |
| 72 |
""" |
| 73 |
Initiate a redirect to the provider. |
| 74 |
""" |
| 75 |
raise NotImplementedError() |
| 76 |
|
| 77 |
def verify_token(self, request: HttpRequest, token): |
| 78 |
""" |
| 79 |
Verifies the token, returning a `SocialLogin` instance when valid. |
| 80 |
Raises a `ValidationError` otherwise. |
| 81 |
""" |
| 82 |
raise NotImplementedError() |
| 83 |
|
| 84 |
def media_js(self, request: HttpRequest) -> str: |
| 85 |
""" |
| 86 |
Some providers may require extra scripts (e.g. a Facebook connect) |
| 87 |
""" |
| 88 |
return "" |
| 89 |
|
| 90 |
def wrap_account(self, social_account): |
| 91 |
return self.account_class(social_account) |
| 92 |
|
| 93 |
def get_settings(self) -> dict: |
| 94 |
return app_settings.PROVIDERS.get(self.id, {}) |
| 95 |
|
| 96 |
def sociallogin_from_response(self, request: HttpRequest, response): |
| 97 |
""" |
| 98 |
Instantiates and populates a `SocialLogin` model based on the data |
| 99 |
retrieved in `response`. The method does NOT save the model to the |
| 100 |
DB. |
| 101 |
|
| 102 |
Data for `SocialLogin` will be extracted from `response` with the |
| 103 |
help of the `.extract_uid()`, `.extract_extra_data()`, |
| 104 |
`.extract_common_fields()`, and `.extract_email_addresses()` |
| 105 |
methods. |
| 106 |
|
| 107 |
:param request: a Django `HttpRequest` object. |
| 108 |
:param response: object retrieved via the callback response of the |
| 109 |
social auth provider. |
| 110 |
:return: A populated instance of the `SocialLogin` model (unsaved). |
| 111 |
""" |
| 112 |
# NOTE: Avoid loading models at top due to registry boot... |
| 113 |
from allauth.socialaccount.adapter import get_adapter |
| 114 |
from allauth.socialaccount.models import SocialAccount, SocialLogin |
| 115 |
|
| 116 |
adapter = get_adapter() |
| 117 |
uid = self.extract_uid(response) |
| 118 |
if not isinstance(uid, str): |
| 119 |
raise ValueError(f"uid must be a string: {repr(uid)}") |
| 120 |
if len(uid) > app_settings.UID_MAX_LENGTH: |
| 121 |
raise ImproperlyConfigured( |
| 122 |
f"SOCIALACCOUNT_UID_MAX_LENGTH too small (<{len(uid)})" |
| 123 |
) |
| 124 |
if not uid: |
| 125 |
raise ValueError("uid must be a non-empty string") |
| 126 |
|
| 127 |
extra_data = self.extract_extra_data(response) |
| 128 |
common_fields = self.extract_common_fields(response) |
| 129 |
socialaccount = SocialAccount( |
| 130 |
extra_data=extra_data, |
| 131 |
uid=uid, |
| 132 |
provider=self.sub_id, |
| 133 |
) |
| 134 |
email_addresses = self.extract_email_addresses(response) |
| 135 |
email = self.cleanup_email_addresses( |
| 136 |
common_fields.get("email"), |
| 137 |
email_addresses, |
| 138 |
email_verified=bool(common_fields.get("email_verified")), |
| 139 |
) |
| 140 |
if email: |
| 141 |
common_fields["email"] = email |
| 142 |
else: |
| 143 |
common_fields.pop("email", None) |
| 144 |
phone = common_fields.get("phone") |
| 145 |
if phone: |
| 146 |
try: |
| 147 |
phone = ( |
| 148 |
get_account_adapter().phone_form_field(required=True).clean(phone) |
| 149 |
) |
| 150 |
common_fields["phone"] = phone |
| 151 |
except ValidationError: |
| 152 |
phone = None |
| 153 |
common_fields.pop("phone") |
| 154 |
sociallogin = SocialLogin( |
| 155 |
provider=self, |
| 156 |
account=socialaccount, |
| 157 |
email_addresses=email_addresses, |
| 158 |
phone=phone, |
| 159 |
phone_verified=common_fields.get("phone_verified", False), |
| 160 |
) |
| 161 |
user = sociallogin.user = adapter.new_user(request, sociallogin) |
| 162 |
user.set_unusable_password() |
| 163 |
adapter.populate_user(request, sociallogin, common_fields) |
| 164 |
return sociallogin |
| 165 |
|
| 166 |
def extract_uid(self, data) -> str: |
| 167 |
""" |
| 168 |
Extracts the unique user ID from `data` |
| 169 |
""" |
| 170 |
raise NotImplementedError( |
| 171 |
"The provider must implement the `extract_uid()` method" |
| 172 |
) |
| 173 |
|
| 174 |
def extract_extra_data(self, data) -> dict: |
| 175 |
""" |
| 176 |
Extracts fields from `data` that will be stored in |
| 177 |
`SocialAccount`'s `extra_data` JSONField, such as email address, first |
| 178 |
name, last name, and phone number. |
| 179 |
|
| 180 |
:return: any JSON-serializable Python structure. |
| 181 |
""" |
| 182 |
return data |
| 183 |
|
| 184 |
def extract_common_fields(self, data) -> dict: |
| 185 |
""" |
| 186 |
Extracts fields from `data` that will be used to populate the |
| 187 |
`User` model in the `SOCIALACCOUNT_ADAPTER`'s `populate_user()` |
| 188 |
method. |
| 189 |
|
| 190 |
For example: |
| 191 |
|
| 192 |
{'first_name': 'John'} |
| 193 |
|
| 194 |
:return: dictionary of key-value pairs. |
| 195 |
""" |
| 196 |
return {} |
| 197 |
|
| 198 |
def cleanup_email_addresses( |
| 199 |
self, email: str | None, addresses: list, email_verified: bool = False |
| 200 |
) -> str | None: |
| 201 |
# Avoid loading models before adapters have been registered. |
| 202 |
from allauth.account.models import EmailAddress |
| 203 |
|
| 204 |
# Validate & clean the email addresses. |
| 205 |
email = valid_email_or_none(email) |
| 206 |
# A bit ugly, but the signature of this function is such that we have to |
| 207 |
# modify addresses in place. |
| 208 |
for idx in range(len(addresses))[::-1]: |
| 209 |
address = addresses[idx] |
| 210 |
address.email = valid_email_or_none(address.email) |
| 211 |
if not address.email: |
| 212 |
addresses.pop(idx) |
| 213 |
|
| 214 |
# Move user.email over to EmailAddress |
| 215 |
if email and email not in [a.email for a in addresses]: |
| 216 |
addresses.insert( |
| 217 |
0, |
| 218 |
EmailAddress(email=email, verified=bool(email_verified), primary=True), |
| 219 |
) |
| 220 |
# Force verified emails |
| 221 |
adapter = get_adapter() |
| 222 |
for address in addresses: |
| 223 |
if adapter.is_email_verified(self, address.email): |
| 224 |
address.verified = True |
| 225 |
|
| 226 |
# Sort in order of importance (primary, verified...) |
| 227 |
addresses.sort(key=lambda a: (a.primary, a.verified, a.email), reverse=True) |
| 228 |
if not email and addresses: |
| 229 |
email = addresses[0].email |
| 230 |
return email |
| 231 |
|
| 232 |
def extract_email_addresses(self, data) -> list: |
| 233 |
""" |
| 234 |
For example: |
| 235 |
|
| 236 |
[EmailAddress(email='[email protected]', |
| 237 |
verified=True, |
| 238 |
primary=True)] |
| 239 |
""" |
| 240 |
return [] |
| 241 |
|
| 242 |
@classmethod |
| 243 |
def get_package(cls) -> str: |
| 244 |
pkg = getattr(cls, "package", None) |
| 245 |
if not pkg: |
| 246 |
pkg = cls.__module__.rpartition(".")[0] |
| 247 |
return pkg |
| 248 |
|
| 249 |
def stash_redirect_state( |
| 250 |
self, |
| 251 |
request: HttpRequest, |
| 252 |
process, |
| 253 |
next_url=None, |
| 254 |
data=None, |
| 255 |
state_id=None, |
| 256 |
**kwargs, |
| 257 |
): |
| 258 |
""" |
| 259 |
Stashes state, returning a (random) state ID using which the state |
| 260 |
can be looked up later. Application specific state is stored separately |
| 261 |
from (core) allauth state such as `process` and `**kwargs`. |
| 262 |
""" |
| 263 |
state = {"process": process, "data": data, **kwargs} |
| 264 |
if next_url: |
| 265 |
state["next"] = next_url |
| 266 |
return statekit.stash_state(request, state, state_id=state_id) |
| 267 |
|
| 268 |
def unstash_redirect_state(self, request: HttpRequest, state_id): |
| 269 |
state = statekit.unstash_state(request, state_id) |
| 270 |
if state is None: |
| 271 |
raise PermissionDenied() |
| 272 |
return state |
| 273 |
|
| 274 |
@property |
| 275 |
def sub_id(self) -> str: |
| 276 |
return ( |
| 277 |
(self.app.provider_id or self.app.provider) if self.uses_apps else self.id |
| 278 |
) |
| 279 |
|
| 280 |
def serialize(self) -> dict[str, Any]: |
| 281 |
ret = {"id": self.id} |
| 282 |
if self.uses_apps: |
| 283 |
ret["app.client_id"] = self.app.client_id |
| 284 |
return ret |
| 285 |
|
| 286 |
@classmethod |
| 287 |
def deserialize(cls, data: Any) -> "Provider": |
| 288 |
if not isinstance(data, dict): |
| 289 |
raise ValueError() |
| 290 |
provider = data.get("id") |
| 291 |
if not isinstance(provider, str): |
| 292 |
raise ValueError() |
| 293 |
client_id = data.get("app.client_id") |
| 294 |
if client_id is not None and not isinstance(client_id, str): |
| 295 |
raise ValueError() |
| 296 |
return get_adapter().get_provider( |
| 297 |
context.request, |
| 298 |
provider=provider, |
| 299 |
client_id=client_id, |
| 300 |
) |
| 301 |
|
| 302 |
|
| 303 |
class ProviderAccount: |
| 304 |
def __init__(self, social_account) -> None: |
| 305 |
self.account = social_account |
| 306 |
|
| 307 |
def get_profile_url(self) -> str | None: |
| 308 |
return None |
| 309 |
|
| 310 |
def get_avatar_url(self) -> str | None: |
| 311 |
return None |
| 312 |
|
| 313 |
def get_brand(self) -> dict: |
| 314 |
""" |
| 315 |
Returns a dict containing an id and name identifying the |
| 316 |
brand. Useful when displaying logos next to accounts in |
| 317 |
templates. |
| 318 |
|
| 319 |
For most providers, these are identical to the provider. For |
| 320 |
OpenID however, the brand can derived from the OpenID identity |
| 321 |
url. |
| 322 |
""" |
| 323 |
provider = self.account.get_provider() |
| 324 |
return dict(id=provider.id, name=provider.name) |
| 325 |
|
| 326 |
def __str__(self) -> str: |
| 327 |
return self.to_str() |
| 328 |
|
| 329 |
def get_user_data(self) -> dict | None: |
| 330 |
"""Typically, the ``extra_data`` directly contains user related keys. |
| 331 |
For some providers, however, they are nested below a different key. In |
| 332 |
that case, you can override this method so that the base ``__str__()`` |
| 333 |
will still be able to find the data. |
| 334 |
""" |
| 335 |
ret = self.account.extra_data |
| 336 |
if not isinstance(ret, dict): |
| 337 |
ret = None |
| 338 |
return ret |
| 339 |
|
| 340 |
def to_str(self) -> str: |
| 341 |
""" |
| 342 |
Returns string representation of this social account. This is the |
| 343 |
unique identifier of the account, such as its username or its email |
| 344 |
address. It should be meaningful to human beings, which means a numeric |
| 345 |
ID number is rarely the appropriate representation here. |
| 346 |
|
| 347 |
Subclasses are meant to override this method. |
| 348 |
|
| 349 |
Users will see the string representation of their social accounts in |
| 350 |
the page rendered by the allauth.socialaccount.views.connections view. |
| 351 |
|
| 352 |
The following code did not use to work in the past due to py2 |
| 353 |
compatibility: |
| 354 |
|
| 355 |
class GoogleAccount(ProviderAccount): |
| 356 |
def __str__(self): |
| 357 |
dflt = super(GoogleAccount, self).__str__() |
| 358 |
return self.account.extra_data.get('name', dflt) |
| 359 |
|
| 360 |
So we have this method `to_str` that can be overridden in a conventional |
| 361 |
fashion, without having to worry about it. |
| 362 |
""" |
| 363 |
user_data = self.get_user_data() |
| 364 |
if user_data: |
| 365 |
combi_values = {} |
| 366 |
tbl = [ |
| 367 |
# Prefer username -- it's the most human recognizable & unique. |
| 368 |
( |
| 369 |
None, |
| 370 |
[ |
| 371 |
"username", |
| 372 |
"userName", |
| 373 |
"user_name", |
| 374 |
"login", |
| 375 |
"handle", |
| 376 |
], |
| 377 |
), |
| 378 |
# Second best is email |
| 379 |
(None, ["email", "Email", "mail", "email_address"]), |
| 380 |
( |
| 381 |
None, |
| 382 |
[ |
| 383 |
"name", |
| 384 |
"display_name", |
| 385 |
"displayName", |
| 386 |
"displayname", |
| 387 |
"Display_Name", |
| 388 |
"nickname", |
| 389 |
], |
| 390 |
), |
| 391 |
# Use the full name |
| 392 |
(None, ["full_name", "fullName"]), |
| 393 |
# Alternatively, try to assemble a full name ourselves. |
| 394 |
( |
| 395 |
"first_name", |
| 396 |
[ |
| 397 |
"first_name", |
| 398 |
"firstname", |
| 399 |
"firstName", |
| 400 |
"First_Name", |
| 401 |
"given_name", |
| 402 |
"givenName", |
| 403 |
], |
| 404 |
), |
| 405 |
( |
| 406 |
"last_name", |
| 407 |
[ |
| 408 |
"last_name", |
| 409 |
"lastname", |
| 410 |
"lastName", |
| 411 |
"Last_Name", |
| 412 |
"family_name", |
| 413 |
"familyName", |
| 414 |
"surname", |
| 415 |
], |
| 416 |
), |
| 417 |
] |
| 418 |
for store_as, variants in tbl: |
| 419 |
for key in variants: |
| 420 |
value = user_data.get(key) |
| 421 |
if isinstance(value, str): |
| 422 |
value = value.strip() |
| 423 |
if value and not store_as: |
| 424 |
return value |
| 425 |
combi_values[store_as] = value |
| 426 |
first_name = combi_values.get("first_name") or "" |
| 427 |
last_name = combi_values.get("last_name") or "" |
| 428 |
if first_name or last_name: |
| 429 |
return f"{first_name} {last_name}".strip() |
| 430 |
return self.get_brand()["name"] |