<commit_before>from django.utils.translation import ugettext_lazy as _
from django.utils.safestring import mark_safe
from django.contrib import auth
from django.contrib.auth import get_user_model
from django.conf import settings
from django.contrib.auth.forms import SetPasswordForm as DjangoSetPasswordForm
from django import forms

from froide.helper.form_utils import JSONMixin
from froide.helper.content_urls import get_content_url
from froide.helper.widgets import BootstrapCheckboxInput

from .widgets import ConfirmationWidget
from .services import AccountService
from .models import has_newsletter


USER_CAN_HIDE_WEB = settings.FROIDE_CONFIG.get("user_can_hide_web", True)
HAVE_ORGANIZATION = settings.FROIDE_CONFIG.get("user_has_organization", True)
ALLOW_PSEUDONYM = settings.FROIDE_CONFIG.get("allow_pseudonym", False)


class NewUserBaseForm(forms.Form):
    first_name = forms.CharField(max_length=30,
            label=_('First name'),
            widget=forms.TextInput(attrs={'placeholder': _('First Name'),
                'class': 'form-control'}))
    last_name = forms.CharField(max_length=30,
            label=_('Last name'),
            widget=forms.TextInput(attrs={'placeholder': _('Last Name'),
                'class': 'form-control'}))
    address = forms.CharField(max_length=300,
        required=False,
        label=_('Mailing Address'),
        help_text=_(
            'Optional. Your address will not be displayed '
            'publicly and is only needed in case a public body '
            'needs to send you paper.'),
        widget=forms.Textarea(attrs={
            'rows': '3',
            'class': 'form-control',
            'placeholder': _('Street, Post Code, City'),
        })
    )
    user_email = forms.EmailField(label=_('Email address'),
            max_length=75,
            help_text=_('Not public. The given address will '
                        'need to be confirmed.'),
            widget=forms.EmailInput(attrs={
                    'placeholder': _('<EMAIL>'),
                    'class': 'form-control'
            }))

    if HAVE_ORGANIZATION:
        organization = forms.CharField(required=False,
                label=_("Organization"),
                help_text=_('Optional. Affiliation will be shown next to your name'),
                widget=forms.TextInput(attrs={
                    'placeholder': _('Organization'),
                    'class': 'form-control'})
        )

    if USER_CAN_HIDE_WEB:
        private = forms.BooleanField(
            required=False,
            widget=BootstrapCheckboxInput,
            label=_("Hide my name from public view"),
            help_text=mark_safe(_("If you check this, your name will still appear in requests to public bodies, but we will do our best to not display it publicly. However, we cannot guarantee your anonymity")))

    def __init__(self, *args, **kwargs):
        super(NewUserBaseForm, self).__init__(*args, **kwargs)
        if ALLOW_PSEUDONYM:
            self.fields["last_name"].help_text = mark_safe(
                    _('<a target="_blank" href="{url}">You may use a pseudonym if you don\'t need to receive postal messages</a>.')
                    .format(url=get_content_url("privacy") + '#pseudonym'))

    def clean_first_name(self):
        return self.cleaned_data['first_name'].strip()

    def clean_last_name(self):
        return self.cleaned_data['last_name'].strip()


class AddressForm(JSONMixin, forms.Form):
    address = forms.CharField(max_length=300,
        required=False,
        label=_('Mailing Address'),
        help_text=_(
            'Your address will not be displayed '
            'publicly and is only needed because a public body '
            'will likely want to send you paper.'),
        widget=forms.Textarea(attrs={
            'rows': '3',
            'class': 'form-control',
            'placeholder': _('Street, Post Code, City'),
        })
    )

    def save(self, user):
        address = self.cleaned_data['address']
        if address:
            user.address = address
            user.save()


class TermsForm(forms.Form):
    terms = forms.BooleanField(
        widget=BootstrapCheckboxInput,
        error_messages={
            'required': _('You need to accept our Terms '
                'and Conditions and Priavcy Statement.')},
    )

    def __init__(self, *args, **kwargs):
        super(TermsForm, self).__init__(*args, **kwargs)

        self.fields['terms'].label = mark_safe(
            _('You agree to our <a href="{url_terms}" target="_blank">'
                'Terms and Conditions</a> and <a href="{url_privacy}" target="_blank">'
                'Privacy Statement</a>').format(
                    url_terms=get_content_url("terms"),
                    url_privacy=get_content_url("privacy")
                )
        )

        if has_newsletter():
            self.fields['newsletter'] = forms.BooleanField(
                required=False,
                widget=BootstrapCheckboxInput,
                label=_("Check if you want to receive our newsletter.")
            )

    def save(self, user):
        user.terms = True
        if has_newsletter():
            user.newsletter = self.cleaned_data['newsletter']
        user.save()


