Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / activation_backends.py @ f46c95c4

History | View | Annotate | Download (10.3 kB)

1
# Copyright 2011 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.utils.importlib import import_module
35
from django.core.exceptions import ImproperlyConfigured
36
from django.utils.translation import ugettext as _
37

    
38
from astakos.im.models import AstakosUser
39
from astakos.im.forms import LocalUserCreationForm, ShibbolethUserCreationForm
40
from astakos.im.util import get_invitation
41
from astakos.im.functions import (send_verification, send_activation,
42
                                  send_account_creation_notification,
43
                                  send_group_creation_notification, activate)
44
from astakos.im.settings import INVITATIONS_ENABLED, MODERATION_ENABLED, SITENAME, RE_USER_EMAIL_PATTERNS
45

    
46
import logging
47
import re
48

    
49
logger = logging.getLogger(__name__)
50

    
51

    
52
def get_backend(request):
53
    """
54
    Returns an instance of an activation backend,
55
    according to the INVITATIONS_ENABLED setting
56
    (if True returns ``astakos.im.activation_backends.InvitationsBackend`` and if False
57
    returns ``astakos.im.activation_backends.SimpleBackend``).
58

59
    If the backend cannot be located ``django.core.exceptions.ImproperlyConfigured``
60
    is raised.
61
    """
62
    module = 'astakos.im.activation_backends'
63
    prefix = 'Invitations' if INVITATIONS_ENABLED else 'Simple'
64
    backend_class_name = '%sBackend' % prefix
65
    try:
66
        mod = import_module(module)
67
    except ImportError, e:
68
        raise ImproperlyConfigured(
69
            'Error loading activation backend %s: "%s"' % (module, e))
70
    try:
71
        backend_class = getattr(mod, backend_class_name)
72
    except AttributeError:
73
        raise ImproperlyConfigured('Module "%s" does not define a activation backend named "%s"' % (module, backend_class_name))
74
    return backend_class(request)
75

    
76

    
77
class ActivationBackend(object):
78
    def __init__(self, request):
79
        self.request = request
80

    
81
    def _is_preaccepted(self, user):
82
        # return True if user email matches specific patterns
83
        for pattern in RE_USER_EMAIL_PATTERNS:
84
            if re.match(pattern, user.email):
85
                return True
86
        return False
87

    
88
    def get_signup_form(self, provider='local', instance=None):
89
        """
90
        Returns a form instance of the relevant class
91
        """
92
        main = provider.capitalize() if provider == 'local' else 'ThirdParty'
93
        suffix = 'UserCreationForm'
94
        formclass = '%s%s' % (main, suffix)
95
        request = self.request
96
        initial_data = None
97
        if request.method == 'POST':
98
            if provider == request.POST.get('provider', ''):
99
                initial_data = request.POST
100
        return globals()[formclass](initial_data, instance=instance, request=request)
101

    
102
    def handle_activation(self, user,
103
                          activation_template_name='im/activation_email.txt',
104
                          greeting_template_name='im/welcome_email.txt',
105
                          admin_email_template_name='im/account_notification.txt',
106
                          switch_accounts_email_template_name='im/switch_accounts_email.txt'):
107
        """
108
        If the user is already active returns immediately.
109
        If the user is not active and there is another account associated with
110
        the specific email, it sends an informative email to the user whether
111
        wants to switch to this account.
112
        If the user is preaccepted and the email is verified, the account is
113
        activated automatically. Otherwise, if the email is not verified,
114
        it sends a verification email to the user.
115
        If the user is not preaccepted, it sends an email to the administrators
116
        and informs the user that the account is pending activation.
117
        """
118
        try:
119
            if user.is_active:
120
                return RegistationCompleted()
121
            if user.conflicting_email():
122
                send_verification(user, switch_accounts_email_template_name)
123
                return SwitchAccountsVerificationSent(user.email)
124

    
125
            if self._is_preaccepted(user):
126
                if user.email_verified:
127
                    activate(user, greeting_template_name)
128
                    return RegistationCompleted()
129
                else:
130
                    send_activation(user, activation_template_name)
131
                    return VerificationSent()
132
            else:
