~grupoesoc/cubicerp-addons/7.0

« back to all changes in this revision

Viewing changes to report_geraldo/lib/geraldo/site/newsite/django_1_0/django/contrib/auth/forms.py

  • Committer: Cubic ERP
  • Date: 2014-01-07 15:38:09 UTC
  • Revision ID: info@cubicerp.com-20140107153809-4jmif3zoi8rcveve
[ADD] cubicReport

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
from django.contrib.auth.models import User
 
2
from django.contrib.auth import authenticate
 
3
from django.contrib.sites.models import Site
 
4
from django.template import Context, loader
 
5
from django import forms
 
6
from django.utils.translation import ugettext_lazy as _
 
7
 
 
8
class UserCreationForm(forms.ModelForm):
 
9
    """
 
10
    A form that creates a user, with no privileges, from the given username and password.
 
11
    """
 
12
    username = forms.RegexField(label=_("Username"), max_length=30, regex=r'^\w+$',
 
13
        help_text = _("Required. 30 characters or fewer. Alphanumeric characters only (letters, digits and underscores)."),
 
14
        error_message = _("This value must contain only letters, numbers and underscores."))
 
15
    password1 = forms.CharField(label=_("Password"), max_length=60, widget=forms.PasswordInput)
 
16
    password2 = forms.CharField(label=_("Password confirmation"), max_length=60, widget=forms.PasswordInput)
 
17
    
 
18
    class Meta:
 
19
        model = User
 
20
        fields = ("username",)
 
21
    
 
22
    def clean_username(self):
 
23
        username = self.cleaned_data["username"]
 
24
        try:
 
25
            User.objects.get(username=username)
 
26
        except User.DoesNotExist:
 
27
            return username
 
28
        raise forms.ValidationError(_("A user with that username already exists."))
 
29
    
 
30
    def clean_password2(self):
 
31
        password1 = self.cleaned_data["password1"]
 
32
        password2 = self.cleaned_data["password2"]
 
33
        if password1 != password2:
 
34
            raise forms.ValidationError(_("The two password fields didn't match."))
 
35
        return password2
 
36
    
 
37
    def save(self, commit=True):
 
38
        user = super(UserCreationForm, self).save(commit=False)
 
39
        user.set_password(self.cleaned_data["password1"])
 
40
        if commit:
 
41
            user.save()
 
42
        return user
 
43
 
 
44
class AuthenticationForm(forms.Form):
 
45
    """
 
46
    Base class for authenticating users. Extend this to get a form that accepts
 
47
    username/password logins.
 
48
    """
 
49
    username = forms.CharField(label=_("Username"), max_length=30)
 
50
    password = forms.CharField(label=_("Password"), max_length=30, widget=forms.PasswordInput)
 
51
    
 
52
    def __init__(self, request=None, *args, **kwargs):
 
53
        """
 
54
        If request is passed in, the form will validate that cookies are
 
55
        enabled. Note that the request (a HttpRequest object) must have set a
 
56
        cookie with the key TEST_COOKIE_NAME and value TEST_COOKIE_VALUE before
 
57
        running this validation.
 
58
        """
 
59
        self.request = request
 
60
        self.user_cache = None
 
61
        super(AuthenticationForm, self).__init__(*args, **kwargs)
 
62
    
 
63
    def clean(self):
 
64
        username = self.cleaned_data.get('username')
 
65
        password = self.cleaned_data.get('password')
 
66
        
 
67
        if username and password:
 
68
            self.user_cache = authenticate(username=username, password=password)
 
69
            if self.user_cache is None:
 
70
                raise forms.ValidationError(_("Please enter a correct username and password. Note that both fields are case-sensitive."))
 
71
            elif not self.user_cache.is_active:
 
72
                raise forms.ValidationError(_("This account is inactive."))
 
73
        
 
74
        # TODO: determine whether this should move to its own method.
 
75
        if self.request:
 
76
            if not self.request.session.test_cookie_worked():
 
77
                raise forms.ValidationError(_("Your Web browser doesn't appear to have cookies enabled. Cookies are required for logging in."))
 
78
        
 
79
        return self.cleaned_data
 
80
    
 
81
    def get_user_id(self):
 
82
        if self.user_cache:
 
83
            return self.user_cache.id
 
84
        return None
 
85
    
 
86
    def get_user(self):
 
87
        return self.user_cache
 
88
 
 
89
class PasswordResetForm(forms.Form):
 
