root / astakos / im / forms.py @ a196eb7e
History | View | Annotate | Download (9 kB)
1 |
# Copyright 2011-2012 GRNET S.A. All rights reserved.
|
---|---|
2 |
#
|
3 |
# Redistribution and use in source and binary forms, with or
|
4 |
# without modification, are permitted provided that the following
|
5 |
# conditions are met:
|
6 |
#
|
7 |
# 1. Redistributions of source code must retain the above
|
8 |
# copyright notice, this list of conditions and the following
|
9 |
# disclaimer.
|
10 |
#
|
11 |
# 2. Redistributions in binary form must reproduce the above
|
12 |
# copyright notice, this list of conditions and the following
|
13 |
# disclaimer in the documentation and/or other materials
|
14 |
# provided with the distribution.
|
15 |
#
|
16 |
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
|
17 |
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
18 |
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
19 |
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
|
20 |
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
21 |
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
22 |
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
|
23 |
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
|
24 |
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
25 |
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
26 |
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
27 |
# POSSIBILITY OF SUCH DAMAGE.
|
28 |
#
|
29 |
# The views and conclusions contained in the software and
|
30 |
# documentation are those of the authors and should not be
|
31 |
# interpreted as representing official policies, either expressed
|
32 |
# or implied, of GRNET S.A.
|
33 |
|
34 |
from django import forms |
35 |
from django.utils.translation import ugettext as _ |
36 |
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm, PasswordResetForm |
37 |
from django.conf import settings |
38 |
from django.core.validators import email_re |
39 |
from django.conf import settings |
40 |
from django.core.mail import send_mail |
41 |
from django.contrib.auth.tokens import default_token_generator |
42 |
from django.template import Context, loader |
43 |
from django.utils.http import int_to_base36 |
44 |
|
45 |
from hashlib import new as newhasher |
46 |
|
47 |
from astakos.im.models import AstakosUser |
48 |
from astakos.im.util import get_current_site |
49 |
|
50 |
import logging |
51 |
|
52 |
class LocalUserCreationForm(UserCreationForm): |
53 |
"""
|
54 |
Extends the built in UserCreationForm in several ways:
|
55 |
|
56 |
* Adds email, first_name and last_name field.
|
57 |
* The username field isn't visible and it is assigned a generated id.
|
58 |
* User created is not active.
|
59 |
"""
|
60 |
|
61 |
class Meta: |
62 |
model = AstakosUser |
63 |
fields = ("email", "first_name", "last_name") |
64 |
|
65 |
def __init__(self, *args, **kwargs): |
66 |
"""
|
67 |
Changes the order of fields, and removes the username field.
|
68 |
"""
|
69 |
super(LocalUserCreationForm, self).__init__(*args, **kwargs) |
70 |
self.fields.keyOrder = ['email', 'first_name', 'last_name', |
71 |
'password1', 'password2'] |
72 |
|
73 |
def clean_email(self): |
74 |
email = self.cleaned_data['email'] |
75 |
if not email: |
76 |
raise forms.ValidationError(_("This field is required")) |
77 |
try:
|
78 |
AstakosUser.objects.get(email = email) |
79 |
raise forms.ValidationError(_("Email is reserved")) |
80 |
except AstakosUser.DoesNotExist:
|
81 |
return email
|
82 |
|
83 |
def save(self, commit=True): |
84 |
"""
|
85 |
Saves the email, first_name and last_name properties, after the normal
|
86 |
save behavior is complete.
|
87 |
"""
|
88 |
user = super(LocalUserCreationForm, self).save(commit=False) |
89 |
user.renew_token() |
90 |
if commit:
|
91 |
user.save() |
92 |
logging.info('Created user %s', user)
|
93 |
return user
|
94 |
|
95 |
class InvitedLocalUserCreationForm(LocalUserCreationForm): |
96 |
"""
|
97 |
Extends the LocalUserCreationForm: adds an inviter readonly field.
|
98 |
"""
|
99 |
|
100 |
inviter = forms.CharField(widget=forms.TextInput(), label=_('Inviter Real Name'))
|
101 |
|
102 |
class Meta: |
103 |
model = AstakosUser |
104 |
fields = ("email", "first_name", "last_name") |
105 |
|
106 |
def __init__(self, *args, **kwargs): |
107 |
"""
|
108 |
Changes the order of fields, and removes the username field.
|
109 |
"""
|
110 |
super(InvitedLocalUserCreationForm, self).__init__(*args, **kwargs) |
111 |
self.fields.keyOrder = ['email', 'inviter', 'first_name', |
112 |
'last_name', 'password1', 'password2'] |
113 |
#set readonly form fields
|
114 |
self.fields['inviter'].widget.attrs['readonly'] = True |
115 |
self.fields['email'].widget.attrs['readonly'] = True |
116 |
self.fields['username'].widget.attrs['readonly'] = True |
117 |
|
118 |
def save(self, commit=True): |
119 |
user = super(InvitedLocalUserCreationForm, self).save(commit=False) |
120 |
level = user.invitation.inviter.level + 1
|
121 |
user.level = level |
122 |
user.invitations = settings.INVITATIONS_PER_LEVEL[level] |
123 |
if commit:
|
124 |
user.save() |
125 |
return user
|
126 |
|
127 |
class LoginForm(AuthenticationForm): |
128 |
username = forms.EmailField(label=_("Email"))
|
129 |
|
130 |
class ProfileForm(forms.ModelForm): |
131 |
"""
|
132 |
Subclass of ``ModelForm`` for permiting user to edit his/her profile.
|
133 |
Most of the fields are readonly since the user is not allowed to change them.
|
134 |
|
135 |
The class defines a save method which sets ``is_verified`` to True so as the user
|
136 |
during the next login will not to be redirected to profile page.
|
137 |
"""
|
138 |
class Meta: |
139 |
model = AstakosUser |
140 |
fields = ('email', 'first_name', 'last_name', 'auth_token', 'auth_token_expires') |
141 |
|
142 |
def __init__(self, *args, **kwargs): |
143 |
super(ProfileForm, self).__init__(*args, **kwargs) |
144 |
instance = getattr(self, 'instance', None) |
145 |
ro_fields = ('auth_token', 'auth_token_expires', 'email') |
146 |
if instance and instance.id: |
147 |
for field in ro_fields: |
148 |
self.fields[field].widget.attrs['readonly'] = True |
149 |
|
150 |
def save(self, commit=True): |
151 |
user = super(ProfileForm, self).save(commit=False) |
152 |
user.is_verified = True
|
153 |
if commit:
|
154 |
user.save() |
155 |
return user
|
156 |
|
157 |
class ThirdPartyUserCreationForm(ProfileForm): |
158 |
class Meta: |
159 |
model = AstakosUser |
160 |
fields = ('email', 'last_name', 'first_name', 'affiliation', 'provider', 'third_party_identifier') |
161 |
|
162 |
def __init__(self, *args, **kwargs): |
163 |
super(ThirdPartyUserCreationForm, self).__init__(*args, **kwargs) |
164 |
self.fields.keyOrder = ['email'] |
165 |
|
166 |
def clean_email(self): |
167 |
email = self.cleaned_data['email'] |
168 |
if not email: |
169 |
raise forms.ValidationError(_("This field is required")) |
170 |
try:
|
171 |
user = AstakosUser.objects.get(email = email) |
172 |
raise forms.ValidationError(_("Email is reserved")) |
173 |
except AstakosUser.DoesNotExist:
|
174 |
return email
|
175 |
|
176 |
def save(self, commit=True): |
177 |
user = super(ThirdPartyUserCreationForm, self).save(commit=False) |
178 |
user.verified = False
|
179 |
user.renew_token() |
180 |
if commit:
|
181 |
user.save() |
182 |
logging.info('Created user %s', user)
|
183 |
return user
|
184 |
|
185 |
class InvitedThirdPartyUserCreationForm(ThirdPartyUserCreationForm): |
186 |
def __init__(self, *args, **kwargs): |
187 |
super(InvitedThirdPartyUserCreationForm, self).__init__(*args, **kwargs) |
188 |
#set readonly form fields
|
189 |
self.fields['email'].widget.attrs['readonly'] = True |
190 |
|
191 |
class FeedbackForm(forms.Form): |
192 |
"""
|
193 |
Form for writing feedback.
|
194 |
"""
|
195 |
feedback_msg = forms.CharField(widget=forms.Textarea(), |
196 |
label=u'Message', required=False) |
197 |
feedback_data = forms.CharField(widget=forms.Textarea(), |
198 |
label=u'Data', required=False) |
199 |
|
200 |
class SendInvitationForm(forms.Form): |
201 |
"""
|
202 |
Form for sending an invitations
|
203 |
"""
|
204 |
|
205 |
email = forms.EmailField(required = True, label = 'Email address') |
206 |
first_name = forms.EmailField(label = 'First name')
|
207 |
last_name = forms.EmailField(label = 'Last name')
|
208 |
|
209 |
class ExtendedPasswordResetForm(PasswordResetForm): |
210 |
"""
|
211 |
Extends PasswordResetForm by overriding save method:
|
212 |
passes a custom from_email in send_mail.
|
213 |
|
214 |
Since Django 1.3 this is useless since ``django.contrib.auth.views.reset_password``
|
215 |
accepts a from_email argument.
|
216 |
"""
|
217 |
def save(self, domain_override=None, email_template_name='registration/password_reset_email.html', |
218 |
use_https=False, token_generator=default_token_generator, request=None): |
219 |
"""
|
220 |
Generates a one-use only link for resetting password and sends to the user.
|
221 |
"""
|
222 |
for user in self.users_cache: |
223 |
site_name, sitedomain = get_current_site(request, use_https=use_https) |
224 |
t = loader.get_template(email_template_name) |
225 |
c = { |
226 |
'email': user.email,
|
227 |
'domain': sitedomain.split('://')[-1], |
228 |
'site_name': site_name,
|
229 |
'uid': int_to_base36(user.id),
|
230 |
'user': user,
|
231 |
'token': token_generator.make_token(user),
|
232 |
'protocol': use_https and 'https' or 'http', |
233 |
} |
234 |
from_email = settings.DEFAULT_FROM_EMAIL % site_name |
235 |
send_mail(_("Password reset on %s") % site_name,
|
236 |
t.render(Context(c)), from_email, [user.email]) |