Beispiel #1
0
class AddEmailForm(UserForm):

    email = forms.EmailField(
        label=_("E-mail"),
        required=True,
        widget=forms.TextInput(
            attrs={"type": "email",
                   "size": "30",
                   "placeholder": _('E-mail address')}))

    def clean_email(self):
        value = self.cleaned_data["email"]
        value = get_adapter().clean_email(value)
        errors = {
            "this_account": _("This e-mail address is already associated"
                              " with this account."),
            "different_account": _("This e-mail address is already associated"
                                   " with another account."),
        }
        users = filter_users_by_email(value)
        on_this_account = [u for u in users if u.pk == self.user.pk]
        on_diff_account = [u for u in users if u.pk != self.user.pk]

        if on_this_account:
            raise forms.ValidationError(errors["this_account"])
        if on_diff_account and app_settings.UNIQUE_EMAIL:
            raise forms.ValidationError(errors["different_account"])
        return value

    def save(self, request):
        return EmailAddress.objects.add_email(request,
                                              self.user,
                                              self.cleaned_data["email"],
                                              confirm=True)
Beispiel #2
0
 def __init__(self, *args, **kwargs):
     self.request = kwargs.pop('request', None)
     super(LoginForm, self).__init__(*args, **kwargs)
     if app_settings.AUTHENTICATION_METHOD == AuthenticationMethod.EMAIL:
         login_widget = forms.TextInput(attrs={'type': 'email',
                                               'placeholder':
                                               _('Enter email'),
                                               'autofocus': 'autofocus'})
         login_field = forms.EmailField(label=_("E-mail"),
                                        widget=login_widget)
     elif app_settings.AUTHENTICATION_METHOD \
             == AuthenticationMethod.USERNAME:
         login_widget = forms.TextInput(attrs={'placeholder':
                                               _('Enter username'),
                                               'autofocus': 'autofocus'})
         login_field = forms.CharField(
             label=_("Username"),
             widget=login_widget,
             max_length=get_username_max_length())
     else:
         assert app_settings.AUTHENTICATION_METHOD \
             == AuthenticationMethod.USERNAME_EMAIL
         login_widget = forms.TextInput(attrs={'placeholder':
                                               _('Username or e-mail'),
                                               'autofocus': 'autofocus'})
         login_field = forms.CharField(label=pgettext("field label",
                                                      "Login"),
                                       widget=login_widget)
     self.fields["login"] = login_field
     set_form_field_order(self, ["login", "password", "remember"])
     if app_settings.SESSION_REMEMBER is not None:
         del self.fields['remember']
Beispiel #3
0
    def __init__(self, *args, **kwargs):
        email_required = kwargs.pop('email_required',
                                    app_settings.EMAIL_REQUIRED)
        self.username_required = kwargs.pop('username_required',
                                            app_settings.USERNAME_REQUIRED)
        super(BaseSignupForm, self).__init__(*args, **kwargs)
        username_field = self.fields['username']
        username_field.max_length = get_username_max_length()
        username_field.validators.append(
            validators.MaxLengthValidator(username_field.max_length))
        username_field.widget.attrs['maxlength'] = str(
            username_field.max_length)

        default_field_order = [
            'email',
            'email2',  # ignored when not present
            'username',
            'first_name',
            'last_name',
            'description',
            'image',
            'password1',
            'password2'  # ignored when not present
        ]
        if app_settings.SIGNUP_EMAIL_ENTER_TWICE:
            self.fields["email2"] = forms.EmailField(
                label=_("E-mail (again)"),
                widget=forms.TextInput(
                    attrs={
                        'type': 'email',
                        'placeholder': _('E-mail address confirmation')
                    }))
        if email_required:
            self.fields['email'].label = ugettext("E-mail")
            self.fields['email'].required = True
        else:
            self.fields['email'].label = ugettext("E-mail (optional)")
            self.fields['email'].required = False
            self.fields['email'].widget.is_required = False
            if self.username_required:
                default_field_order = [
                    'email',
                    'email2',  # ignored when not present
                    'username',
                    'first_name',
                    'last_name',
                    'description',
                    'image',
                    'password1',
                    'password2'
                ]

        if not self.username_required:
            del self.fields["username"]

        set_form_field_order(
            self,
            getattr(self, 'field_order', None) or default_field_order)
