1 # Copyright 2011 GRNET S.A. All rights reserved.
3 # Redistribution and use in source and binary forms, with or
4 # without modification, are permitted provided that the following
7 # 1. Redistributions of source code must retain the above
8 # copyright notice, this list of conditions and the following
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.
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.
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.
34 from django.utils.importlib import import_module
35 from django.core.exceptions import ImproperlyConfigured
36 from django.core.mail import send_mail
37 from django.template.loader import render_to_string
38 from django.contrib import messages
39 from django.core.urlresolvers import reverse
40 from django.utils.translation import ugettext as _
41 from django.db import transaction
43 from urlparse import urljoin
45 from astakos.im.models import AstakosUser, Invitation
46 from astakos.im.forms import *
47 from astakos.im.util import get_invitation
48 from astakos.im.functions import send_verification, send_activation, \
49 send_admin_notification, activate, SendMailError
50 from astakos.im.settings import INVITATIONS_ENABLED, DEFAULT_CONTACT_EMAIL, \
51 DEFAULT_FROM_EMAIL, MODERATION_ENABLED, SITENAME, DEFAULT_ADMIN_EMAIL, RE_USER_EMAIL_PATTERNS
57 logger = logging.getLogger(__name__)
59 def get_backend(request):
61 Returns an instance of an activation backend,
62 according to the INVITATIONS_ENABLED setting
63 (if True returns ``astakos.im.activation_backends.InvitationsBackend`` and if False
64 returns ``astakos.im.activation_backends.SimpleBackend``).
66 If the backend cannot be located ``django.core.exceptions.ImproperlyConfigured``
69 module = 'astakos.im.activation_backends'
70 prefix = 'Invitations' if INVITATIONS_ENABLED else 'Simple'
71 backend_class_name = '%sBackend' %prefix
73 mod = import_module(module)
74 except ImportError, e:
75 raise ImproperlyConfigured('Error loading activation backend %s: "%s"' % (module, e))
77 backend_class = getattr(mod, backend_class_name)
78 except AttributeError:
79 raise ImproperlyConfigured('Module "%s" does not define a activation backend named "%s"' % (module, attr))
80 return backend_class(request)
82 class ActivationBackend(object):
83 def _is_preaccepted(self, user):
84 # return True if user email matches specific patterns
85 for pattern in RE_USER_EMAIL_PATTERNS:
86 if re.match(pattern, user.email):
90 def get_signup_form(self, provider='local', instance=None):
92 Returns a form instance of the relevant class
94 main = provider.capitalize() if provider == 'local' else 'ThirdParty'
95 suffix = 'UserCreationForm'
96 formclass = '%s%s' % (main, suffix)
97 request = self.request
99 if request.method == 'POST':
100 if provider == request.POST.get('provider', ''):
101 initial_data = request.POST
102 return globals()[formclass](initial_data, instance=instance, request=request)
104 def handle_activation(
105 self, user, activation_template_name='im/activation_email.txt',
106 greeting_template_name='im/welcome_email.txt',
107 admin_email_template_name='im/admin_notification.txt'
110 If the user is already active returns immediately.
111 If the user is not active and there is another account associated with
112 the specific email, it sends an informative email to the user whether
113 wants to switch to this account.
114 If the user is preaccepted and the email is verified, the account is
115 activated automatically. Otherwise, if the email is not verified,
116 it sends a verification email to the user.
117 If the user is not preaccepted, it sends an email to the administrators
118 and informs the user that the account is pending activation.
122 return RegistationCompleted()
124 if self._is_preaccepted(user):
125 if user.email_verified:
126 activate(user, greeting_template_name)
127 return RegistationCompleted()
129 send_activation(user, activation_template_name)
130 return VerificationSent()
132 send_admin_notification(user, admin_email_template_name)
133 return NotificationSent()
134 except BaseException, e:
138 class InvitationsBackend(ActivationBackend):
140 A activation backend which implements the following workflow: a user
141 supplies the necessary registation information, if the request contains a valid
142 inivation code the user is automatically activated otherwise an inactive user
143 account is created and the user is going to receive an email as soon as an
144 administrator activates his/her account.
146 def __init__(self, request):
147 self.request = request
148 super(InvitationsBackend, self).__init__()
150 def get_signup_form(self, provider='local', instance=None):
152 Returns a form instance of the relevant class
154 raises Invitation.DoesNotExist and ValueError if invitation is consumed
155 or invitation username is reserved.
157 self.invitation = get_invitation(self.request)
158 invitation = self.invitation
159 initial_data = self.get_signup_initial_data(provider)
160 prefix = 'Invited' if invitation else ''
161 main = provider.capitalize()
162 suffix = 'UserCreationForm'
163 formclass = '%s%s%s' % (prefix, main, suffix)
164 return globals()[formclass](initial_data, instance=instance, request=self.request)
166 def get_signup_initial_data(self, provider):
168 Returns the necassary activation form depending the user is invited or not
170 Throws Invitation.DoesNotExist in case ``code`` is not valid.
172 request = self.request
173 invitation = self.invitation
175 if request.method == 'GET':
177 # create a tmp user with the invitation realname
178 # to extract first and last name
179 u = AstakosUser(realname = invitation.realname)
180 initial_data = {'email':invitation.username,
181 'inviter':invitation.inviter.realname,
182 'first_name':u.first_name,
183 'last_name':u.last_name,
186 if provider == request.POST.get('provider', ''):
187 initial_data = request.POST
190 def _is_preaccepted(self, user):
192 If there is a valid, not-consumed invitation code for the specific user
193 returns True else returns False.
195 if super(InvitationsBackend, self)._is_preaccepted(user):
197 invitation = self.invitation
200 if invitation.username == user.email and not invitation.is_consumed:
205 class SimpleBackend(ActivationBackend):
207 A activation backend which implements the following workflow: a user
208 supplies the necessary registation information, an incative user account is
209 created and receives an email in order to activate his/her account.
211 def __init__(self, request):
212 self.request = request
213 super(SimpleBackend, self).__init__()
215 def _is_preaccepted(self, user):
216 if super(SimpleBackend, self)._is_preaccepted(user):
218 if MODERATION_ENABLED:
222 class ActivationResult(object):
223 def __init__(self, message):
224 self.message = message
226 class VerificationSent(ActivationResult):
228 message = _('Verification sent.')
229 super(VerificationSent, self).__init__(message)
231 class NotificationSent(ActivationResult):
233 message = _('Your request for an account was successfully received and is now pending \
234 approval. You will be notified by email in the next few days. Thanks for \
235 your interest in ~okeanos! The GRNET team.')
236 super(NotificationSent, self).__init__(message)
238 class RegistationCompleted(ActivationResult):
240 message = _('Registration completed. You can now login.')
241 super(RegistationCompleted, self).__init__(message)