views.py 11.6 KB
Newer Older
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
1
2
import logging

3
from django.db import router
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
4
5
6
from django import forms
from django.conf import settings
from django.contrib import messages
7
from django.contrib.admin.utils import NestedObjects
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
8
9
10
from django.contrib.auth import update_session_auth_hash, authenticate, login, get_user_model
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import PasswordChangeForm
11
from django.contrib.auth.models import Group
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
12
13
14
from django.core.mail import send_mail
from django.db.models import ProtectedError
from django.forms import widgets
15
from django.http import HttpResponseForbidden
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
16
17
from django.shortcuts import render, redirect
from django.template import TemplateDoesNotExist
18
19
20
from django.urls import reverse
from django.utils.encoding import force_bytes, force_text
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
21
22
from django.utils.translation import ugettext

23
from basetheme_bootstrap import tokens
24
from basetheme_bootstrap import user_preferences_utils
25
from basetheme_bootstrap.default_settings import is_validating_email
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
26
27
28
29
30
from basetheme_bootstrap.forms import UserCreationFormWithMore, \
    MyUserChangeForm, UserDeleteForm

logger = logging.getLogger(__name__)

31
32
33
34
__PENDING_ACCOUNT_USER = "PendingAccountUser"

def get_pending_account_user_group_name():
    return __PENDING_ACCOUNT_USER
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67

def about_page(request):
    context = {}
    try:
        return render(request, settings.BASETHEME_BOOTSTRAP_TEMPLATE_LOCATION_PROJECT + '/about.html')
    except TemplateDoesNotExist:
        return render(request, 'basetheme_bootstrap/about.example.html')


@login_required
def change_password(request):
    if request.method == 'POST':
        form = PasswordChangeForm(request.user, request.POST)
        if form.is_valid():
            user = form.save()
            update_session_auth_hash(request, user)  # Important!
            messages.success(request, 'Your password was successfully updated!')
            return redirect('basetheme_bootstrap:account')
        else:
            messages.error(request, 'Please correct the error below.')
    else:
        form = PasswordChangeForm(request.user)
    return render(request, 'registration/small_form_host.html', {
        'title': ugettext('Change password'),
        'submit_text': ugettext('Save changes'),
        'form': form
    })


def signup(request):
    if request.method == 'POST':
        form = UserCreationFormWithMore(request.POST)
        if form.is_valid():
68
            auto_active = not is_validating_email()
69
            next_page = form.cleaned_data["next"]
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
70
71
72
73
            user = form.save()
            if get_user_model().objects.filter(pk__gt=1).count() == 0:
                user.is_superuser = True
                user.is_staff = True
74
                user.is_active = True
75
                Group.objects.get_or_create(name=__PENDING_ACCOUNT_USER)
76
77
            else:
                if not auto_active:
78
                    g, created = Group.objects.get_or_create(name=__PENDING_ACCOUNT_USER)
79
80
81
82
                    user.groups.add(g)
                user.is_active = auto_active
            user.save()

83
            send_account_created(request, user, auto_active=auto_active, next_page=next_page)
84

85
            if not auto_active and not user.is_superuser:
86
87
                return account_is_pending_view(request, email=request.POST['email'])

88
            username = user.username
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
89
90
91
92
93
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=username, password=raw_password)
            request.user = user

            login(request, user)
94
            return redirect(next_page if next_page else 'home')
95
        else:
96
            user = get_user_model().objects.filter(groups__name=__PENDING_ACCOUNT_USER,
97
98
99
100
                                                   email=request.POST['email']).first()
            if user is not None:
                send_account_created(request, user, auto_active=not is_validating_email())
                return account_is_pending_view(request, email=request.POST['email'])
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
101
    else:
102
103
        if not request.user.is_anonymous:
            return HttpResponseForbidden()
104
105
106
107
108
        try:
            initial = dict(next=request.GET["next"])
        except KeyError:
            initial = None
        form = UserCreationFormWithMore(initial=initial)
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
109
110
111
    return render(request, 'registration/signup.html', {'form': form})


112
113
114
115
116
117
118
119
120
def account_is_pending_view(request, email):
    return render(request, 'basetheme_bootstrap/simple_message_page.html', {
        'page_title': ugettext('Account activation pending'),
        'message': ugettext('An email was sent with a link to validate your account, '
                            'please click on the link to enable your account.'),
        'sub_message': ugettext('The email has been addressed  to %s.') % email,
    })


121
def send_account_created(request, user, auto_active=False, next_page=None):
122
123
124
    try:
        activation_link = request.scheme + "://" + request.get_host()
        activation_link += reverse('basetheme_bootstrap:activate', kwargs={
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
125
            'uidb64': urlsafe_base64_encode(force_bytes(user.pk)),
126
127
            'token': tokens.account_activation_token.make_token(user)
        })