Beispiel #4
0
class ResetPasswordForm(forms.Form):

    email = forms.EmailField(
        label=_("E-mail"),
        required=True,
        widget=forms.TextInput(attrs={
            "type": "email",
            "size": "30",
            "placeholder": _("E-mail address"),
        }))

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super(ResetPasswordForm, self).__init__(*args, **kwargs)

    def clean_email(self):
        email = self.cleaned_data["email"]
        email = get_adapter().clean_email(email)
        self.users = filter_users_by_email(email, self.request)
        if not self.users:
            raise forms.ValidationError(
                _("The e-mail address is not assigned"
                  " to any user account"))
        return self.cleaned_data["email"]

    def save(self, request, **kwargs):
        current_site = get_current_site(request)
        email = self.cleaned_data["email"]
        token_generator = kwargs.get("token_generator",
                                     default_token_generator)

        for user in self.users:

            temp_key = token_generator.make_token(user)

            # save it to the password reset model
            # password_reset = PasswordReset(user=user, temp_key=temp_key)
            # password_reset.save()

            # send the password reset email
            path = reverse("account_reset_password_from_key",
                           kwargs=dict(uidb36=user_pk_to_url_str(user),
                                       key=temp_key))
            url = build_absolute_uri(request, path)

            context = {
                "current_site": current_site,
                "user": user,
                "password_reset_url": url,
                "request": request
            }

            if app_settings.AUTHENTICATION_METHOD \
                    != AuthenticationMethod.EMAIL:
                context['username'] = user_username(user)
            get_adapter(request).send_mail('account/email/password_reset_key',
                                           email, context)
        return self.cleaned_data["email"]
Beispiel #5
0
    def __init__(self, *args, **kwargs):
        super(SignupForm, self).__init__(*args, **kwargs)
        self.fields['password1'] = PasswordField(label=_("Password"))
        if app_settings.SIGNUP_PASSWORD_ENTER_TWICE:
            self.fields['password2'] = PasswordField(
                label=_("Password (again)"))

        if hasattr(self, 'field_order'):
            set_form_field_order(self, self.field_order)
Beispiel #6
0
class EmailAddress(models.Model):

    user = models.ForeignKey(allauth_app_settings.USER_MODEL,
                             verbose_name=_('user'),
                             on_delete=models.CASCADE)
    email = models.EmailField(unique=app_settings.UNIQUE_EMAIL,
                              max_length=app_settings.EMAIL_MAX_LENGTH,
                              verbose_name=_('e-mail address'))
    verified = models.BooleanField(verbose_name=_('verified'), default=False)
    primary = models.BooleanField(verbose_name=_('primary'), default=False)

    objects = EmailAddressManager()

    class Meta:
        verbose_name = _("email address")
        verbose_name_plural = _("email addresses")
        if not app_settings.UNIQUE_EMAIL:
            unique_together = [("user", "email")]

    def __str__(self):
        return "%s (%s)" % (self.email, self.user)

    def set_as_primary(self, conditional=False):
        old_primary = EmailAddress.objects.get_primary(self.user)
        if old_primary:
            if conditional:
                return False
            old_primary.primary = False
            old_primary.save()
        self.primary = True
        self.save()
        user_email(self.user, self.email)
        self.user.save()
        return True

    def send_confirmation(self, request=None, signup=False):
        if app_settings.EMAIL_CONFIRMATION_HMAC:
            confirmation = EmailConfirmationHMAC(self)
        else:
            confirmation = EmailConfirmation.create(self)
        confirmation.send(request, signup=signup)
        return confirmation

    def change(self, request, new_email, confirm=True):
        """
        Given a new email address, change self and re-confirm.
        """
        with transaction.atomic():
            user_email(self.user, new_email)
            self.user.save()
            self.email = new_email
            self.verified = False
            self.save()
            if confirm:
                self.send_confirmation(request)
Beispiel #7
0
class SetPasswordForm(PasswordVerificationMixin, UserForm):

    password1 = SetPasswordField(label=_("Password"))
    password2 = PasswordField(label=_("Password (again)"))

    def __init__(self, *args, **kwargs):
        super(SetPasswordForm, self).__init__(*args, **kwargs)
        self.fields['password1'].user = self.user

    def save(self):
        get_adapter().set_password(self.user, self.cleaned_data["password1"])
Beispiel #8
0
class CustomAdapter(DefaultAccountAdapter):
    error_messages = {
        'username_blacklisted':
        _('Username can not be used. Please use other username.'),
        'username_taken':
        User._meta.get_field('username').error_messages['unique'],
        'too_many_login_attempts':
        _('Demasiados intentos de inicio de sesion. Intente mas tarde.'),
        'email_taken':
        _("Este correo ya ha sido registrado."),
    }