90
    email = forms.EmailField(label=_("E-mail"), max_length=40)
 
91
    
 
92
    def clean_email(self):
 
93
        """
 
94
        Validates that a user exists with the given e-mail address.
 
95
        """
 
96
        email = self.cleaned_data["email"]
 
97
        self.users_cache = User.objects.filter(email__iexact=email)
 
98
        if len(self.users_cache) == 0:
 
99
            raise forms.ValidationError(_("That e-mail address doesn't have an associated user account. Are you sure you've registered?"))
 
100
    
 
101
    def save(self, domain_override=None, email_template_name='registration/password_reset_email.html'):
 
102
        """
 
103
        Calculates a new password randomly and sends it to the user.
 
104
        """
 
105
        from django.core.mail import send_mail
 
106
        for user in self.users_cache:
 
107
            new_pass = User.objects.make_random_password()
 
108
            user.set_password(new_pass)
 
109
            user.save()
 
110
            if not domain_override:
 
111
                current_site = Site.objects.get_current()
 
112
                site_name = current_site.name
 
113
                domain = current_site.domain
 
114
            else:
 
115
                site_name = domain = domain_override
 
116
            t = loader.get_template(email_template_name)
 
117
            c = {
 
118
                'new_password': new_pass,
 
119
                'email': user.email,
 
120
                'domain': domain,
 
121
                'site_name': site_name,
 
122
                'user': user,
 
123
            }
 
124
            send_mail(_("Password reset on %s") % site_name,
 
125
                t.render(Context(c)), None, [user.email])
 
126
 
 
127
class PasswordChangeForm(forms.Form):
 
128
    """
 
129
    A form that lets a user change his/her password.
 
130
    """
 
131
    old_password = forms.CharField(label=_("Old password"), max_length=30, widget=forms.PasswordInput)
 
132
    new_password1 = forms.CharField(label=_("New password"), max_length=30, widget=forms.PasswordInput)
 
133
    new_password2 = forms.CharField(label=_("New password confirmation"), max_length=30, widget=forms.PasswordInput)
 
134
    
 
135
    def __init__(self, user, *args, **kwargs):
 
136
        self.user = user
 
137
        super(PasswordChangeForm, self).__init__(*args, **kwargs)
 
138
    
 
139
    def clean_old_password(self):
 
140
        """
 
141
        Validates that the old_password field is correct.
 
142
        """
 
143
        old_password = self.cleaned_data["old_password"]
 
144
        if not self.user.check_password(old_password):
 
145
            raise forms.ValidationError(_("Your old password was entered incorrectly. Please enter it again."))
 
146
        return old_password
 
147
    
 
148
    def clean_new_password2(self):
 
149
        password1 = self.cleaned_data.get('new_password1')
 
150
        password2 = self.cleaned_data.get('new_password2')
 
151
        if password1 and password2:
 
152
            if password1 != password2:
 
153
                raise forms.ValidationError(_("The two password fields didn't match."))
 
154
        return password2
 
155
    
 
156
    def save(self, commit=True):
 
157
        self.user.set_password(self.cleaned_data['new_password1'])
 
158
        if commit:
 
159
            self.user.save()
 
160
        return self.user
 
161
 
 
162
class AdminPasswordChangeForm(forms.Form):
 
163
    """
 
164
    A form used to change the password of a user in the admin interface.
 
165
    """
 
166
    password1 = forms.CharField(label=_("Password"), max_length=60, widget=forms.PasswordInput)
 
167
    password2 = forms.CharField(label=_("Password (again)"), max_length=60, widget=forms.PasswordInput)
 
168
    
 
169
    def __init__(self, user, *args, **kwargs):
 
170
        self.user = user
 
171
        super(AdminPasswordChangeForm, self).__init__(*args, **kwargs)
 
172
    
 
173
    def clean_password2(self):
 
174
        password1 = self.cleaned_data.get('password1')
 
175
        password2 = self.cleaned_data.get('password2')
 
176
        if password1 and password2:
 
177
            if password1 != password2:
 
178
                raise forms.ValidationError(_("The two password fields didn't match."))
 
179
        return password2
 
180
    
 
181
    def save(self, commit=True):
 
182
        """
 
183
        Saves the new password.
 
184
        """
 
185
        self.user.set_password(self.cleaned_data["password1"])
 
186
        if commit:
 
187
            self.user.save()
 
188
        return self.user