Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / forms.py @ 27993be5

History | View | Annotate | Download (8.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.core.mail import send_mail
38
from django.contrib.auth.tokens import default_token_generator
39
from django.template import Context, loader
40
from django.utils.http import int_to_base36
41
from django.core.urlresolvers import reverse
42

    
43
from astakos.im.models import AstakosUser
44
from astakos.im.settings import INVITATIONS_PER_LEVEL, DEFAULT_FROM_EMAIL, BASEURL, SITENAME
45

    
46
import logging
47

    
48
logger = logging.getLogger(__name__)
49

    
50
class LocalUserCreationForm(UserCreationForm):
51
    """
52
    Extends the built in UserCreationForm in several ways:
53
    
54
    * Adds email, first_name and last_name field.
55
    * The username field isn't visible and it is assigned a generated id.
56
    * User created is not active. 
57
    """
58
    
59
    class Meta:
60
        model = AstakosUser
61
        fields = ("email", "first_name", "last_name")
62
    
63
    def __init__(self, *args, **kwargs):
64
        """
65
        Changes the order of fields, and removes the username field.
66
        """
67
        super(LocalUserCreationForm, self).__init__(*args, **kwargs)
68
        self.fields.keyOrder = ['email', 'first_name', 'last_name',
69
                                'password1', 'password2']
70
    
71
    def clean_email(self):
72
        email = self.cleaned_data['email']
73
        if not email:
74
            raise forms.ValidationError(_("This field is required"))
75
        try:
76
            AstakosUser.objects.get(email = email)
77
            raise forms.ValidationError(_("Email is reserved"))
78
        except AstakosUser.DoesNotExist:
79
            return email
80
    
81
    def save(self, commit=True):
82
        """
83
        Saves the email, first_name and last_name properties, after the normal
84
        save behavior is complete.
85
        """
86
        user = super(LocalUserCreationForm, self).save(commit=False)
87
        user.renew_token()
88
        if commit:
89
            user.save()
90
        logger.info('Created user %s', user)
91
        return user
92

    
93
class InvitedLocalUserCreationForm(LocalUserCreationForm):
94
    """
95
    Extends the LocalUserCreationForm: adds an inviter readonly field.
96
    """
97
    
98
    inviter = forms.CharField(widget=forms.TextInput(), label=_('Inviter Real Name'))
99
    
100
    class Meta:
101
        model = AstakosUser
102
        fields = ("email", "first_name", "last_name")
103
    
104
    def __init__(self, *args, **kwargs):
105
        """
106
        Changes the order of fields, and removes the username field.
107
        """
108
        super(InvitedLocalUserCreationForm, self).__init__(*args, **kwargs)
109
        self.fields.keyOrder = ['email', 'inviter', 'first_name',
110
                                'last_name', 'password1', 'password2']
111
        #set readonly form fields
112
        self.fields['inviter'].widget.attrs['readonly'] = True
113
        self.fields['email'].widget.attrs['readonly'] = True
114
        self.fields['username'].widget.attrs['readonly'] = True
115
    
116
    def save(self, commit=True):
117
        user = super(InvitedLocalUserCreationForm, self).save(commit=False)
118
        level = user.invitation.inviter.level + 1
119
        user.level = level
120
        user.invitations = INVITATIONS_PER_LEVEL[level]
121
        if commit:
122
            user.save()
123
        return user
124

    
125
class LoginForm(AuthenticationForm):
126
    username = forms.EmailField(label=_("Email"))
127

    
128
class ProfileForm(forms.ModelForm):
129
    """
130
    Subclass of ``ModelForm`` for permiting user to edit his/her profile.
131
    Most of the fields are readonly since the user is not allowed to change them.
132
    
133
    The class defines a save method which sets ``is_verified`` to True so as the user
134
    during the next login will not to be redirected to profile page.
135
    """
136
    renew = forms.BooleanField(label='Renew token', required=False)
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 self.cleaned_data.get('renew'):
154
            user.renew_token()
155
        if commit:
156
            user.save()
157
        return user
158

    
159
class ThirdPartyUserCreationForm(ProfileForm):
160
    class Meta:
161
        model = AstakosUser
162
        fields = ('email', 'last_name', 'first_name', 'affiliation', 'provider', 'third_party_identifier')
163
    
164
    def __init__(self, *args, **kwargs):
165
        super(ThirdPartyUserCreationForm, self).__init__(*args, **kwargs)
166
        self.fields.keyOrder = ['email']
167
    
168
    def clean_email(self):
169
        email = self.cleaned_data['email']
170
        if not email:
171
            raise forms.ValidationError(_("This field is required"))
172
        try:
173
            user = AstakosUser.objects.get(email = email)
174
            raise forms.ValidationError(_("Email is reserved"))
175
        except AstakosUser.DoesNotExist:
176
            return email
177
    
178
    def save(self, commit=True):
179
        user = super(ThirdPartyUserCreationForm, self).save(commit=False)
180
        user.verified = False
181
        user.renew_token()
182
        if commit:
183
            user.save()
184
        logger.info('Created user %s', user)
185
        return user
186

    
187
class InvitedThirdPartyUserCreationForm(ThirdPartyUserCreationForm):
188
    def __init__(self, *args, **kwargs):
189
        super(InvitedThirdPartyUserCreationForm, self).__init__(*args, **kwargs)
190
        #set readonly form fields
191
        self.fields['email'].widget.attrs['readonly'] = True
192

    
193
class FeedbackForm(forms.Form):
194
    """
195
    Form for writing feedback.
196
    """
197
    feedback_msg = forms.CharField(widget=forms.Textarea(),
198
                                label=u'Message', required=False)
199
    feedback_data = forms.CharField(widget=forms.HiddenInput(),
200
                                label='', required=False)
201

    
202
class SendInvitationForm(forms.Form):
203
    """
204
    Form for sending an invitations
205
    """
206
    
207
    email = forms.EmailField(required = True, label = 'Email address')
208
    first_name = forms.EmailField(label = 'First name')
209
    last_name = forms.EmailField(label = 'Last name')
210

    
211
class ExtendedPasswordResetForm(PasswordResetForm):
212
    """
213
    Extends PasswordResetForm by overriding save method:
214
    passes a custom from_email in send_mail.
215
    
216
    Since Django 1.3 this is useless since ``django.contrib.auth.views.reset_password``
217
    accepts a from_email argument.
218
    """
219
    def save(self, domain_override=None, email_template_name='registration/password_reset_email.html',
220
             use_https=False, token_generator=default_token_generator, request=None):
221
        """
222
        Generates a one-use only link for resetting password and sends to the user.
223
        """
224
        for user in self.users_cache:
225
            t = loader.get_template(email_template_name)
226
            c = {
227
                'email': user.email,
228
                'domain': BASEURL,
229
                'site_name': SITENAME,
230
                'uid': int_to_base36(user.id),
231
                'user': user,
232
                'token': token_generator.make_token(user)
233
            }
234
            from_email = DEFAULT_FROM_EMAIL
235
            send_mail(_("Password reset on %s") % SITENAME,
236
                t.render(Context(c)), from_email, [user.email])