Beispiel #9
0
class SocialAccount(models.Model):
    user = models.ForeignKey(allauth.app_settings.USER_MODEL,
                             on_delete=models.CASCADE)
    provider = models.CharField(verbose_name=_('provider'),
                                max_length=30,
                                choices=providers.registry.as_choices())
    # Just in case you're wondering if an OpenID identity URL is going
    # to fit in a 'uid':
    #
    # Ideally, URLField(max_length=1024, unique=True) would be used
    # for identity.  However, MySQL has a max_length limitation of 191
    # for URLField (in case of utf8mb4). How about
    # models.TextField(unique=True) then?  Well, that won't work
    # either for MySQL due to another bug[1]. So the only way out
    # would be to drop the unique constraint, or switch to shorter
    # identity URLs. Opted for the latter, as [2] suggests that
    # identity URLs are supposed to be short anyway, at least for the
    # old spec.
    #
    # [1] http://code.djangoproject.com/ticket/2495.
    # [2] http://openid.net/specs/openid-authentication-1_1.html#limits

    uid = models.CharField(verbose_name=_('uid'),
                           max_length=app_settings.UID_MAX_LENGTH)
    last_login = models.DateTimeField(verbose_name=_('last login'),
                                      auto_now=True)
    date_joined = models.DateTimeField(verbose_name=_('date joined'),
                                       auto_now_add=True)
    extra_data = JSONField(verbose_name=_('extra data'), default=dict)

    class Meta:
        unique_together = ('provider', 'uid')
        verbose_name = _('social account')
        verbose_name_plural = _('social accounts')

    def authenticate(self):
        return authenticate(account=self)

    def __str__(self):
        return force_str(self.user)

    def get_profile_url(self):
        return self.get_provider_account().get_profile_url()

    def get_avatar_url(self):
        return self.get_provider_account().get_avatar_url()

    def get_provider(self):
        return providers.registry.by_id(self.provider)

    def get_provider_account(self):
        return self.get_provider().wrap_account(self)
Beispiel #10
0
class ResetPasswordKeyForm(PasswordVerificationMixin, forms.Form):

    password1 = SetPasswordField(label=_("New Password"))
    password2 = PasswordField(label=_("New Password (again)"))

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop("user", None)
        self.temp_key = kwargs.pop("temp_key", None)
        super(ResetPasswordKeyForm, self).__init__(*args, **kwargs)
        self.fields['password1'].user = self.user

    def save(self):
        get_adapter().set_password(self.user, self.cleaned_data["password1"])
Beispiel #11
0
class CustomLoginForm(LoginForm):

    error_messages = {
        'account_inactive':
        _("Esta cuenta es inactiva."),

        'email_password_mismatch':
        _("El correo/ó la contraseña especificados no son correctos."),
    }

    def __init__(self, *args, **kwargs):
        super(CustomLoginForm, self).__init__(*args, **kwargs)
        self.fields['login'].widget.attrs.pop("autofocus", None)
Beispiel #12
0
class SocialApp(models.Model):
    objects = SocialAppManager()

    provider = models.CharField(verbose_name=_('provider'),
                                max_length=30,
                                choices=providers.registry.as_choices())
    name = models.CharField(verbose_name=_('name'), max_length=40)
    client_id = models.CharField(verbose_name=_('client id'),
                                 max_length=191,
                                 help_text=_('App ID, or consumer key'))
    secret = models.CharField(verbose_name=_('secret key'),
                              max_length=191,
                              help_text=_('API secret, client secret, or'
                                          ' consumer secret'))
    key = models.CharField(verbose_name=_('key'),
                           max_length=191,
                           blank=True,
                           help_text=_('Key'))
    # Most apps can be used across multiple domains, therefore we use
    # a ManyToManyField. Note that Facebook requires an app per domain
    # (unless the domains share a common base name).
    # blank=True allows for disabling apps without removing them
    sites = models.ManyToManyField(Site, blank=True)

    class Meta:
        verbose_name = _('social application')
        verbose_name_plural = _('social applications')

    def __str__(self):
        return self.name
Beispiel #13
0
class EmailConfirmation(models.Model):

    email_address = models.ForeignKey(EmailAddress,
                                      verbose_name=_('e-mail address'),
                                      on_delete=models.CASCADE)
    created = models.DateTimeField(verbose_name=_('created'),
                                   default=timezone.now)
    sent = models.DateTimeField(verbose_name=_('sent'), null=True)
    key = models.CharField(verbose_name=_('key'), max_length=64, unique=True)

    objects = EmailConfirmationManager()

    class Meta:
        verbose_name = _("email confirmation")
        verbose_name_plural = _("email confirmations")

    def __str__(self):
        return "confirmation for %s" % self.email_address

    @classmethod
    def create(cls, email_address):
        key = get_random_string(64).lower()
        return cls._default_manager.create(email_address=email_address,
                                           key=key)

    def key_expired(self):
        expiration_date = self.sent \
            + datetime.timedelta(days=app_settings
                                 .EMAIL_CONFIRMATION_EXPIRE_DAYS)
        return expiration_date <= timezone.now()

    key_expired.boolean = True

    def confirm(self, request):
        if not self.key_expired() and not self.email_address.verified:
            email_address = self.email_address
            get_adapter(request).confirm_email(request, email_address)
            signals.email_confirmed.send(sender=self.__class__,
                                         request=request,
                                         email_address=email_address)
            return email_address

    def send(self, request=None, signup=False):
        get_adapter(request).send_confirmation_mail(request, self, signup)
        self.sent = timezone.now()
        self.save()
        signals.email_confirmation_sent.send(sender=self.__class__,
                                             request=request,
                                             confirmation=self,
                                             signup=signup)
