Projet

Général

Profil

0001-Registration-process-refactored-django-registration-.patch

Serghei Mihai (congés, retour 15/05), 11 septembre 2014 10:10

Télécharger (14,5 ko)

Voir les différences:

Subject: [PATCH 1/3] Registration process refactored, django-registration
 removed.

 authentic2/registration_backend/urls.py         |  98 ++++++++++-----------
 authentic2/registration_backend/views.py        | 109 +++++++++++++-----------
 authentic2/templates/registration/activate.html |   6 ++
 authentic2/urls.py                              |   2 +
 authentic2/utils.py                             |   5 ++
 requirements.txt                                |   1 -
 setup.py                                        |   1 -
 7 files changed, 118 insertions(+), 104 deletions(-)
authentic2/registration_backend/urls.py
4 4
from django.contrib.auth import views as auth_views
5 5
from django.views.generic.base import TemplateView
6 6

  
7

  
7
from authentic2.utils import get_form_class
8 8
from .. import app_settings
9

  
10
from registration.backends.default.views import ActivationView
11

  
12

  
13
def get_form_class(form_class):
14
    module, form_class = form_class.rsplit('.', 1)
15
    module = import_module(module)
16
    return getattr(module, form_class)
17

  
9
from .views import RegistrationView, ActivationView
18 10

  
19 11
SET_PASSWORD_FORM_CLASS = get_form_class(
20 12
        app_settings.A2_REGISTRATION_SET_PASSWORD_FORM_CLASS)
......
23 15

  
24 16

  
25 17
urlpatterns = patterns('authentic2.registration_backend.views',
26
                       url(r'^activate/complete/$',
27
                           TemplateView.as_view(template_name='registration/activation_complete.html'),
28
                           name='registration_activation_complete'),
29
                       # Activation keys get matched by \w+ instead of the more specific
30
                       # [a-fA-F0-9]{40} because a bad activation key should still get to the view;
31
                       # that way it can return a sensible "invalid key" message instead of a
32
                       # confusing 404.
33
                       url(r'^activate/(?P<activation_key>\w+)/$',
34
                           ActivationView.as_view(),
35
                           name='registration_activate'),
36
                       url(r'^register/$',
37
                           'register',
38
                           name='registration_register'),
39
                       url(r'^register/complete/$',
40
                           TemplateView.as_view(template_name='registration/registration_complete.html'),
41
                           name='registration_complete'),
42
                       url(r'^register/closed/$',
43
                           TemplateView.as_view(template_name='registration/registration_closed.html'),
44
                           name='registration_disallowed'),
45
                       url(r'^password/change/$',
46
                           auth_views.password_change,
47
                           {'password_change_form': CHANGE_PASSWORD_FORM_CLASS},
48
                           name='auth_password_change'),
49
                       url(r'^password/change/done/$',
50
                           auth_views.password_change_done,
51
                           name='auth_password_change_done'),
52
                       url(r'^password/reset/$',
53
                           auth_views.password_reset,
54
                           name='auth_password_reset'),
55
                       url(r'^password/reset/confirm/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$',
56
                           auth_views.password_reset_confirm,
57
                           {'set_password_form': SET_PASSWORD_FORM_CLASS},
58
                           name='auth_password_reset_confirm'),
59
                       url(r'^password/reset/complete/$',
60
                           auth_views.password_reset_complete,
61
                           name='auth_password_reset_complete'),
62
                       url(r'^password/reset/done/$',
63
                           auth_views.password_reset_done,
64
                           name='auth_password_reset_done'),
65
                       url(r'^delete/$',
66
                           'delete',
67
                           name='delete_account'),
68
                       )
18
    url(r'^activate/complete/$',
19
        TemplateView.as_view(template_name='registration/activation_complete.html'),
20
        name='registration_activation_complete'),
21
    # Activation keys get matched by \w+ instead of the more specific
22
    # [a-fA-F0-9]{40} because a bad activation key should still get to the view;
23
    # that way it can return a sensible "invalid key" message instead of a
24
    # confusing 404.
25
    url(r'^activate/(?P<activation_key>[\w:-]+)/$',
26
        ActivationView.as_view(),
27
        name='registration_activate'),
28
    url(r'^register/$',
29
        RegistrationView.as_view(),
30
        name='registration_register'),
31
    url(r'^register/complete/$',
32
        TemplateView.as_view(template_name='registration/registration_complete.html'),
33
        name='registration_complete'),
