| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from django.http import HttpRequest |
| 4 |
|
| 5 |
from allauth.socialaccount.providers.base import AuthAction, ProviderAccount |
| 6 |
from allauth.socialaccount.providers.oauth.provider import OAuthProvider |
| 7 |
from allauth.socialaccount.providers.twitter.views import TwitterOAuthAdapter |
| 8 |
|
| 9 |
|
| 10 |
class TwitterAccount(ProviderAccount): |
| 11 |
def get_screen_name(self): |
| 12 |
"""The screen name is the username of the Twitter account.""" |
| 13 |
return self.account.extra_data.get("screen_name") |
| 14 |
|
| 15 |
def get_profile_url(self): |
| 16 |
ret = None |
| 17 |
screen_name = self.get_screen_name() |
| 18 |
if screen_name: |
| 19 |
ret = f"https://x.com/{screen_name}" |
| 20 |
return ret |
| 21 |
|
| 22 |
def get_avatar_url(self): |
| 23 |
ret = None |
| 24 |
profile_image_url = self.account.extra_data.get("profile_image_url") |
| 25 |
if profile_image_url: |
| 26 |
# Hmm, hack to get our hands on the large image. Not |
| 27 |
# really documented, but seems to work. |
| 28 |
ret = profile_image_url.replace("_normal", "") |
| 29 |
return ret |
| 30 |
|
| 31 |
def to_str(self): |
| 32 |
screen_name = self.get_screen_name() |
| 33 |
return screen_name or super().to_str() |
| 34 |
|
| 35 |
|
| 36 |
class TwitterProvider(OAuthProvider): |
| 37 |
id = "twitter" |
| 38 |
name = "X" |
| 39 |
account_class = TwitterAccount |
| 40 |
oauth_adapter_class = TwitterOAuthAdapter |
| 41 |
|
| 42 |
def get_auth_url(self, request: HttpRequest, action): |
| 43 |
if action == AuthAction.REAUTHENTICATE: |
| 44 |
url = "https://api.x.com/oauth/authorize" |
| 45 |
else: |
| 46 |
url = "https://api.x.com/oauth/authenticate" |
| 47 |
return url |
| 48 |
|
| 49 |
def extract_uid(self, data): |
| 50 |
return str(data["id"]) |
| 51 |
|
| 52 |
def extract_common_fields(self, data): |
| 53 |
return dict( |
| 54 |
username=data.get("screen_name"), |
| 55 |
name=data.get("name"), |
| 56 |
email=data.get("email"), |
| 57 |
) |
| 58 |
|
| 59 |
|
| 60 |
provider_classes = [TwitterProvider] |