summaryrefslogtreecommitdiffstats
path: root/src/authentic2_cut/views.py
blob: 1a73bea60824e196d7f9bad961c33481bcf0f4c7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
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
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
# -*- coding: utf-8 -*-
# authentic2_cut - Authentic2 plugin for CUT
# Copyright (C) 2017  Entr'ouvert
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from django.utils.timezone import now
from django.utils.translation import ugettext_lazy as _
from django.contrib import messages
from django.contrib.auth import get_user_model
from django.views.generic.base import TemplateView
from django.core.exceptions import PermissionDenied
from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.db.transaction import atomic

from authentic2.views import EditProfile
from authentic2.manager.views import SimpleSubTableView, BaseTableView, FilterQuerysetByPermMixin
from authentic2.manager.user_views import UserEditView, UserDetailView
from authentic2 import hooks
from authentic2.utils import redirect

from .custom_settings import CORE_ATTRIBUTES
from . import models, forms, tables


class EditCoreView(EditProfile):
    template_names = ['authentic2/cut-edit-core.html']
    fields = [
        'first_name',
        'last_name',
        'title',
        'birthdate',
        'birthplace',
        'birthcountry',
    ]

    @classmethod
    def get_fields(cls, scopes=None):
        fields, labels = super(EditCoreView, cls).get_fields(scopes=scopes)
        return [field for field in fields if field in cls.fields], labels

    def form_valid(self, form):
        response = super(EditCoreView, self).form_valid(form)
        hooks.call_hooks('event', name='cut-edit-core', user=self.request.user, form=form)
        return response

edit_core = EditCoreView.as_view()


class EditCrownView(EditProfile):
    template_names = ['authentic2/cut-edit-crown.html']
    fields = [
        'first_name',
        'last_name',
        'title',
        'birthdate',
        'birthplace',
        'birthcountry',
    ]

    @classmethod
    def get_fields(cls, scopes=None):
        fields, labels = super(EditCrownView, cls).get_fields(scopes=scopes)
        return [field for field in fields if field not in cls.fields], labels

    def form_valid(self, form):
        response = super(EditCrownView, self).form_valid(form)
        hooks.call_hooks('event', name='cut-edit-crown', user=self.request.user, form=form)
        return response

edit_crown = EditCrownView.as_view()


class UserEditCoreView(UserEditView):
    template_name = 'authentic2/cut_manager_user_edit_core.html'
    permissions = ['custom_user.cut_validate_user']

    def get_title(self):
        if self.object.attributes.validated:
            return u'Modifier les attributs cœurs'
        return u'Valider les attributs cœurs'

    def get_fields(self):
        fields = super(UserEditCoreView, self).get_fields()
        return [field for field in CORE_ATTRIBUTES if field in fields]

    def get_form(self, *args, **kwargs):
        form = super(UserEditCoreView, self).get_form(*args, **kwargs)
        for field in form.fields.values():
            field.required = True
        return form

    def form_valid(self, form, context='office', partner=''):
        response = super(UserEditCoreView, self).form_valid(form)
        already_validated = form.instance.attributes.validated
        if form.has_changed() or not already_validated:
            form.instance.attributes.validated = True
            form.instance.attributes.validation_context = context
            form.instance.attributes.validation_date = now().date()
            if not partner and self.request.user.ou:
                partner = self.request.user.ou.slug
            form.instance.attributes.validation_partner = partner
            hooks.call_hooks('event', user=self.request.user, name='manager-cut-validate',
                             instance=form.instance, form=form, context=context, partner=partner)
            if already_validated:
                msg = u'Les données cœur ont été modifiées.'
            else:
                msg = u'Le compte a été validé.'
            messages.info(self.request, msg)
        return response

manager_user_edit_core = UserEditCoreView.as_view()


class ManagerUserDetailView(UserDetailView):
    def get(self, request, *args, **kwargs):
        response = super(ManagerUserDetailView, self).get(request, *args, **kwargs)
        # journalise les accès aux fiches une fois par heure et par session
        t = now()
        key = 'user-looked-%s-%s-%s' % (self.object, t.date(), t.time().hour)
        if key not in request.session:
            request.session[key] = True
            hooks.call_hooks('event', name='manager-view-user', user=request.user,
                             instance=self.object, request=request, **kwargs)
        return response


manager_user_detail = ManagerUserDetailView.as_view()


class UserActionsJournal(SimpleSubTableView):
    model = get_user_model()
    table_class = tables.UserActionsTable
    template_name = 'authentic2/cut_manager_user_actions_journal.html'
    permissions = ['custom_user.view_user']
    filter_table_by_perm = False

    def get_table_queryset(self):
        return self.object.actor_journal.all()

user_actions_journal = UserActionsJournal.as_view()


class UserModificationsJournal(SimpleSubTableView):
    model = get_user_model()
    table_class = tables.UserModificationsTable
    template_name = 'authentic2/cut_manager_user_modifications_journal.html'
    permissions = ['custom_user.view_user']
    filter_table_by_perm = False

    def get_table_queryset(self):
        return self.object.subject_journal.all()