Beispiel #14
0
    def __init__(self, *args, **kwargs):
        super(SignupForm, self).__init__(*args, **kwargs)

        # -------
        self.fields['test'] = forms.CharField(label=_("Not Robot enter 1:"), min_length=1, widget=forms.TextInput(
            attrs={'placeholder': _('Type 1 '), 'autofocus': 'autofocus', 'style': 'border:1px solid lightblue'}))
        # -------

        self.fields['password1'] = PasswordField(label=_("Enter password"))

        if app_settings.SIGNUP_PASSWORD_ENTER_TWICE:
            self.fields['password2'] = PasswordField(label=_("Enter password (again)"))

        if hasattr(self, 'field_order'):
            set_form_field_order(self, self.field_order)
Beispiel #15
0
class UserTokenForm(forms.Form):

    uidb36 = forms.CharField()
    key = forms.CharField()

    reset_user = None
    token_generator = default_token_generator

    error_messages = {
        'token_invalid': _('The password reset token was invalid.'),
    }

    def _get_user(self, uidb36):
        User = get_user_model()
        try:
            pk = url_str_to_user_pk(uidb36)
            return User.objects.get(pk=pk)
        except (ValueError, User.DoesNotExist):
            return None

    def clean(self):
        cleaned_data = super(UserTokenForm, self).clean()

        uidb36 = cleaned_data.get('uidb36', None)
        key = cleaned_data.get('key', None)

        if not key:
            raise forms.ValidationError(self.error_messages['token_invalid'])

        self.reset_user = self._get_user(uidb36)
        if (self.reset_user is None
                or not self.token_generator.check_token(self.reset_user, key)):
            raise forms.ValidationError(self.error_messages['token_invalid'])

        return cleaned_data
Beispiel #16
0
    def clean(self):
        super(SignupForm, self).clean()

        # `password` cannot be of type `SetPasswordField`, as we don't
        # have a `User` yet. So, let's populate a dummy user to be used
        # for password validaton.
        dummy_user = get_user_model()
        user_username(dummy_user, self.cleaned_data.get("username"))
        user_email(dummy_user, self.cleaned_data.get("email"))
        password = self.cleaned_data.get('password1')

        # --------
        test = self.cleaned_data.get('test')
        if int(test) != 1:
            self.add_error('test', "Sorry, You must answer the test question 1+0=")
            # raise Exception("Sorry, You must answer the test question")
        # --------

        if password:
            try:
                get_adapter().clean_password(
                    password,
                    user=dummy_user)
            except forms.ValidationError as e:
                self.add_error('password1', e)

        if app_settings.SIGNUP_PASSWORD_ENTER_TWICE \
                and "password1" in self.cleaned_data \
                and "password2" in self.cleaned_data:
            if self.cleaned_data["password1"] \
                    != self.cleaned_data["password2"]:
                self.add_error(
                    'password2',
                    _("You must type the same password each time."))
        return self.cleaned_data
Beispiel #17
0
 def clean(self):
     cleaned_data = super(PasswordVerificationMixin, self).clean()
     password1 = cleaned_data.get('password1')
     password2 = cleaned_data.get('password2')
     if (password1 and password2) and password1 != password2:
         self.add_error('password2',
                        _("You must type the same password each time."))
     return cleaned_data
Beispiel #18
0
 def validate_disconnect(self, account, accounts):
     """
     Validate whether or not the socialaccount account can be
     safely disconnected.
     """
     if len(accounts) == 1:
         # No usable password would render the local account unusable
         if not account.user.has_usable_password():
             raise ValidationError(_("Your account has no password set"
                                     " up."))
         # No email address, no password reset
         if app_settings.EMAIL_VERIFICATION \
                 == EmailVerificationMethod.MANDATORY:
             if EmailAddress.objects.filter(user=account.user,
                                            verified=True).count() == 0:
                 raise ValidationError(_("Your account has no verified"
                                         " e-mail address."))
Beispiel #19
0
 def clean_email(self):
     email = self.cleaned_data["email"]
     email = get_adapter().clean_email(email)
     self.users = filter_users_by_email(email)
     if not self.users:
         raise forms.ValidationError(_("The e-mail address is not assigned"
                                       " to any user account"))
     return self.cleaned_data["email"]
Beispiel #20
0
 def clean(self):
     cleaned_data = super(BaseSignupForm, self).clean()
     if app_settings.SIGNUP_EMAIL_ENTER_TWICE:
         email = cleaned_data.get('email')
         email2 = cleaned_data.get('email2')
         if (email and email2) and email != email2:
             self.add_error('email2',
                            _("You must type the same email each time."))
     return cleaned_data
