| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from django import forms |
| 4 |
from django.contrib.auth.models import AbstractBaseUser |
| 5 |
from django.http import HttpRequest |
| 6 |
|
| 7 |
from allauth.account.forms import BaseSignupForm |
| 8 |
from allauth.socialaccount.internal import flows |
| 9 |
|
| 10 |
from . import app_settings |
| 11 |
from .adapter import get_adapter |
| 12 |
from .models import SocialAccount |
| 13 |
|
| 14 |
|
| 15 |
class SignupForm(BaseSignupForm): |
| 16 |
def __init__(self, *args, **kwargs) -> None: |
| 17 |
self.sociallogin = kwargs.pop("sociallogin") |
| 18 |
initial = get_adapter().get_signup_form_initial_data(self.sociallogin) |
| 19 |
kwargs.update( |
| 20 |
{ |
| 21 |
"initial": initial, |
| 22 |
"email_required": kwargs.get( |
| 23 |
"email_required", app_settings.EMAIL_REQUIRED |
| 24 |
), |
| 25 |
} |
| 26 |
) |
| 27 |
super().__init__(*args, **kwargs) |
| 28 |
|
| 29 |
def save(self, request: HttpRequest) -> AbstractBaseUser: |
| 30 |
adapter = get_adapter() |
| 31 |
user = adapter.save_user(request, self.sociallogin, form=self) |
| 32 |
self.custom_signup(request, user) |
| 33 |
return user |
| 34 |
|
| 35 |
def validate_unique_email(self, value) -> str: |
| 36 |
try: |
| 37 |
return super().validate_unique_email(value) |
| 38 |
except forms.ValidationError: |
| 39 |
raise get_adapter().validation_error( |
| 40 |
"email_taken", self.sociallogin.provider.name |
| 41 |
) |
| 42 |
|
| 43 |
|
| 44 |
class DisconnectForm(forms.Form): |
| 45 |
account = forms.ModelChoiceField( |
| 46 |
queryset=SocialAccount.objects.none(), |
| 47 |
widget=forms.RadioSelect, |
| 48 |
required=True, |
| 49 |
) |
| 50 |
|
| 51 |
def __init__(self, *args, **kwargs) -> None: |
| 52 |
self.request = kwargs.pop("request") |
| 53 |
self.accounts = SocialAccount.objects.filter(user=self.request.user) |
| 54 |
super().__init__(*args, **kwargs) |
| 55 |
account_field: forms.ModelChoiceField = self.fields["account"] # type: ignore[assignment] |
| 56 |
account_field.queryset = self.accounts |
| 57 |
|
| 58 |
def clean(self): |
| 59 |
cleaned_data = super().clean() |
| 60 |
account = cleaned_data.get("account") |
| 61 |
if account: |
| 62 |
flows.connect.validate_disconnect(self.request, account) |
| 63 |
return cleaned_data |
| 64 |
|
| 65 |
def save(self) -> None: |
| 66 |
account = self.cleaned_data["account"] |
| 67 |
flows.connect.disconnect(self.request, account) |