views.py 11 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
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
24
from basetheme_bootstrap import user_preferences
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()
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
69
70
71
72
            user = form.save()
            if get_user_model().objects.filter(pk__gt=1).count() == 0:
                user.is_superuser = True
                user.is_staff = True
73
                user.is_active = True
74
                Group.objects.get_or_create(name=__PENDING_ACCOUNT_USER)
75
76
            else:
                if not auto_active:
77
                    g, created = Group.objects.get_or_create(name=__PENDING_ACCOUNT_USER)
78
79
80
81
82
83
                    user.groups.add(g)
                user.is_active = auto_active
            user.save()

            send_account_created(request, user, auto_active=auto_active)

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

87
            username = user.username
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
88
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)
            return redirect('home')
94
        else:
95
            user = get_user_model().objects.filter(groups__name=__PENDING_ACCOUNT_USER,
96
97
98
99
                                                   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
100
    else:
101
102
        if not request.user.is_anonymous:
            return HttpResponseForbidden()
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
103
104
105
106
        form = UserCreationFormWithMore()
    return render(request, 'registration/signup.html', {'form': form})


107
108
109
110
111
112
113
114
115
116
117
118
119
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,
    })


def send_account_created(request, user, auto_active=False):
    try:
        activation_link = request.scheme + "://" + request.get_host()
        activation_link += reverse('basetheme_bootstrap:activate', kwargs={
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
120
            'uidb64': urlsafe_base64_encode(force_bytes(user.pk)),
121
122
123
124
125
126
127
128
129
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
            'token': tokens.account_activation_token.make_token(user)
        })
        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
158
159
160
161
162
163
164
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
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)
196
197
198
199
    # 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
200
201
202
        'title': ugettext('Account deletion'),
        'submit_text': ugettext('Delete account and all related data'),
        'form': form,
203
        'protected': collector.protected,
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
204
205
206
        'medium_width': True,
        'btn_classes': 'btn-lg btn-danger text-center',
        'btn_container_classes': 'text-center',
207
        'custom_css_width':' ',
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
208
209
210
    })


211
@login_required
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
def account_detail(request):
    klass = user_preferences.get_user_preference_class()
    if klass is None:
        form_prefs = None
    else:
        is_posted = request.method == 'POST'
        pref = klass.get_for_user(user=request.user)
        form_prefs = forms.modelform_factory(
            klass,
            fields=list(klass.get_allowed_fields()),
        )(instance=pref, data=request.POST if is_posted else None)
        if is_posted and form_prefs.is_valid():
            form_prefs.save()
            form_prefs = forms.modelform_factory(
                klass,
                fields=list(klass.get_allowed_fields()),
            )(instance=klass.get_for_user(user=request.user))
        # 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'
233
234
        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
235
236
237
238
    return render(request, 'registration/account.html', {
        'form_prefs': form_prefs,
        'btn_classes': 'pull-right float-right'
    })
239
240
241
242
243
244
245
246


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
247
    if user is not None and user.groups.filter(name=__PENDING_ACCOUNT_USER).exists():
248
249
        if tokens.account_activation_token.check_token(user, token):
            user.is_active = True
250
            user.groups.remove(user.groups.get(name=__PENDING_ACCOUNT_USER))
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
            user.save()
            login(request, user)
            # 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'),
                'message': ugettext('Thank you for your email confirmation, you account have been activated '
                                    'and you are now logged in.'),
            })
        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!'),
        })