Beispiel #21
0
    def clean_email(self):
        value = self.cleaned_data["email"]
        value = get_adapter().clean_email(value)
        errors = {
            "this_account": _("This e-mail address is already associated"
                              " with this account."),
            "different_account": _("This e-mail address is already associated"
                                   " with another account."),
        }
        users = filter_users_by_email(value)
        on_this_account = [u for u in users if u.pk == self.user.pk]
        on_diff_account = [u for u in users if u.pk != self.user.pk]

        if on_this_account:
            raise forms.ValidationError(errors["this_account"])
        if on_diff_account and app_settings.UNIQUE_EMAIL:
            raise forms.ValidationError(errors["different_account"])
        return value
Beispiel #22
0
class ChangePasswordForm(PasswordVerificationMixin, UserForm):

    oldpassword = PasswordField(label=_("Current Password"))
    password1 = SetPasswordField(label=_("New Password"))
    password2 = PasswordField(label=_("New Password (again)"))

    def __init__(self, *args, **kwargs):
        super(ChangePasswordForm, self).__init__(*args, **kwargs)
        self.fields['password1'].user = self.user

    def clean_oldpassword(self):
        if not self.user.check_password(self.cleaned_data.get("oldpassword")):
            raise forms.ValidationError(_("Please type your current"
                                          " password."))
        return self.cleaned_data["oldpassword"]

    def save(self):
        get_adapter().set_password(self.user, self.cleaned_data["password1"])
Beispiel #23
0
 def validate_disconnect(self, account, accounts):
     """
     Validate whether or not the socialaccount account can be
     safely disconnected.
     """
     if len(accounts) == 1:
         # No usable password would render the local account unusable
         if not account.user.has_usable_password():
             raise ValidationError(
                 _("Your account has no password set"
                   " up."))
         # No email address, no password reset
         if app_settings.EMAIL_VERIFICATION \
                 == EmailVerificationMethod.MANDATORY:
             if EmailAddress.objects.filter(user=account.user,
                                            verified=True).count() == 0:
                 raise ValidationError(
                     _("Your account has no verified"
                       " e-mail address."))
Beispiel #24
0
 def clean_password(self, password, user=None):
     """
     Validates a password. You can hook into this if you want to
     restric the allowed password choices.
     """
     min_length = app_settings.PASSWORD_MIN_LENGTH
     if min_length and len(password) < min_length:
         raise forms.ValidationError(_("Password must be a minimum of {0} "
                                       "characters.").format(min_length))
     validate_password(password, user)
     return password
Beispiel #25
0
class SocialToken(models.Model):
    app = models.ForeignKey(SocialApp, on_delete=models.CASCADE)
    account = models.ForeignKey(SocialAccount, on_delete=models.CASCADE)
    token = models.TextField(
        verbose_name=_('token'),
        help_text=_('"oauth_token" (OAuth1) or access token (OAuth2)'))
    token_secret = models.TextField(
        blank=True,
        verbose_name=_('token secret'),
        help_text=_('"oauth_token_secret" (OAuth1) or refresh token (OAuth2)'))
    expires_at = models.DateTimeField(blank=True,
                                      null=True,
                                      verbose_name=_('expires at'))

    class Meta:
        unique_together = ('app', 'account')
        verbose_name = _('social application token')
        verbose_name_plural = _('social application tokens')

    def __str__(self):
        return self.token
Beispiel #26
0
 def clean_password(self, password, user=None):
     """
     Validates a password. You can hook into this if you want to
     restric the allowed password choices.
     """
     min_length = app_settings.PASSWORD_MIN_LENGTH
     if min_length and len(password) < min_length:
         raise forms.ValidationError(
             _("Password must be a minimum of {0} "
               "characters.").format(min_length))
     validate_password(password, user)
     return password
Beispiel #27
0
    def complete_login(self, request, app, token, **kwargs):
        headers = {'Authorization': 'Bearer %s' % token.token}
        resp = requests.get(self.profile_url, headers=headers)
        extra_data = resp.json()
        """
        Douban may return data like this:

            {
                'code': 128,
                'request': 'GET /v2/user/~me',
                'msg': 'user_is_locked:53358092'
            }

        """
        if 'id' not in extra_data:
            msg = extra_data.get('msg', _('Invalid profile data'))
            raise ProviderException(msg)
        return self.get_provider().sociallogin_from_response(
            request, extra_data)