128
        if next_page:
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
129
            activation_link += "?next=" + next_page
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
        if auto_active:
            message = ugettext(
                'Dear %(first_name)s %(last_name)s\n\n'
                'Your account have successfully been created on %(joined)s.'
                '\n\n'
                'Best regards') % dict(
                first_name=user.first_name,
                last_name=user.last_name,
                joined=str(user.date_joined),
            )
        else:
            message = ugettext(
                'Dear %(first_name)s %(last_name)s\n\n'
                'Your account have successfully been created on %(joined)s.'
                '\n\n'
                'Please click on the link to confirm your registration\n'
                '%(activation_link)s'
                '\n\n'
                'Best regards') % dict(
                first_name=user.first_name,
                last_name=user.last_name,
                joined=str(user.date_joined),
                activation_link=activation_link,
            )
        send_mail(
            subject=ugettext('Account successfully created'),
            message=message,
            from_email=settings.DEFAULT_FROM_EMAIL,
            recipient_list=[user.email],
            fail_silently=False,
        )
    except Exception as e:
        logging.exception("Sending email to user %i failed" % user.pk)


Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
def user_update(request):
    if request.method == 'POST':
        form = MyUserChangeForm(instance=request.user, data=request.POST)
        if form.is_valid():
            user = form.save()
            update_session_auth_hash(request, user)  # Important!
            messages.success(request, 'Your account was successfully updated!')
            return redirect('basetheme_bootstrap:account')
        else:
            messages.error(request, 'Please correct the error below.')
    else:
        form = MyUserChangeForm(instance=request.user)
    return render(request, 'registration/small_form_host.html', {
        'title': ugettext('Update account'),
        'submit_text': ugettext('Save changes'),
        'form': form,
        'medium_width': True,
    })


def user_delete(request):
    if request.method == 'POST':
        form = UserDeleteForm(instance=request.user, data=request.POST)
        if form.is_valid():
            try:
                user = form.save()
                user.delete()
                update_session_auth_hash(request, user)  # Important!
                messages.success(request, 'Your account was successfully deleted!')
                return redirect('/')
            except ProtectedError as e:
                messages.error(request, ugettext("Some data remaining in the system prevent the deletion of your "
                                                 "account. Please either remove these data, or contact the "
                                                 "administrator to solve the issue.\nMessage:\n" + str(e)))
            except Exception as e:
                messages.error(request, e)
    else:
        form = UserDeleteForm(instance=request.user)
203
204
205
206
    # Inspired from auth/admin.py#get_deleted_objects
    collector = NestedObjects(using=router.db_for_write(get_user_model()))
    collector.collect([request.user,])
    return render(request, 'registration/account_deletion.html', {
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
207
208
209
        'title': ugettext('Account deletion'),
        'submit_text': ugettext('Delete account and all related data'),
        'form': form,
210
        'protected': collector.protected,
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
211
        'medium_width': True,
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
212
        'btn_classes': 'btn btn-lg btn-danger text-center',
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
213
        'btn_container_classes': 'text-center',
214
        'custom_css_width':' ',
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
215
216
217
    })


218
@login_required
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
219
def account_detail(request):
220
    klass = user_preferences_utils.get_user_preference_class()
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
221
222
223
224
225
    if klass is None:
        form_prefs = None
    else:
        is_posted = request.method == 'POST'
        pref = klass.get_for_user(user=request.user)
226
227
        widgets_dict = dict(
            (f.name, widgets.CheckboxSelectMultiple()) for f in pref._meta.get_fields() if f.many_to_many)
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
228
229
        form_prefs = forms.modelform_factory(
            klass,
230
231
            fields=list(pref.get_allowed_fields()),
            widgets=widgets_dict,
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
232
233
234
        )(instance=pref, data=request.POST if is_posted else None)
        if is_posted and form_prefs.is_valid():
            form_prefs.save()
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
235
            return redirect(reverse("basetheme_bootstrap:account"))
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
236
237
238
239
        # dirty patch for time field (don't know why django doesn't express the correct type by default)
        for f in form_prefs.fields.values():
            if isinstance(f.widget, widgets.TimeInput):
                f.widget.input_type = 'time'
240
241
        form_prefs.preferences_groups = getattr(pref, "preferences_groups", None)
        form_prefs.preferences_groups_descriptions = getattr(pref, "preferences_groups_descriptions", None)
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
242
243
244
245
    return render(request, 'registration/account.html', {
        'form_prefs': form_prefs,
        'btn_classes': 'pull-right float-right'
    })
246
247
248
249
250
251
252
253


def activate(request, uidb64, token):
    try:
        uid = force_text(urlsafe_base64_decode(uidb64))
        user = get_user_model().objects.get(pk=uid)
    except(TypeError, ValueError, OverflowError, get_user_model().DoesNotExist):
        user = None
254
    if user is not None and user.groups.filter(name=__PENDING_ACCOUNT_USER).exists():
255
256
        if tokens.account_activation_token.check_token(user, token):
            user.is_active = True
257
            user.groups.remove(user.groups.get(name=__PENDING_ACCOUNT_USER))
258
259
            user.save()
            login(request, user)
260
261
262
263
264
265
            message = ugettext('Thank you for your email confirmation, you account have been activated '
                               'and you are now logged in.')
            next_page = request.GET.get("next", '')
            if next_page:
                messages.success(request, message)
                return redirect(next_page)
266
267
268
269
            # return redirect('home')
            # return HttpResponse('Thank you for your email confirmation. Now you can login your account.')
            return render(request, 'basetheme_bootstrap/simple_message_page.html', {
                'page_title': ugettext('Account activated'),
270
                'message': message,
271
272
273
274
275
276
277
278
            })
        else:
            send_account_created(request, user)
            return account_is_pending_view(request, email=user.email)
    else:
        return render(request, 'basetheme_bootstrap/simple_message_page.html', {
            'page_title': ugettext('Activation link is invalid!'),
        })