34
    url(r'^register/closed/$',
35
        TemplateView.as_view(template_name='registration/registration_closed.html'),
36
        name='registration_disallowed'),
37
    url(r'^password/change/$',
38
        auth_views.password_change,
39
        {'password_change_form': CHANGE_PASSWORD_FORM_CLASS},
40
        name='auth_password_change'),
41
    url(r'^password/change/done/$',
42
        auth_views.password_change_done,
43
        name='auth_password_change_done'),
44
    url(r'^password/reset/confirm/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$',
45
        auth_views.password_reset_confirm,
46
        {'set_password_form': SET_PASSWORD_FORM_CLASS},
47
        name='auth_password_reset_confirm'),
48
    url(r'^delete/$',
49
        'delete',
50
        name='delete_account'),
51
    url(r'^password/reset/$',
52
        auth_views.password_reset,
53
        name='auth_password_reset'),
54
    url(r'^password/reset/complete/$',
55
        auth_views.password_reset_complete,
56
        name='auth_password_reset_complete'),
57
    url(r'^password/reset/done/$',
58
        auth_views.password_reset_done,
59
        name='auth_password_reset_done'),
60
)
authentic2/registration_backend/views.py
1 1
import logging
2

  
2
from datetime import datetime
3 3

  
4 4
from django.shortcuts import redirect, render
5 5
from django.utils.translation import ugettext as _
6 6
from django.contrib import messages
7 7
from django.contrib.auth.decorators import login_required
8
from django.contrib.sites.models import RequestSite
9
from django.contrib.sites.models import Site
8
from django.contrib.sites.models import Site, RequestSite
10 9
from django.contrib.auth.models import BaseUserManager, Group
11 10
from django.conf import settings
12 11
from django.db.models import FieldDoesNotExist
12
from django.db import IntegrityError
13
from django.core import signing
14
from django.core.mail import send_mail
13 15

  
16
from django.template.loader import render_to_string
14 17

  
15
from registration.views import RegistrationView as BaseRegistrationView
16
from registration.models import RegistrationProfile
17
from registration import signals
18
from django.views.generic.edit import FormView
19
from django.views.generic.base import TemplateView
18 20

  
21
from authentic2.utils import get_form_class
19 22
from .. import models, app_settings, compat
20
from . import urls
21 23

  
24
EXPIRATION = settings.ACCOUNT_ACTIVATION_DAYS
22 25

  
23 26
logger = logging.getLogger(__name__)
24 27

  
28
class RegistrationView(FormView):
29
    form_class = get_form_class(app_settings.A2_REGISTRATION_FORM_CLASS)
30
    template_name = 'registration/registration_form.html'
25 31

  
26
class RegistrationView(BaseRegistrationView):
27
    form_class = urls.get_form_class(app_settings.A2_REGISTRATION_FORM_CLASS)
28

  
29
    def register(self, request, **cleaned_data):
30
        User = compat.get_user_model()
32
    def form_valid(self, form):
31 33
        if Site._meta.installed:
32 34
            site = Site.objects.get_current()
33 35
        else:
34
            site = RequestSite(request)
36
            site = RequestSite(self.request)
37

  
38
        activation_key = signing.dumps(form.cleaned_data)
39
        ctx_dict = {'activation_key': activation_key,
40
                    'user': form.cleaned_data,
41
                    'expiration_days': EXPIRATION,
42
                    'site': site}
43

  
44
        subject = render_to_string('registration/activation_email_subject.txt',
45
                                   ctx_dict)
46

  
47
        subject = ''.join(subject.splitlines())
48
        message = render_to_string('registration/activation_email.txt',
49
                                   ctx_dict)
50

  
51
        send_mail(subject, message, settings.DEFAULT_FROM_EMAIL,
52
                  [form.cleaned_data['email']], fail_silently=True)
53
        return redirect('registration_complete')
54

  
55
register = RegistrationView.as_view()
56

  
57
class ActivationView(TemplateView):
58
    http_method_names = ['get']
59
    template_name = 'registration/activate.html'
60

  
61
    def get(self, request, *args, **kwargs):
62
        context = {}
63
        try:
64
            self.register(kwargs['activation_key'])
65
            return redirect('registration_activation_complete')
66
        except signing.SignatureExpired:
67
            context['expired'] = True
68
        except IntegrityError:
69
            context['existing_user'] = True
70
        return self.render_to_response(context)
71

  
72
    def register(self, registration_token):
73
        User = compat.get_user_model()