Beispiel #28
0
class DefaultAccountAdapter(object):

    error_messages = {
        'username_blacklisted':
        _('Username can not be used. Please use other username.'),
        'username_taken':
        AbstractUser._meta.get_field('username').error_messages['unique'],
        'too_many_login_attempts':
        _('Too many failed login attempts. Try again later.'),
        'email_taken':
        _("A user is already registered with this e-mail address."),
    }

    def __init__(self, request=None):
        self.request = request

    def stash_verified_email(self, request, email):
        request.session['account_verified_email'] = email

    def unstash_verified_email(self, request):
        ret = request.session.get('account_verified_email')
        request.session['account_verified_email'] = None
        return ret

    def stash_user(self, request, user):
        request.session['account_user'] = user

    def unstash_user(self, request):
        return request.session.pop('account_user', None)

    def is_email_verified(self, request, email):
        """
        Checks whether or not the email address is already verified
        beyond allauth scope, for example, by having accepted an
        invitation before signing up.
        """
        ret = False
        verified_email = request.session.get('account_verified_email')
        if verified_email:
            ret = verified_email.lower() == email.lower()
        return ret

    def format_email_subject(self, subject):
        prefix = app_settings.EMAIL_SUBJECT_PREFIX
        if prefix is None:
            site = get_current_site(self.request)
            prefix = "[{name}] ".format(name=site.name)
        return prefix + force_str(subject)

    def get_from_email(self):
        """
        This is a hook that can be overridden to programatically
        set the 'from' email address for sending emails
        """
        return settings.DEFAULT_FROM_EMAIL

    def render_mail(self, template_prefix, email, context):
        """
        Renders an e-mail to `email`.  `template_prefix` identifies the
        e-mail that is to be sent, e.g. "account/email/email_confirmation"
        """
        subject = render_to_string('{0}_subject.txt'.format(template_prefix),
                                   context)
        # remove superfluous line breaks
        subject = " ".join(subject.splitlines()).strip()
        subject = self.format_email_subject(subject)

        from_email = self.get_from_email()

        bodies = {}
        for ext in ['html', 'txt']:
            try:
                template_name = '{0}_message.{1}'.format(template_prefix, ext)
                bodies[ext] = render_to_string(template_name, context).strip()
            except TemplateDoesNotExist:
                if ext == 'txt' and not bodies:
                    # We need at least one body
                    raise
        if 'txt' in bodies:
            msg = EmailMultiAlternatives(subject, bodies['txt'], from_email,
                                         [email])
            if 'html' in bodies:
                msg.attach_alternative(bodies['html'], 'text/html')
        else:
            msg = EmailMessage(subject, bodies['html'], from_email, [email])
            msg.content_subtype = 'html'  # Main content is now text/html
        return msg

    def send_mail(self, template_prefix, email, context):
        msg = self.render_mail(template_prefix, email, context)
        msg.send()

    def get_login_redirect_url(self, request):
        """
        Returns the default URL to redirect to after logging in.  Note
        that URLs passed explicitly (e.g. by passing along a `next`
        GET parameter) take precedence over the value returned here.
        """
        assert request.user.is_authenticated
        url = getattr(settings, "LOGIN_REDIRECT_URLNAME", None)
        if url:
            warnings.warn(
                "LOGIN_REDIRECT_URLNAME is deprecated, simply"
                " use LOGIN_REDIRECT_URL with a URL name", DeprecationWarning)
        else:
            url = settings.LOGIN_REDIRECT_URL
        return resolve_url(url)

    def get_logout_redirect_url(self, request):
        """
        Returns the URL to redirect to after the user logs out. Note that
        this method is also invoked if you attempt to log out while no users
        is logged in. Therefore, request.user is not guaranteed to be an
        authenticated user.
        """
        return resolve_url(app_settings.LOGOUT_REDIRECT_URL)

    def get_email_confirmation_redirect_url(self, request):
        """
        The URL to return to after successful e-mail confirmation.
        """
        if request.user.is_authenticated:
            if app_settings.EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL:
                return  \
                    app_settings.EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL
            else:
                return self.get_login_redirect_url(request)
        else:
            return app_settings.EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL

    def is_open_for_signup(self, request):
        """
        Checks whether or not the site is open for signups.

        Next to simply returning True/False you can also intervene the
        regular flow by raising an ImmediateHttpResponse
        """
        return True

    def new_user(self, request):
        """
        Instantiates a new User instance.
        """
        user = get_user_model()()
        return user

    def populate_username(self, request, user):
        """
        Fills in a valid username, if required and missing.  If the
        username is already present it is assumed to be valid
        (unique).
        """
        from .utils import user_username, user_email, user_field
        first_name = user_field(user, 'first_name')
        last_name = user_field(user, 'last_name')
        email = user_email(user)
        username = user_username(user)
        if app_settings.USER_MODEL_USERNAME_FIELD:
            user_username(
                user, username or self.generate_unique_username(
                    [first_name, last_name, email, username, 'user']))

    def generate_unique_username(self, txts, regex=None):
        return generate_unique_username(txts, regex)

    def save_user(self, request, user, form, commit=True):
        """
        Saves a new `User` instance using information provided in the
        signup form.
        """
        from .utils import user_username, user_email, user_field

        data = form.cleaned_data
        first_name = data.get('first_name')
        last_name = data.get('last_name')
        email = data.get('email')
        username = data.get('username')
        user_email(user, email)
        user_username(user, username)
        if first_name:
            user_field(user, 'first_name', first_name)
        if last_name:
            user_field(user, 'last_name', last_name)
        if 'password1' in data:
            user.set_password(data["password1"])
        else:
            user.set_unusable_password()
        self.populate_username(request, user)
        if commit:
            # Ability not to commit makes it easier to derive from
            # this adapter by adding
            user.save()
        return user

    def clean_username(self, username, shallow=False):
        """
        Validates the username. You can hook into this if you want to
        (dynamically) restrict what usernames can be chosen.
        """
        for validator in app_settings.USERNAME_VALIDATORS:
            validator(username)

        # TODO: Add regexp support to USERNAME_BLACKLIST
        username_blacklist_lower = [
            ub.lower() for ub in app_settings.USERNAME_BLACKLIST
        ]
        if username.lower() in username_blacklist_lower:
            raise forms.ValidationError(
                self.error_messages['username_blacklisted'])
        # Skipping database lookups when shallow is True, needed for unique
        # username generation.
        if not shallow:
            from .utils import filter_users_by_username
            if filter_users_by_username(username).exists():
                user_model = get_user_model()
                username_field = app_settings.USER_MODEL_USERNAME_FIELD
                error_message = user_model._meta.get_field(
                    username_field).error_messages.get('unique')
                if not error_message:
                    error_message = self.error_messages['username_taken']
                raise forms.ValidationError(error_message,
                                            params={
                                                'model_name':
                                                user_model.__name__,
                                                'field_label': username_field,
                                            })
        return username

    def clean_email(self, email):
        """
        Validates an email value. You can hook into this if you want to
        (dynamically) restrict what email addresses can be chosen.
        """
        return email

    def clean_password(self, password, user=None):
        """
        Validates a password. You can hook into this if you want to
        restric the allowed password choices.
        """
        min_length = app_settings.PASSWORD_MIN_LENGTH
        if min_length and len(password) < min_length:
            raise forms.ValidationError(
                _("Password must be a minimum of {0} "
                  "characters.").format(min_length))
        validate_password(password, user)
        return password

    def validate_unique_email(self, email, site=None):
        if email_address_exists(email, site=site):
            raise forms.ValidationError(self.error_messages['email_taken'])
        return email

    def add_message(self,
                    request,
                    level,
                    message_template,
                    message_context=None,
                    extra_tags=''):
        """
        Wrapper of `django.contrib.messages.add_message`, that reads
        the message text from a template.
        """
        if 'django.contrib.messages' in settings.INSTALLED_APPS:
            try:
                if message_context is None:
                    message_context = {}
                message = render_to_string(message_template,
                                           message_context).strip()
                if message:
                    messages.add_message(request,
                                         level,
                                         message,
                                         extra_tags=extra_tags)
            except TemplateDoesNotExist:
                pass

    def ajax_response(self,
                      request,
                      response,
                      redirect_to=None,
                      form=None,
                      data=None):
        resp = {}
        status = response.status_code

        if redirect_to:
            status = 200
            resp['location'] = redirect_to
        if form:
            if request.method == 'POST':
                if form.is_valid():
                    status = 200
                else:
                    status = 400
            else:
                status = 200
            resp['form'] = self.ajax_response_form(form)
            if hasattr(response, 'render'):
                response.render()
            resp['html'] = response.content.decode('utf8')
        if data is not None:
            resp['data'] = data
        return HttpResponse(json.dumps(resp),
                            status=status,
                            content_type='application/json')

    def ajax_response_form(self, form):
        form_spec = {
            'fields': {},
            'field_order': [],
            'errors': form.non_field_errors()
        }
        for field in form:
            field_spec = {
                'label': force_str(field.label),
                'value': field.value(),
                'help_text': force_str(field.help_text),
                'errors': [force_str(e) for e in field.errors],
                'widget': {
                    'attrs': {
                        k: force_str(v)
                        for k, v in field.field.widget.attrs.items()
                    }
                }
            }
            form_spec['fields'][field.html_name] = field_spec
            form_spec['field_order'].append(field.html_name)
        return form_spec

    def login(self, request, user):
        # HACK: This is not nice. The proper Django way is to use an
        # authentication backend
        if not hasattr(user, 'backend'):
            from .auth_backends import AuthenticationBackend
            backends = get_backends()
            backend = None
            for b in backends:
                if isinstance(b, AuthenticationBackend):
                    # prefer our own backend
                    backend = b
                    break
                elif not backend and hasattr(b, 'get_user'):
                    # Pick the first vald one
                    backend = b
            backend_path = '.'.join(
                [backend.__module__, backend.__class__.__name__])
            user.backend = backend_path
        django_login(request, user)

    def logout(self, request):
        django_logout(request)

    def confirm_email(self, request, email_address):
        """
        Marks the email address as confirmed on the db
        """
        email_address.verified = True
        email_address.set_as_primary(conditional=True)
        email_address.save()

    def set_password(self, user, password):
        user.set_password(password)
        user.save()

    def get_user_search_fields(self):
        user = get_user_model()()
        return filter(lambda a: a and hasattr(user, a), [
            app_settings.USER_MODEL_USERNAME_FIELD, 'first_name', 'last_name',
            'email'
        ])

    def is_safe_url(self, url):
        from django.utils.http import is_safe_url
        return is_safe_url(url, allowed_hosts=None)

    def get_email_confirmation_url(self, request, emailconfirmation):
        """Constructs the email confirmation (activation) url.

        Note that if you have architected your system such that email
        confirmations are sent outside of the request context `request`
        can be `None` here.
        """
        url = reverse("account_confirm_email", args=[emailconfirmation.key])
        ret = build_absolute_uri(request, url)
        return ret

    def send_confirmation_mail(self, request, emailconfirmation, signup):
        current_site = get_current_site(request)
        activate_url = self.get_email_confirmation_url(request,
                                                       emailconfirmation)
        ctx = {
            "user": emailconfirmation.email_address.user,
            "activate_url": activate_url,
            "current_site": current_site,
            "key": emailconfirmation.key,
        }
        if signup:
            email_template = 'account/email/email_confirmation_signup'
        else:
            email_template = 'account/email/email_confirmation'
        self.send_mail(email_template, emailconfirmation.email_address.email,
                       ctx)

    def respond_user_inactive(self, request, user):
        return HttpResponseRedirect(reverse('account_inactive'))

    def respond_email_verification_sent(self, request, user):
        return HttpResponseRedirect(reverse('account_email_verification_sent'))

    def _get_login_attempts_cache_key(self, request, **credentials):
        site = get_current_site(request)
        login = credentials.get('email', credentials.get('username', ''))
        login_key = hashlib.sha256(login.encode('utf8')).hexdigest()
        return 'allauth/login_attempts@{site_id}:{login}'.format(
            site_id=site.pk, login=login_key)

    def pre_authenticate(self, request, **credentials):
        if app_settings.LOGIN_ATTEMPTS_LIMIT:
            cache_key = self._get_login_attempts_cache_key(
                request, **credentials)
            login_data = cache.get(cache_key, None)
            if login_data:
                dt = timezone.now()
                current_attempt_time = time.mktime(dt.timetuple())
                if (len(login_data) >= app_settings.LOGIN_ATTEMPTS_LIMIT
                        and current_attempt_time <
                    (login_data[-1] + app_settings.LOGIN_ATTEMPTS_TIMEOUT)):
                    raise forms.ValidationError(
                        self.error_messages['too_many_login_attempts'])

    def authenticate(self, request, **credentials):
        """Only authenticates, does not actually login. See `login`"""
        from allauth.account.auth_backends import AuthenticationBackend

        self.pre_authenticate(request, **credentials)
        AuthenticationBackend.unstash_authenticated_user()
        user = authenticate(request, **credentials)
        alt_user = AuthenticationBackend.unstash_authenticated_user()
        user = user or alt_user
        if user and app_settings.LOGIN_ATTEMPTS_LIMIT:
            cache_key = self._get_login_attempts_cache_key(
                request, **credentials)
            cache.delete(cache_key)
        else:
            self.authentication_failed(request, **credentials)
        return user

    def authentication_failed(self, request, **credentials):
        if app_settings.LOGIN_ATTEMPTS_LIMIT:
            cache_key = self._get_login_attempts_cache_key(
                request, **credentials)
            data = cache.get(cache_key, [])
            dt = timezone.now()
            data.append(time.mktime(dt.timetuple()))
            cache.set(cache_key, data, app_settings.LOGIN_ATTEMPTS_TIMEOUT)

    def is_ajax(self, request):
        return request.is_ajax()
Beispiel #29
0
 class Meta:
     verbose_name = _("email confirmation")
     verbose_name_plural = _("email confirmations")
Beispiel #30
0
 class Meta:
     verbose_name = _("email address")
     verbose_name_plural = _("email addresses")
     if not app_settings.UNIQUE_EMAIL:
         unique_together = [("user", "email")]
Beispiel #31
0
 class Meta:
     verbose_name = _('social application')
     verbose_name_plural = _('social applications')
Beispiel #32
0
 class Meta:
     unique_together = ('app', 'account')
     verbose_name = _('social application token')
     verbose_name_plural = _('social application tokens')