133
                send_account_creation_notification(
134
                    template_name=admin_email_template_name,
135
                    dictionary={'user': user, 'group_creation': True}
136
                )
137
                return NotificationSent()
138
        except BaseException, e:
139
            logger.exception(e)
140
            raise e
141

    
142

    
143
class InvitationsBackend(ActivationBackend):
144
    """
145
    A activation backend which implements the following workflow: a user
146
    supplies the necessary registation information, if the request contains a valid
147
    inivation code the user is automatically activated otherwise an inactive user
148
    account is created and the user is going to receive an email as soon as an
149
    administrator activates his/her account.
150
    """
151

    
152
    def get_signup_form(self, provider='local', instance=None):
153
        """
154
        Returns a form instance of the relevant class
155

156
        raises Invitation.DoesNotExist and ValueError if invitation is consumed
157
        or invitation username is reserved.
158
        """
159
        self.invitation = get_invitation(self.request)
160
        invitation = self.invitation
161
        initial_data = self.get_signup_initial_data(provider)
162
        prefix = 'Invited' if invitation else ''
163
        main = provider.capitalize()
164
        suffix = 'UserCreationForm'
165
        formclass = '%s%s%s' % (prefix, main, suffix)
166
        return globals()[formclass](initial_data, instance=instance, request=self.request)
167

    
168
    def get_signup_initial_data(self, provider):
169
        """
170
        Returns the necassary activation form depending the user is invited or not
171

172
        Throws Invitation.DoesNotExist in case ``code`` is not valid.
173
        """
174
        request = self.request
175
        invitation = self.invitation
176
        initial_data = None
177
        if request.method == 'GET':
178
            if invitation:
179
                # create a tmp user with the invitation realname
180
                # to extract first and last name
181
                u = AstakosUser(realname=invitation.realname)
182
                initial_data = {'email': invitation.username,
183
                                'inviter': invitation.inviter.realname,
184
                                'first_name': u.first_name,
185
                                'last_name': u.last_name,
186
                                'provider': provider}
187
        else:
188
            if provider == request.POST.get('provider', ''):
189
                initial_data = request.POST
190
        return initial_data
191

    
192
    def _is_preaccepted(self, user):
193
        """
194
        If there is a valid, not-consumed invitation code for the specific user
195
        returns True else returns False.
196
        """
197
        if super(InvitationsBackend, self)._is_preaccepted(user):
198
            return True
199
        invitation = self.invitation
200
        if not invitation:
201
            return False
202
        if invitation.username == user.email and not invitation.is_consumed:
203
            invitation.consume()
204
            return True
205
        return False
206

    
207

    
208
class SimpleBackend(ActivationBackend):
209
    """
210
    A activation backend which implements the following workflow: a user
211
    supplies the necessary registation information, an incative user account is
212
    created and receives an email in order to activate his/her account.
213
    """
214
    def _is_preaccepted(self, user):
215
        if super(SimpleBackend, self)._is_preaccepted(user):
216
            return True
217
        if MODERATION_ENABLED:
218
            return False
219
        return True
220

    
221

    
222
class ActivationResult(object):
223
    def __init__(self, message):
224
        self.message = message
225

    
226

    
227
class VerificationSent(ActivationResult):
228
    def __init__(self):
229
        message = _('Verification sent.')
230
        super(VerificationSent, self).__init__(message)
231

    
232

    
233
class SwitchAccountsVerificationSent(ActivationResult):
234
    def __init__(self, email):
235
        message = _('This email is already associated with another \
236
                    local account. To change this account to a shibboleth \
237
                    one follow the link in the verification email sent \
238
                    to %s. Otherwise just ignore it.' % email)
239
        super(SwitchAccountsVerificationSent, self).__init__(message)
240

    
241

    
242
class NotificationSent(ActivationResult):
243
    def __init__(self):
244
        message = _('Your request for an account was successfully received and is now pending \
245
                    approval. You will be notified by email in the next few days. Thanks for \
246
                    your interest in ~okeanos! The GRNET team.')
247
        super(NotificationSent, self).__init__(message)
248

    
249

    
250
class RegistationCompleted(ActivationResult):
251
    def __init__(self):
252
        message = _('Registration completed. You can now login.')
253
        super(RegistationCompleted, self).__init__(message)