74
        registration_fields = signing.loads(registration_token,
75
                                            max_age=EXPIRATION * 3600 * 24)
35 76
        user_fields = {}
36 77
        for field in compat.get_registration_fields():
37 78
            # save User model fields
......
41 82
                continue
42 83
            if field.startswith('password'):
43 84
                continue
44
            user_fields[field] = cleaned_data[field]
85
            user_fields[field] = registration_fields[field]
45 86
            if field == 'email':
46 87
                user_fields[field] = BaseUserManager.normalize_email(user_fields[field])
47
        new_user = User(is_active=False, **user_fields)
88

  
89
        new_user = User(is_active=True, **user_fields)
48 90
        new_user.clean()
49
        new_user.set_password(cleaned_data['password1'])
91
        new_user.set_password(registration_fields['password1'])
50 92
        new_user.save()
93

  
51 94
        attributes = models.Attribute.objects.filter(
52 95
                asked_on_registration=True)
53 96
        if attributes:
54 97
            for attribute in attributes:
55
                attribute.set_value(new_user, cleaned_data[attribute.name])
98
                attribute.set_value(new_user, registration_fields[attribute.name])
56 99
        if app_settings.A2_REGISTRATION_GROUPS:
57 100
            groups = []
58 101
            for name in app_settings.A2_REGISTRATION_GROUPS:
59 102
                group, created = Group.objects.get_or_create(name=name)
60 103
                groups.append(group)
61 104
            new_user.groups = groups
62
        registration_profile = RegistrationProfile.objects.create_profile(new_user)
63
        registration_profile.send_activation_email(site)
64

  
65
        signals.user_registered.send(sender=self.__class__,
66
                                     user=new_user,
67
                                     request=request)
68 105
        return new_user
69 106

  
70
    def registration_allowed(self, request):
71
        """
72
        Indicate whether account registration is currently permitted,
73
        based on the value of the setting ``REGISTRATION_OPEN``. This
74
        is determined as follows:
75

  
76
        * If ``REGISTRATION_OPEN`` is not specified in settings, or is
77
          set to ``True``, registration is permitted.
78

  
79
        * If ``REGISTRATION_OPEN`` is both specified and set to
80
          ``False``, registration is not permitted.
81
        
82
        """
83
        return getattr(settings, 'REGISTRATION_OPEN', True)
84

  
85
    def get_success_url(self, request, user):
86
        """
87
        Return the name of the URL to redirect to after successful
88
        user registration.
89
        
90
        """
91
        return ('registration_complete', (), {})
92

  
93
register = RegistrationView.as_view()
94

  
95

  
96 107
@login_required
97 108
def delete(request, next_url='/'):
98 109
    next_url = request.build_absolute_uri(request.META.get('HTTP_REFERER') or next_url)
authentic2/templates/registration/activate.html
16 16
{% else %}
17 17

  
18 18
<p>{% trans "Account activation failed" %}</p>
19
{% if expired %}
20
<p>{% trans "Your activation key is expired" %}</p>
21
{% endif %}
22
{% if existing_user %}
23
<p>{% trans "A user with that username already exists." %}</p>
24
{% endif %}
19 25

  
20 26
{% endif %}
21 27

  
authentic2/urls.py
18 18
    url(r'^accounts/', include('authentic2.profile_urls')),
19 19
)
20 20

  
21

  
22

  
21 23
not_homepage_patterns += patterns('',
22 24
    url(r'^accounts/', include(app_settings.A2_REGISTRATION_URLCONF)),
23 25
    url(r'^admin/', include(admin.site.urls)),
authentic2/utils.py
206 206
            yield t
207 207
        else:
208 208
            yield t[0]
209

  
210
def get_form_class(form_class):
211
    module, form_class = form_class.rsplit('.', 1)
212
    module = import_module(module)
213
    return getattr(module, form_class)
requirements.txt
2 2
south>=0.8.4,<0.9
3 3
requests
4 4
django-model-utils
5
django-registration>=1
6 5
django-debug-toolbar>=1.2,<1.3
7 6
--allow-external django-admin-tools
8 7
--allow-unverified django-admin-tools
setup.py
117 117
        'south>=0.8.4,<0.9',
118 118
        'requests',
119 119
        'django-model-utils',
120
        'django-registration>=1',
121 120
        'django-admin-tools>=0.5.1',
122 121
        'django-debug-toolbar>=1.2,<1.3',
123 122
        'dnspython',
124
-