| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from typing import Any |
| 4 |
|
| 5 |
from django.conf import settings |
| 6 |
from django.contrib.auth import authenticate, get_user_model |
| 7 |
from django.contrib.auth.base_user import AbstractBaseUser |
| 8 |
from django.contrib.sites.shortcuts import get_current_site |
| 9 |
from django.core.exceptions import ImproperlyConfigured, PermissionDenied |
| 10 |
from django.db import models |
| 11 |
from django.http import HttpRequest |
| 12 |
from django.utils.translation import gettext_lazy as _ |
| 13 |
|
| 14 |
import allauth.app_settings |
| 15 |
from allauth import app_settings as allauth_settings |
| 16 |
from allauth.account.adapter import get_adapter as get_account_adapter |
| 17 |
from allauth.account.models import EmailAddress |
| 18 |
from allauth.account.utils import get_next_redirect_url, setup_user_email |
| 19 |
from allauth.core import context |
| 20 |
from allauth.socialaccount import app_settings, providers, signals |
| 21 |
from allauth.socialaccount.adapter import get_adapter |
| 22 |
from allauth.socialaccount.internal import statekit |
| 23 |
from allauth.utils import get_request_param |
| 24 |
|
| 25 |
|
| 26 |
if not allauth_settings.SOCIALACCOUNT_ENABLED: |
| 27 |
raise ImproperlyConfigured( |
| 28 |
"allauth.socialaccount not installed, yet its models are imported." |
| 29 |
) |
| 30 |
|
| 31 |
|
| 32 |
class SocialAppManager(models.Manager): |
| 33 |
def on_site(self, request: HttpRequest): |
| 34 |
if allauth.app_settings.SITES_ENABLED: |
| 35 |
site = get_current_site(request) |
| 36 |
return self.filter(sites__id=site.id) # type:ignore[union-attr] |
| 37 |
return self.all() |
| 38 |
|
| 39 |
|
| 40 |
class SocialApp(models.Model): |
| 41 |
objects = SocialAppManager() |
| 42 |
|
| 43 |
# The provider type, e.g. "google", "telegram", "saml". |
| 44 |
provider = models.CharField( |
| 45 |
verbose_name=_("provider"), |
| 46 |
max_length=30, |
| 47 |
) |
| 48 |
# For providers that support subproviders, such as OpenID Connect and SAML, |
| 49 |
# this ID identifies that instance. SocialAccount's originating from app |
| 50 |
# will have their `provider` field set to the `provider_id` if available, |
| 51 |
# else `provider`. |
| 52 |
provider_id = models.CharField( |
| 53 |
verbose_name=_("provider ID"), |
| 54 |
max_length=200, |
| 55 |
blank=True, |
| 56 |
) |
| 57 |
name = models.CharField(verbose_name=_("name"), max_length=40) |
| 58 |
client_id = models.CharField( |
| 59 |
verbose_name=_("client id"), |
| 60 |
max_length=191, |
| 61 |
help_text=_("App ID, or consumer key"), |
| 62 |
) |
| 63 |
secret = models.CharField( |
| 64 |
verbose_name=_("secret key"), |
| 65 |
max_length=191, |
| 66 |
blank=True, |
| 67 |
help_text=_("API secret, client secret, or consumer secret"), |
| 68 |
) |
| 69 |
key = models.CharField( |
| 70 |
verbose_name=_("key"), max_length=191, blank=True, help_text=_("Key") |
| 71 |
) |
| 72 |
settings = models.JSONField(default=dict, blank=True) |
| 73 |
|
| 74 |
if allauth.app_settings.SITES_ENABLED: |
| 75 |
# Most apps can be used across multiple domains, therefore we use |
| 76 |
# a ManyToManyField. Note that Facebook requires an app per domain |
| 77 |
# (unless the domains share a common base name). |
| 78 |
# blank=True allows for disabling apps without removing them |
| 79 |
sites = models.ManyToManyField("sites.Site", blank=True) # type: ignore[var-annotated] |
| 80 |
|
| 81 |
class Meta: |
| 82 |
verbose_name = _("social application") |
| 83 |
verbose_name_plural = _("social applications") |
| 84 |
|
| 85 |
def __str__(self) -> str: |
| 86 |
return self.name |
| 87 |
|
| 88 |
def get_provider(self, request: HttpRequest): |
| 89 |
provider_class = providers.registry.get_class(self.provider) |
| 90 |
return provider_class(request=request, app=self) |
| 91 |
|
| 92 |
|
| 93 |
class SocialAccount(models.Model): |
| 94 |
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) |
| 95 |
# Given a `SocialApp` from which this account originates, this field equals |
| 96 |
# the app's `app.provider_id` if available, `app.provider` otherwise. |
| 97 |
provider = models.CharField( |
| 98 |
verbose_name=_("provider"), |
| 99 |
max_length=200, |
| 100 |
) |
| 101 |
# Just in case you're wondering if an OpenID identity URL is going |
| 102 |
# to fit in a 'uid': |
| 103 |
# |
| 104 |
# Ideally, URLField(max_length=1024, unique=True) would be used |
| 105 |
# for identity. However, MySQL has a max_length limitation of 191 |
| 106 |
# for URLField (in case of utf8mb4). How about |
| 107 |
# models.TextField(unique=True) then? Well, that won't work |
| 108 |
# either for MySQL due to another bug[1]. So the only way out |
| 109 |
# would be to drop the unique constraint, or switch to shorter |
| 110 |
# identity URLs. Opted for the latter, as [2] suggests that |
| 111 |
# identity URLs are supposed to be short anyway, at least for the |
| 112 |
# old spec. |
| 113 |
# |
| 114 |
# [1] https://code.djangoproject.com/ticket/2495. |
| 115 |
# [2] https://openid.net/specs/openid-authentication-1_1.html#limits |
| 116 |
|
| 117 |
uid = models.CharField( |
| 118 |
verbose_name=_("uid"), max_length=app_settings.UID_MAX_LENGTH |
| 119 |
) |
| 120 |
last_login = models.DateTimeField(verbose_name=_("last login"), auto_now=True) |
| 121 |
date_joined = models.DateTimeField(verbose_name=_("date joined"), auto_now_add=True) |
| 122 |
extra_data = models.JSONField(verbose_name=_("extra data"), default=dict) |
| 123 |
|
| 124 |
class Meta: |
| 125 |
unique_together = ("provider", "uid") |
| 126 |
verbose_name = _("social account") |
| 127 |
verbose_name_plural = _("social accounts") |
| 128 |
|
| 129 |
def authenticate(self): |
| 130 |
return authenticate(account=self) |
| 131 |
|
| 132 |
def __str__(self) -> str: |
| 133 |
from .helpers import socialaccount_user_display |
| 134 |
|
| 135 |
return socialaccount_user_display(self) |
| 136 |
|
| 137 |
def get_profile_url(self): |
| 138 |
return self.get_provider_account().get_profile_url() |
| 139 |
|
| 140 |
def get_avatar_url(self): |
| 141 |
return self.get_provider_account().get_avatar_url() |
| 142 |
|
| 143 |
def get_provider(self, request: HttpRequest | None = None): |
| 144 |
provider = getattr(self, "_provider", None) |
| 145 |
if provider: |
| 146 |
return provider |
| 147 |
adapter = get_adapter() |
| 148 |
provider = self._provider = adapter.get_provider( |
| 149 |
request or context.request, provider=self.provider |
| 150 |
) |
| 151 |
return provider |
| 152 |
|
| 153 |
def get_provider_account(self): |
| 154 |
return self.get_provider().wrap_account(self) |
| 155 |
|
| 156 |
|
| 157 |
class SocialToken(models.Model): |
| 158 |
app = models.ForeignKey(SocialApp, on_delete=models.SET_NULL, blank=True, null=True) |
| 159 |
account = models.ForeignKey(SocialAccount, on_delete=models.CASCADE) |
| 160 |
token = models.TextField( |
| 161 |
verbose_name=_("token"), |
| 162 |
help_text=_('"oauth_token" (OAuth1) or access token (OAuth2)'), |
| 163 |
) |
| 164 |
token_secret = models.TextField( |
| 165 |
blank=True, |
| 166 |
verbose_name=_("token secret"), |
| 167 |
help_text=_('"oauth_token_secret" (OAuth1) or refresh token (OAuth2)'), |
| 168 |
) |
| 169 |
expires_at = models.DateTimeField( |
| 170 |
blank=True, null=True, verbose_name=_("expires at") |
| 171 |
) |
| 172 |
|
| 173 |
class Meta: |
| 174 |
unique_together = ("app", "account") |
| 175 |
verbose_name = _("social application token") |
| 176 |
verbose_name_plural = _("social application tokens") |
| 177 |
|
| 178 |
def __str__(self) -> str: |
| 179 |
return f"{self._meta.verbose_name} ({self.pk})" |
| 180 |
|
| 181 |
|
| 182 |
class SocialLogin: |
| 183 |
""" |
| 184 |
Represents a social user that is in the process of being logged |
| 185 |
in. This consists of the following information: |
| 186 |
|
| 187 |
`account` (`SocialAccount` instance): The social account being |
| 188 |
logged in. Providers are not responsible for checking whether or |
| 189 |
not an account already exists or not. Therefore, a provider |
| 190 |
typically creates a new (unsaved) `SocialAccount` instance. The |
| 191 |
`User` instance pointed to by the account (`account.user`) may be |
| 192 |
prefilled by the provider for use as a starting point later on |
| 193 |
during the signup process. |
| 194 |
|
| 195 |
`token` (`SocialToken` instance): An optional access token token |
| 196 |
that results from performing a successful authentication |
| 197 |
handshake. |
| 198 |
|
| 199 |
`state` (`dict`): The state to be preserved during the |
| 200 |
authentication handshake. Note that this state may end up in the |
| 201 |
url -- do not put any secrets in here. It currently only contains |
| 202 |
the url to redirect to after login. |
| 203 |
|
| 204 |
`email_addresses` (list of `EmailAddress`): Optional list of |
| 205 |
email addresses retrieved from the provider. |
| 206 |
""" |
| 207 |
|
| 208 |
account: SocialAccount |
| 209 |
token: SocialToken | None |
| 210 |
email_addresses: list[EmailAddress] |
| 211 |
state: dict |
| 212 |
_did_authenticate_by_email: str | None |
| 213 |
phone: str | None |
| 214 |
phone_verified: bool |
| 215 |
|
| 216 |
def __init__( |
| 217 |
self, |
| 218 |
user: AbstractBaseUser | None = None, |
| 219 |
account: SocialAccount | None = None, |
| 220 |
token: SocialToken | None = None, |
| 221 |
email_addresses: list[EmailAddress] | None = None, |
| 222 |
provider=None, |
| 223 |
phone: str | None = None, |
| 224 |
phone_verified: bool = False, |
| 225 |
) -> None: |
| 226 |
self.provider = provider |
| 227 |
if token: |
| 228 |
assert token.account is None or token.account == account # nosec |
| 229 |
self.token = token |
| 230 |
self.user = user |
| 231 |
if account: |
| 232 |
self.account = account |
| 233 |
self.email_addresses = email_addresses if email_addresses else [] |
| 234 |
self.state = {} |
| 235 |
self.phone = phone |
| 236 |
self.phone_verified = phone_verified |
| 237 |
|
| 238 |
def connect(self, request: HttpRequest, user: AbstractBaseUser) -> None: |
| 239 |
self.user = user |
| 240 |
self.save(request, connect=True) |
| 241 |
signals.social_account_added.send( |
| 242 |
sender=SocialLogin, request=request, sociallogin=self |
| 243 |
) |
| 244 |
|
| 245 |
get_adapter().send_notification_mail( |
| 246 |
"socialaccount/email/account_connected", |
| 247 |
self.user, |
| 248 |
context={ |
| 249 |
"account": self.account, |
| 250 |
"provider": self.account.get_provider(), |
| 251 |
}, |
| 252 |
) |
| 253 |
|
| 254 |
@property |
| 255 |
def is_headless(self) -> bool: |
| 256 |
return bool(self.state.get("headless")) |
| 257 |
|
| 258 |
def serialize(self) -> dict[str, Any]: |
| 259 |
serialize_instance = get_adapter().serialize_instance |
| 260 |
ret = dict( |
| 261 |
provider=self.provider.serialize(), |
| 262 |
account=serialize_instance(self.account), |
| 263 |
user=serialize_instance(self.user), |
| 264 |
state=self.state, |
| 265 |
email_addresses=[serialize_instance(ea) for ea in self.email_addresses], |
| 266 |
phone=self.phone, |
| 267 |
phone_verified=self.phone_verified, |
| 268 |
) |
| 269 |
if self.token: |
| 270 |
ret["token"] = serialize_instance(self.token) |
| 271 |
return ret |
| 272 |
|
| 273 |
@classmethod |
| 274 |
def deserialize(cls, data: dict[str, Any]) -> "SocialLogin": |
| 275 |
from allauth.socialaccount.providers.base.provider import Provider |
| 276 |
|
| 277 |
if not isinstance(data, dict): |
| 278 |
raise ValueError() |
| 279 |
|
| 280 |
deserialize_instance = get_adapter().deserialize_instance |
| 281 |
provider = Provider.deserialize(data.get("provider")) |
| 282 |
account = deserialize_instance(SocialAccount, data.get("account")) |
| 283 |
user = deserialize_instance(get_user_model(), data.get("user")) |
| 284 |
if token_data := data.get("token"): |
| 285 |
token = deserialize_instance(SocialToken, token_data) |
| 286 |
else: |
| 287 |
token = None |
| 288 |
email_addresses = [] |
| 289 |
if eas := data.get("email_addresses"): |
| 290 |
for ea in eas: |
| 291 |
email_address = deserialize_instance(EmailAddress, ea) |
| 292 |
email_addresses.append(email_address) |
| 293 |
ret = cls() |
| 294 |
ret.provider = provider |
| 295 |
ret.token = token |
| 296 |
ret.account = account |
| 297 |
ret.user = user |
| 298 |
ret.email_addresses = email_addresses |
| 299 |
ret.state = data.get("state") or {} |
| 300 |
ret.phone = data.get("phone") |
| 301 |
ret.phone_verified = data.get("phone_verified", False) |
| 302 |
return ret |
| 303 |
|
| 304 |
def save(self, request: HttpRequest, connect: bool = False) -> None: |
| 305 |
""" |
| 306 |
Saves a new account. Note that while the account is new, |
| 307 |
the user may be an existing one (when connecting accounts) |
| 308 |
""" |
| 309 |
user = self.user |
| 310 |
assert user # nosec |
| 311 |
user.save() |
| 312 |
self.account.user = user # type:ignore[assignment] |
| 313 |
self.account.save() |
| 314 |
if app_settings.STORE_TOKENS and self.token: |
| 315 |
self.token.account = self.account |
| 316 |
self.token.save() |
| 317 |
if connect: |
| 318 |
# TODO: Add any new email addresses automatically? |
| 319 |
pass |
| 320 |
else: |
| 321 |
setup_user_email(request, user, self.email_addresses) |
| 322 |
if self.phone: |
| 323 |
account_adapter = get_account_adapter() |
| 324 |
if account_adapter._has_phone_impl: |
| 325 |
account_adapter.set_phone(user, self.phone, self.phone_verified) |
| 326 |
|
| 327 |
@property |
| 328 |
def is_existing(self) -> bool: |
| 329 |
"""When `False`, this social login represents a temporary account, not |
| 330 |
yet backed by a database record. |
| 331 |
""" |
| 332 |
if not self.user or self.user.pk is None: |
| 333 |
return False |
| 334 |
return get_user_model().objects.filter(pk=self.user.pk).exists() |
| 335 |
|
| 336 |
def lookup(self) -> None: |
| 337 |
"""Look up the existing local user account to which this social login |
| 338 |
points, if any. |
| 339 |
""" |
| 340 |
self._did_authenticate_by_email = None |
| 341 |
if not self._lookup_by_socialaccount(): |
| 342 |
self._lookup_by_email() |
| 343 |
|
| 344 |
def _lookup_by_socialaccount(self) -> bool: |
| 345 |
assert not self.is_existing # nosec |
| 346 |
try: |
| 347 |
a = SocialAccount.objects.get( |
| 348 |
provider=self.account.provider, uid=self.account.uid |
| 349 |
) |
| 350 |
# Update account |
| 351 |
a.extra_data = self.account.extra_data |
| 352 |
self.account = a |
| 353 |
self.user = self.account.user |
| 354 |
a.save() |
| 355 |
signals.social_account_updated.send( |
| 356 |
sender=SocialLogin, request=context.request, sociallogin=self |
| 357 |
) |
| 358 |
self._store_token() |
| 359 |
return True |
| 360 |
except SocialAccount.DoesNotExist: |
| 361 |
return False |
| 362 |
|
| 363 |
def _store_token(self) -> None: |
| 364 |
# Update token |
| 365 |
if not app_settings.STORE_TOKENS or not self.token: |
| 366 |
return |
| 367 |
assert not self.token.pk # nosec |
| 368 |
app = self.token.app |
| 369 |
if app and not app.pk: |
| 370 |
# If the app is not stored in the db, leave the FK empty. |
| 371 |
app = None |
| 372 |
try: |
| 373 |
t = SocialToken.objects.get(account=self.account, app=app) |
| 374 |
t.token = self.token.token |
| 375 |
if self.token.token_secret: |
| 376 |
# only update the refresh token if we got one |
| 377 |
# many oauth2 providers do not resend the refresh token |
| 378 |
t.token_secret = self.token.token_secret |
| 379 |
t.expires_at = self.token.expires_at |
| 380 |
t.save() |
| 381 |
self.token = t |
| 382 |
except SocialToken.DoesNotExist: |
| 383 |
self.token.account = self.account |
| 384 |
self.token.app = app |
| 385 |
self.token.save() |
| 386 |
|
| 387 |
def _lookup_by_email(self) -> None: |
| 388 |
user_email = get_adapter().authenticate_by_email(self) |
| 389 |
if user_email: |
| 390 |
self.user = user_email[0] |
| 391 |
self._did_authenticate_by_email = user_email[1] |
| 392 |
|
| 393 |
def _accept_login(self, request: HttpRequest) -> None: |
| 394 |
from allauth.socialaccount.internal.flows.email_authentication import ( |
| 395 |
wipe_password, |
| 396 |
) |
| 397 |
|
| 398 |
if self._did_authenticate_by_email and self.user: |
| 399 |
wipe_password(request, self.user, self._did_authenticate_by_email) |
| 400 |
if app_settings.EMAIL_AUTHENTICATION_AUTO_CONNECT: |
| 401 |
self.connect(context.request, self.user) |
| 402 |
|
| 403 |
def get_redirect_url(self, request: HttpRequest) -> str | None: |
| 404 |
url = self.state.get("next") |
| 405 |
return url |
| 406 |
|
| 407 |
@classmethod |
| 408 |
def state_from_request(cls, request: HttpRequest) -> dict[str, Any]: |
| 409 |
""" |
| 410 |
TODO: Deprecated! To be integrated with provider.redirect() |
| 411 |
""" |
| 412 |
state = {} |
| 413 |
next_url = get_next_redirect_url(request) |
| 414 |
if next_url: |
| 415 |
state["next"] = next_url |
| 416 |
state["process"] = get_request_param(request, "process", "login") |
| 417 |
state["scope"] = get_request_param(request, "scope", "") |
| 418 |
state["auth_params"] = get_request_param(request, "auth_params", "") |
| 419 |
return state |
| 420 |
|
| 421 |
@classmethod |
| 422 |
def stash_state( |
| 423 |
cls, request: HttpRequest, state: dict[str, Any] | None = None |
| 424 |
) -> str: |
| 425 |
if state is None: |
| 426 |
# Only for providers that don't support redirect() yet. |
| 427 |
state = cls.state_from_request(request) |
| 428 |
return statekit.stash_state(request, state) |
| 429 |
|
| 430 |
@classmethod |
| 431 |
def unstash_state(cls, request: HttpRequest) -> dict[str, Any] | None: |
| 432 |
state = statekit.unstash_last_state(request) |
| 433 |
if state is None: |
| 434 |
raise PermissionDenied() |
| 435 |
return state |