root / astakos / im / backends / __init__.py @ 794852f2
History | View | Annotate | Download (8.5 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.conf import settings |
35 |
from django.utils.importlib import import_module |
36 |
from django.core.exceptions import ImproperlyConfigured |
37 |
from django.core.mail import send_mail |
38 |
from django.template.loader import render_to_string |
39 |
from django.utils.translation import ugettext as _ |
40 |
from django.contrib.auth.forms import UserCreationForm |
41 |
from django.contrib import messages |
42 |
|
43 |
from smtplib import SMTPException |
44 |
from urllib import quote |
45 |
|
46 |
from astakos.im.util import get_or_create_user |
47 |
from astakos.im.models import AstakosUser, Invitation |
48 |
from astakos.im.forms import ExtendedUserCreationForm, InvitedExtendedUserCreationForm |
49 |
|
50 |
def get_backend(): |
51 |
"""
|
52 |
Return an instance of a registration backend,
|
53 |
according to the INVITATIONS_ENABLED setting
|
54 |
(if True returns ``astakos.im.backends.InvitationsBackend`` and if False
|
55 |
returns ``astakos.im.backends.SimpleBackend``).
|
56 |
|
57 |
If the backend cannot be located ``django.core.exceptions.ImproperlyConfigured``
|
58 |
is raised.
|
59 |
"""
|
60 |
module = 'astakos.im.backends'
|
61 |
prefix = 'Invitations' if settings.INVITATIONS_ENABLED else 'Simple' |
62 |
backend_class_name = '%sBackend' %prefix
|
63 |
try:
|
64 |
mod = import_module(module) |
65 |
except ImportError, e: |
66 |
raise ImproperlyConfigured('Error loading registration backend %s: "%s"' % (module, e)) |
67 |
try:
|
68 |
backend_class = getattr(mod, backend_class_name)
|
69 |
except AttributeError: |
70 |
raise ImproperlyConfigured('Module "%s" does not define a registration backend named "%s"' % (module, attr)) |
71 |
return backend_class()
|
72 |
|
73 |
class InvitationsBackend(object): |
74 |
"""
|
75 |
A registration backend which implements the following workflow: a user
|
76 |
supplies the necessary registation information, if the request contains a valid
|
77 |
inivation code the user is automatically activated otherwise an inactive user
|
78 |
account is created and the user is going to receive an email as soon as an
|
79 |
administrator activates his/her account.
|
80 |
"""
|
81 |
def get_signup_form(self, request): |
82 |
"""
|
83 |
Returns the necassary registration form depending the user is invited or not
|
84 |
|
85 |
Throws Invitation.DoesNotExist in case ``code`` is not valid.
|
86 |
"""
|
87 |
code = request.GET.get('code', '') |
88 |
formclass = 'ExtendedUserCreationForm'
|
89 |
initial_data = None
|
90 |
if request.method == 'GET': |
91 |
if code:
|
92 |
formclass = 'Invited%s' %formclass
|
93 |
self.invitation = Invitation.objects.get(code=code)
|
94 |
if self.invitation.is_consumed: |
95 |
raise Exception('Invitation has beeen used') |
96 |
initial_data = {'username':self.invitation.username, |
97 |
'email':self.invitation.username, |
98 |
'realname':self.invitation.realname} |
99 |
inviter = AstakosUser.objects.get(username=self.invitation.inviter)
|
100 |
initial_data['inviter'] = inviter.realname
|
101 |
else:
|
102 |
initial_data = request.POST |
103 |
return globals()[formclass](initial_data) |
104 |
|
105 |
def _is_preaccepted(self, user): |
106 |
"""
|
107 |
If there is a valid, not-consumed invitation code for the specific user
|
108 |
returns True else returns False.
|
109 |
|
110 |
It should be called after ``get_signup_form`` which sets invitation if exists.
|
111 |
"""
|
112 |
invitation = getattr(self, 'invitation') if hasattr(self, 'invitation') else None |
113 |
if not invitation: |
114 |
return False |
115 |
if invitation.username == user.username and not invitation.is_consumed: |
116 |
return True |
117 |
return False |
118 |
|
119 |
def signup(self, request): |
120 |
"""
|
121 |
Creates a incative user account. If the user is preaccepted (has a valid
|
122 |
invitation code) the user is activated and if the request param ``next``
|
123 |
is present redirects to it.
|
124 |
In any other case the method returns the action status and a message.
|
125 |
"""
|
126 |
kwargs = {} |
127 |
form = self.get_signup_form(request)
|
128 |
user = form.save() |
129 |
|
130 |
try:
|
131 |
if self._is_preaccepted(user): |
132 |
user.is_active = True
|
133 |
user.save() |
134 |
message = _('Registration completed. You can now login.')
|
135 |
next = request.POST.get('next')
|
136 |
if next: |
137 |
return redirect(next) |
138 |
else:
|
139 |
message = _('Registration completed. You will receive an email upon your account\'s activation')
|
140 |
status = messages.SUCCESS |
141 |
except Invitation.DoesNotExist, e:
|
142 |
status = messages.ERROR |
143 |
message = _('Invalid invitation code')
|
144 |
return status, message
|
145 |
|
146 |
class SimpleBackend(object): |
147 |
"""
|
148 |
A registration backend which implements the following workflow: a user
|
149 |
supplies the necessary registation information, an incative user account is
|
150 |
created and receives an email in order to activate his/her account.
|
151 |
"""
|
152 |
def get_signup_form(self, request): |
153 |
"""
|
154 |
Returns the UserCreationForm
|
155 |
"""
|
156 |
initial_data = request.POST if request.method == 'POST' else None |
157 |
return UserCreationForm(initial_data)
|
158 |
|
159 |
def signup(self, request, email_template_name='activation_email.txt'): |
160 |
"""
|
161 |
Creates an inactive user account and sends a verification email.
|
162 |
|
163 |
** Arguments **
|
164 |
|
165 |
``email_template_name``
|
166 |
A custom template for the verification email body to use. This is
|
167 |
optional; if not specified, this will default to
|
168 |
``activation_email.txt``.
|
169 |
|
170 |
** Templates **
|
171 |
activation_email.txt or ``email_template_name`` keyword argument
|
172 |
|
173 |
** Settings **
|
174 |
|
175 |
* ACTIVATION_LOGIN_TARGET: Where users should activate their local account
|
176 |
* DEFAULT_CONTACT_EMAIL: service support email
|
177 |
* DEFAULT_FROM_EMAIL: from email
|
178 |
"""
|
179 |
kwargs = {} |
180 |
form = self.get_signup_form(request)
|
181 |
user = form.save() |
182 |
|
183 |
status = messages.SUCCESS |
184 |
try:
|
185 |
_send_verification(request, user, email_template_name) |
186 |
message = _('Verification sent to %s' % user.email)
|
187 |
except (SMTPException, socket.error) as e: |
188 |
status = messages.ERROR |
189 |
name = 'strerror'
|
190 |
message = getattr(e, name) if hasattr(e, name) else e |
191 |
return status, message
|
192 |
|
193 |
def _send_verification(request, user, template_name): |
194 |
site = get_current_site(request) |
195 |
baseurl = request.build_absolute_uri('/').rstrip('/') |
196 |
url = settings.ACTIVATION_LOGIN_TARGET % (baseurl, |
197 |
quote(user.auth_token), |
198 |
quote(baseurl)) |
199 |
message = render_to_string(template_name, { |
200 |
'user': user,
|
201 |
'url': url,
|
202 |
'baseurl': baseurl,
|
203 |
'site_name': site.name,
|
204 |
'support': settings.DEFAULT_CONTACT_EMAIL})
|
205 |
sender = settings.DEFAULT_FROM_EMAIL |
206 |
send_mail('Pithos account activation', message, sender, [user.email])
|
207 |
logging.info('Sent activation %s', user)
|