user_modifications_journal = UserModificationsJournal.as_view()


class CGU(TemplateView):
    template_name = 'authentic2/cut_cgu.html'

    def get_context_data(self, **kwargs):
        kwargs['cut_base_url'] = self.request.build_absolute_uri('/')
        return super(CGU, self).get_context_data(**kwargs)

cgu = CGU.as_view()


def next_validation(request):
    if not request.user.is_authenticated() or not request.user.has_perm_any('custom_user.cut_validate_user'):
        raise PermissionDenied
    with atomic():
        validation_request = models.ValidationRequest.objects.next_request(request.user)
    if not validation_request:
        messages.info(request, u'Il n\'y aucune demande de validation en ce moment.')
        return redirect(request, 'a2-manager-homepage')
    return redirect(request, 'cut-manager-user-validation',
                    kwargs={'pk': validation_request.pk})


class Validation(UserEditCoreView):
    template_name = 'authentic2/cut_manager_user_validation.html'
    permissions = ['custom_user.cut_validate_user']

    def get_object(self, queryset=None):
        qs = models.ValidationRequest.objects.all()
        self.validation_request = super(Validation, self).get_object(queryset=qs)
        return self.validation_request.user

    def dispatch(self, request, *args, **kwargs):
        # si la demande en cours a déjà été traitée, on passe à la suivante
        try:
            return super(Validation, self).dispatch(request, *args, **kwargs)
        except Http404:
            return redirect(request, 'cut-manager-user-next-validation')

    def get_context_data(self, **kwargs):
        ctx = super(Validation, self).get_context_data(**kwargs)
        ctx['validation_request'] = self.validation_request
        ctx['attachment_urls'] = [
            reverse('cut-manager-user-validation-attachment', kwargs={'pk': attachment.pk})
            for attachment in self.validation_request.attachments.all()]
        ctx['action'] = u'Valider'
        ctx['validation_form'] = forms.ValidationForm()
        return ctx

    def post(self, request, *args, **kwargs):
        # POST is disabled on already validated requests
        if self.validation_request.validated:
            return self.get(request, *args, **kwargs)

        if 'refuse' in request.POST:
            reason = request.POST.get('reason')
            if not reason:
                messages.error(request, u'Vous devez préciser une raison pour le refus.')
                return HttpResponseRedirect('')
            messages.info(request, u'Demande traitée.')
            self.validation_request.reason = reason
            self.validation_request.status = models.ValidationRequest.STATUS_REFUSED
            self.validation_request.validated = now()
            self.validation_request.validated_by = request.user
            self.validation_request.save()
            return self.next_request(request)
        elif 'validate' in request.POST:
            return super(Validation, self).post(request, *args, **kwargs)
        else:  # next
            return self.next_request(request)

    def next_request(self, request):
        # on ne trouve plus de requête de validation après celle-ci
        # recommençons du début
        with atomic():
            validation_request = models.ValidationRequest.objects.next_request(
                request.user, after=self.validation_request)
        if not validation_request:
            return redirect(request, 'cut-manager-user-next-validation')
        return redirect(request, 'cut-manager-user-validation',
                        kwargs={'pk': validation_request.pk})

    def form_valid(self, form):
        partner = ''
        if hasattr(self.validation_request.origin, 'ou') and self.validation_request.origin.ou:
            partner = self.validation_request.origin.ou.slug
        if not partner and self.request.user.ou:
            partner = self.request.user.ou.slug
        super(UserEditCoreView, self).form_valid(form)
        form.instance.attributes.validated = True
        form.instance.attributes.validation_context = 'online'
        form.instance.attributes.validation_date = now().date()
        form.instance.attributes.validation_partner = partner
        hooks.call_hooks('event', user=self.request.user, name='manager-cut-validate',
                         instance=form.instance, form=form, context='office', partner=partner)
        self.validation_request.status = models.ValidationRequest.STATUS_ACCEPTED
        self.validation_request.validated = now()
        self.validation_request.validated_by = self.request.user
        self.validation_request.save()
        messages.info(self.request, u'Demande traitée.')
        return self.next_request(self.request)

validation = Validation.as_view()


def validation_attachment(request, pk):
    if not request.user.is_authenticated() or not request.user.has_perm_any('custom_user.cut_validate_user'):
        raise PermissionDenied
    attachment = models.ValidationRequestAttachment.objects.get(pk=pk)
    return HttpResponse(attachment.image, content_type='image/jpeg')


class ValidationHomepage(BaseTableView):
    template_name = 'authentic2/cut_manager_user_validations.html'
    model = models.ValidationRequest
    table_class = tables.ValidationTable
    permissions = ['custom_user.cut_validate_user']
    title = _('Validation requests')

    def get_queryset(self):
        qs = super(FilterQuerysetByPermMixin, self).get_queryset()
        if 'all' not in self.request.GET:
            qs = qs.filter(status=models.ValidationRequest.STATUS_RECEIVED)
        qs = qs.prefetch_related('origin').select_related()
        return qs

validation_homepage = ValidationHomepage.as_view()