class NewUserForm(JSONMixin, TermsForm, NewUserBaseForm):
    pass


class NewUserWithPasswordForm(NewUserForm):
    password = forms.CharField(widget=forms.PasswordInput,
            label=_('Password'))
    password2 = forms.CharField(widget=forms.PasswordInput,
            label=_('Password (repeat)'))

    def clean(self):
        cleaned = super(NewUserWithPasswordForm, self).clean()
        if cleaned['password'] != cleaned['password2']:
            raise forms.ValidationError(_("Passwords do not match!"))
        return cleaned


class UserLoginForm(forms.Form):
    email = forms.EmailField(widget=forms.EmailInput(
        attrs={
            'placeholder': _('<EMAIL>'),
            'class': 'form-control'
        }),
        label=_('Email address'))
    password = forms.CharField(widget=forms.PasswordInput(
        attrs={
            'class': 'form-control'
        }),
        label=_('Password'))


class PasswordResetForm(auth.forms.PasswordResetForm):
    email = forms.EmailField(widget=forms.EmailInput(
        attrs={
            'placeholder': _('<EMAIL>'),
            'class': 'form-control'
        }),
        label=_('Email address'))


class UserChangeForm(forms.Form):
    email = forms.EmailField(required=False, widget=forms.EmailInput(
        attrs={
            'placeholder': _('<EMAIL>'),
            'class': 'form-control'
        }),
        label=_('Your email address'))

    address = forms.CharField(
        max_length=300,
        label=_('Your mailing address'),
        help_text=_('Your address will never be displayed publicly.'),
        widget=forms.Textarea(attrs={
            'placeholder': _('Street, Post Code, City'),
            'class': 'form-control',
            'rows': '3'
        }),
        required=False
    )
    if HAVE_ORGANIZATION:
        organization = forms.CharField(
            required=False,
            label=_("Organization"),
            help_text=_('Optional. Affiliation will be shown next to your name'),<commit_msg>Add autocomplete attribute to login/signup forms<commit_after>from django.utils.translation import ugettext_lazy as _
from django.utils.safestring import mark_safe
from django.contrib import auth
from django.contrib.auth import get_user_model
from django.conf import settings
from django.contrib.auth.forms import SetPasswordForm as DjangoSetPasswordForm
from django import forms

from froide.helper.form_utils import JSONMixin
from froide.helper.content_urls import get_content_url
from froide.helper.widgets import BootstrapCheckboxInput

from .widgets import ConfirmationWidget
from .services import AccountService
from .models import has_newsletter


USER_CAN_HIDE_WEB = settings.FROIDE_CONFIG.get("user_can_hide_web", True)
HAVE_ORGANIZATION = settings.FROIDE_CONFIG.get("user_has_organization", True)
ALLOW_PSEUDONYM = settings.FROIDE_CONFIG.get("allow_pseudonym", False)


class NewUserBaseForm(forms.Form):
    first_name = forms.CharField(max_length=30,
            label=_('First name'),
            widget=forms.TextInput(attrs={'placeholder': _('First Name'),
                'class': 'form-control'}))
    last_name = forms.CharField(max_length=30,
            label=_('Last name'),
            widget=forms.TextInput(attrs={'placeholder': _('<NAME>'),
                'class': 'form-control'}))
    address = forms.CharField(max_length=300,
        required=False,
        label=_('Mailing Address'),
        help_text=_(
            'Optional. Your address will not be displayed '
            'publicly and is only needed in case a public body '
            'needs to send you paper.'),
        widget=forms.Textarea(attrs={
            'rows': '3',
            'class': 'form-control',
            'placeholder': _('Street, Post Code, City'),
        })
    )
    user_email = forms.EmailField(label=_('Email address'),
            max_length=75,
            help_text=_('Not public. The given address will '
                        'need to be confirmed.'),
            widget=forms.EmailInput(attrs={
                    'placeholder': _('<EMAIL>'),
                    'class': 'form-control',
                    'autocomplete': 'username'
            }))

    if HAVE_ORGANIZATION:
        organization = forms.CharField(required=False,
                label=_("Organization"),
                help_text=_('Optional. Affiliation will be shown next to your name'),
                widget=forms.TextInput(attrs={
                    'placeholder': _('Organization'),
                    'class': 'form-control'})
        )

    if USER_CAN_HIDE_WEB:
        private = forms.BooleanField(
            required=False,
            widget=BootstrapCheckboxInput,
            label=_("Hide my name from public view"),
            help_text=mark_safe(_("If you check this, your name will still appear in requests to public bodies, but we will do our best to not display it publicly. However, we cannot guarantee your anonymity")))

    def __init__(self, *args, **kwargs):
        super(NewUserBaseForm, self).__init__(*args, **kwargs)
        if ALLOW_PSEUDONYM:
            self.fields["last_name"].help_text = mark_safe(
                    _('<a target="_blank" href="{url}">You may use a pseudonym if you don\'t need to receive postal messages</a>.')
                    .format(url=get_content_url("privacy") + '#pseudonym'))

    def clean_first_name(self):
        return self.cleaned_data['first_name'].strip()

    def clean_last_name(self):
        return self.cleaned_data['last_name'].strip()


class AddressForm(JSONMixin, forms.Form):
    address = forms.CharField(max_length=300,
        required=False,
        label=_('Mailing Address'),
        help_text=_(
            'Your address will not be displayed '
            'publicly and is only needed because a public body '
            'will likely want to send you paper.'),
        widget=forms.Textarea(attrs={
            'rows': '3',
            'class': 'form-control',
            'placeholder': _('Street, Post Code, City'),
        })
    )

    def save(self, user):
        address = self.cleaned_data['address']
        if address:
            user.address = address
            user.save()


class TermsForm(forms.Form):
    terms = forms.BooleanField(
        widget=BootstrapCheckboxInput,
        error_messages={
            'required': _('You need to accept our Terms '
                'and Conditions and Priavcy Statement.')},
    )

    def __init__(self, *args, **kwargs):
        super(TermsForm, self).__init__(*args, **kwargs)

        self.fields['terms'].label = mark_safe(
            _('You agree to our <a href="{url_terms}" target="_blank">'
                'Terms and Conditions</a> and <a href="{url_privacy}" target="_blank">'
                'Privacy Statement</a>').format(
                    url_terms=get_content_url("terms"),
                    url_privacy=get_content_url("privacy")
                )
        )

        if has_newsletter():
            self.fields['newsletter'] = forms.BooleanField(
                required=False,
                widget=BootstrapCheckboxInput,
                label=_("Check if you want to receive our newsletter.")
            )

    def save(self, user):
        user.terms = True
        if has_newsletter():
            user.newsletter = self.cleaned_data['newsletter']
        user.save()


class NewUserForm(JSONMixin, TermsForm, NewUserBaseForm):
    pass


class NewUserWithPasswordForm(NewUserForm):
    password = forms.CharField(
        widget=forms.PasswordInput(
            attrs={
                'class': 'form-control',
                'autocomplete': 'new-password'
            }
        ),
        label=_('Password')
    )
    password2 = forms.CharField(
        widget=forms.PasswordInput(
            attrs={
                'class': 'form-control',
                'autocomplete': 'new-password'
            }
        ),
        label=_('Password (repeat)')
    )

    def clean(self):
        cleaned = super(NewUserWithPasswordForm, self).clean()
        if cleaned['password'] != cleaned['password2']:
            raise forms.ValidationError(_("Passwords do not match!"))
        return cleaned


class UserLoginForm(forms.Form):
    email = forms.EmailField(widget=forms.EmailInput(
        attrs={
            'placeholder': _('<EMAIL>'),
            'class': 'form-control',
            'autocomplete': 'username'
        }),
        label=_('Email address'))
    password = forms.CharField(widget=forms.PasswordInput(
        attrs={
            'class': 'form-control',
            'autocomplete': "current-password"
        }),
        label=_('Password'))


class PasswordResetForm(auth.forms.PasswordResetForm):
    email = forms.EmailField(widget=forms.EmailInput(
        attrs={
            'placeholder': _('<EMAIL>'),
            'class': 'form-control',
            'autocomplete': 'username'
        }),
        label=_('Email address'))


class UserChangeForm(forms.Form):
    email = forms.EmailField(required=False, widget=forms.EmailInput(
        attrs={
            'placeholder': _('<EMAIL>'),
            'class': 'form-control',
            'autocomplete': 'username'
        }),
        label=_('Your email address'))

    address = forms.CharField(
        max_length=300,
        label=_('Your mailing address'),
        help_text=_('Your address will never be displayed publicly.'),
        widget=forms.Textarea(attrs={
            'placeholder': _('Street, Post Code, City'),
            'class': 'form-control',
            'rows': '3'
        }),
        required=False
    )
    if HAVE_ORGANIZATION:
        organization = forms.CharField(
            required=False,
            label=_("Organization"),
            help_text=_('Optional. Affiliation will be shown next to your name'),
{'fraction_non_alphanumeric': 0.11763925729442971, 'fraction_numerical': 0.002652519893899204, 'mean_word_length': 2.3476137624861266, 'pattern_counts': {'":': 0, '<': 24, '<?xml version=': 0, '>': 24, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2323489', 'n_tokens_mistral': 4196, 'n_tokens_neox': 4054, 'n_words': 963}