views.py 10.5 KB
Newer Older
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
1
2
3
4
5
6
7
8
import logging

from django import forms
from django.conf import settings
from django.contrib import messages
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
9
from django.contrib.auth.models import Group
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
10
11
12
from django.core.mail import send_mail
from django.db.models import ProtectedError
from django.forms import widgets
13
from django.http import HttpResponseForbidden
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
14
15
from django.shortcuts import render, redirect
from django.template import TemplateDoesNotExist
16
17
18
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
19
20
from django.utils.translation import ugettext

21
from basetheme_bootstrap import tokens
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
22
from basetheme_bootstrap import user_preferences
23
from basetheme_bootstrap.default_settings import is_validating_email
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
24
25
26
27
28
29
30
31
32
33
34
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
from basetheme_bootstrap.forms import UserCreationFormWithMore, \
    MyUserChangeForm, UserDeleteForm

logger = logging.getLogger(__name__)


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():
62
            auto_active = not is_validating_email()
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
63
64
65
66
            user = form.save()
            if get_user_model().objects.filter(pk__gt=1).count() == 0:
                user.is_superuser = True
                user.is_staff = True
67
68
69
70
71
72
73
74
75
76
77
78
79
80
                user.is_active = True
                Group.objects.get_or_create(name="PendingAccountUser")
            else:
                if not auto_active:
                    g, created = Group.objects.get_or_create(name="PendingAccountUser")
                    user.groups.add(g)
                user.is_active = auto_active
            user.save()

            send_account_created(request, user, auto_active=auto_active)

            if not auto_active:
                return account_is_pending_view(request, email=request.POST['email'])

81
            username = user.username
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
82
83
84
85
86
87
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=username, password=raw_password)
            request.user = user

            login(request, user)
            return redirect('home')
88
89
90
91
92
93
        else:
            user = get_user_model().objects.filter(groups__name="PendingAccountUser",
                                                   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
94
    else:
95
96
        if not request.user.is_anonymous:
            return HttpResponseForbidden()
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
97
98
99
100
        form = UserCreationFormWithMore()
    return render(request, 'registration/signup.html', {'form': form})


101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
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
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={
            'uidb64': urlsafe_base64_encode(force_bytes(user.pk)).decode(),
            '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
152
153
154
155
156
157
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
196
197
198
199
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)
    return render(request, 'registration/small_form_host.html', {
        'title': ugettext('Account deletion'),
        'submit_text': ugettext('Delete account and all related data'),
        'form': form,
        'medium_width': True,
        'btn_classes': 'btn-lg btn-danger text-center',
        'btn_container_classes': 'text-center',
    })


200
@login_required
Bryan  BRANCOTTE's avatar
Bryan BRANCOTTE committed
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
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'
222
223
        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
224
225
226
227
    return render(request, 'registration/account.html', {
        'form_prefs': form_prefs,
        'btn_classes': 'pull-right float-right'
    })
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255


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
    if user is not None and user.groups.filter(name="PendingAccountUser").exists():
        if tokens.account_activation_token.check_token(user, token):
            user.is_active = True
            user.groups.remove(user.groups.get(name="PendingAccountUser"))
            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!'),
        })