Gitlab CSE Unil

views.py 15.2 KB
Newer Older
Julien Furrer's avatar
Julien Furrer committed
1
2
3
# coding=utf-8
from __future__ import unicode_literals

Julien Furrer's avatar
Julien Furrer committed
4
5
import json
import os
6
7
from django.contrib.auth.views import redirect_to_login
from django.views.decorators.csrf import csrf_exempt
8
import ldap
9
10
import logging

Julien Furrer's avatar
Julien Furrer committed
11
from django.conf import settings
12
from django.core.exceptions import PermissionDenied
Julien Furrer's avatar
Julien Furrer committed
13
from django.core.urlresolvers import reverse
14
15
from django.core.cache import cache
from django.db.models import Q
Julien Furrer's avatar
Julien Furrer committed
16
17
from django.http.response import HttpResponse, HttpResponseBadRequest, HttpResponseRedirect, Http404, \
    HttpResponseForbidden
18
from django.shortcuts import render, get_object_or_404, resolve_url
Julien Furrer's avatar
Julien Furrer committed
19
from django.contrib.auth.decorators import login_required
20
from django.contrib.auth.models import User
Julien Furrer's avatar
Julien Furrer committed
21
from django.views.decorators.http import require_POST
22
from django.views.decorators.cache import cache_control
23

24
from adim.models import AnObj, AnObjMembership
25
26
27
from adim.permissions import get_permission_class, has_anobj_access, get_ttp_sharing_mode, SHARING_MODE_NONE
from adim_ttp.decorators import attp_login
from adim_utils.decorators import clear_function_cache
28

Julien Furrer's avatar
Julien Furrer committed
29
30
from .forms import UploadImageFileForm
from sendfile import sendfile
Julien Furrer's avatar
Julien Furrer committed
31
32
from .utils import add_image_border, create_image_thumbnail

Julien Furrer's avatar
Julien Furrer committed
33

34
35
36
logger = logging.getLogger(__name__)


Julien Furrer's avatar
Julien Furrer committed
37
38
39
40
41
42
def home(request):
    """
    Home page
    :param request:
    :return:
    """
M. Chardon's avatar
M. Chardon committed
43
44
45
46
    next = request.GET.get('next', "")
    if request.user.is_anonymous:
        return render(request, "adim/home.html", {'next': next})
    return render(request, "adim/home.html", {})
Julien Furrer's avatar
Julien Furrer committed
47
48
49
50


def handle_404(request):
    if request.user.is_authenticated():
51
        return HttpResponseRedirect(reverse("adim_app:annotate-new"))
Julien Furrer's avatar
Julien Furrer committed
52
    else:
53
        return HttpResponseRedirect(reverse('adim_app:home'))
Julien Furrer's avatar
Julien Furrer committed
54

55
56

@login_required
Julien Furrer's avatar
Julien Furrer committed
57
58
59
60
61
62
def essai(request):
    """
    Page d'essais
    :param request:
    :return:
    """
63
64
65
66
    if settings.DEBUG and request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS:
        return render(request, "adim/essai.html", {})
    else:
        raise Http404()
Julien Furrer's avatar
Julien Furrer committed
67
68
69
70
71
72
73
74
75
76
77
78


@login_required
def _get_anobj(request, anobj_uuid=None, anobj_id=None):
    """
    Returns an AnObj with the uuid or id passed in parameters if
    the request.user has sufficient permissions for it
    Raise a 404 if it cannot return the AnObj

    :param request:
    :param anobj_uuid:
    :return: AnObj
79
    :raise: PermissionDenied
Julien Furrer's avatar
Julien Furrer committed
80
81
82
83
84
85
86
87
88
    """
    q = {}
    if anobj_uuid is not None:
        q['uuid'] = anobj_uuid
    elif anobj_id is not None:
        q['id'] = anobj_id
    if not q:
        raise Http404()
    anobj = get_object_or_404(AnObj, **q)
89
90
91
92

    if not has_anobj_access(request, anobj):
        raise PermissionDenied()

Julien Furrer's avatar
Julien Furrer committed
93
94
95
96
    return anobj


@login_required
97
@cache_control(public=True, max_age=120)
Julien Furrer's avatar
Julien Furrer committed
98
99
100
101
102
103
104
105
def send_anobj_img(request, anobj_uuid):
    try:
        anobj = _get_anobj(request, anobj_uuid=anobj_uuid)
        return sendfile(request, anobj.image.path)
    except Http404:
        return HttpResponseForbidden('Sorry, you cannot access this file')


106
107
108
109
110
111
112
113
@login_required
def anobj_thumb(request, anobj_uuid):
    if request.method == 'GET':
        return send_anobj_thumb(request, anobj_uuid=anobj_uuid)
    elif request.method == 'POST':
        return upload_anobj_thumb(request, anobj_uuid=anobj_uuid)


Julien Furrer's avatar
Julien Furrer committed
114
@login_required
Julien Furrer's avatar
Julien Furrer committed
115
@cache_control(public=True, max_age=1)
Julien Furrer's avatar
Julien Furrer committed
116
117
118
def send_anobj_thumb(request, anobj_uuid):
    try:
        anobj = _get_anobj(request, anobj_uuid=anobj_uuid)
119
        thumb_name = "{name}__{user}.png".format(name=os.path.splitext(anobj.image.name)[0], user=request.user.id)
Julien Furrer's avatar
Julien Furrer committed
120
121
        thumb_path = os.path.join(
            settings.MEDIA_ROOT,
122
            thumb_name
Julien Furrer's avatar
Julien Furrer committed
123
        )
124
125
126
127
128
129
130
131
        # If there is not yet a thumbnail for the current user
        # return the original one
        if not os.path.isfile(thumb_path):
            thumb_name = "{name}__.png".format(name=os.path.splitext(anobj.image.name)[0])
            thumb_path = os.path.join(
                settings.MEDIA_ROOT,
                thumb_name
            )
Julien Furrer's avatar
Julien Furrer committed
132
133
134
135
136
137
138
        return sendfile(request, thumb_path)
    except Http404:
        return HttpResponseForbidden('Sorry, you cannot access this file')


@login_required
def annotate_new(request):
Julien Furrer's avatar
Julien Furrer committed
139
    return render(request, "adim/annotation_new.html", {})
Julien Furrer's avatar
Julien Furrer committed
140
141


142
# @login_required
Julien Furrer's avatar
Julien Furrer committed
143
144
145
146
147
148
149
def annotate(request, anobj_uuid=None):
    """
    Annotation page
    :param request:
    :param anobj_uuid:
    :return:
    """
150
151
152
    # ----- Some preliminary validations
    if anobj_uuid is None or len(anobj_uuid) < 8:
        raise Http404()
Julien Furrer's avatar
Julien Furrer committed
153

154
155
156
157
    try:
        anobj = AnObj.objects.select_related('owner').get(uuid__startswith=anobj_uuid)
    except AnObj.DoesNotExist:
        raise Http404()
158
159
160
161

    # In case of fragmentary uuid, redirect to the url with full uuid
    if len(anobj_uuid) < 32:
        return HttpResponseRedirect(reverse('adim_app:annotate', kwargs={'anobj_uuid': anobj.uuid}))
162

163
    # ----- Login check. Not using decorator so we can delegate to Trusted Third Party if needed
164
    permission = get_permission_class(anobj.sharing_mode)
M. Chardon's avatar
M. Chardon committed
165
    if request.user.is_anonymous:
166
167
        if permission and permission.ttp:
            check_url = settings.ATTP.get(permission.ttp_id, {}).get('CHECK_URL')
168
169
170
171
172
173
174
175
            return HttpResponseRedirect(check_url.format(uuid=anobj.uuid))
        else:
            return redirect_to_login(resolve_url('adim_app:annotate', anobj_uuid=anobj.uuid))

    # ----- Build context
    context = {
        'membership': False
    }
176
177
178
    # is_owner = request.user == anobj.owner
    # is_owner = request.user in anobj.owners.all()
    is_owner = anobj.is_owned(request.user.id)
179

180
    # ----- Detailed check for permissions
181
    membership = None
182
183
    # User is owner and anobj is not shared via Trusted Third Party
    if is_owner and not (permission and permission.ttp):
184
185
        if anobj.sharing_mode != SHARING_MODE_NONE:
            membership, _ = AnObjMembership.objects.get_or_create(anobj=anobj, user=request.user)
186
    # User is guest or owner and anobj shared via TTP
187
    else:
188
        if permission is None:
189
190
191
192
            # AnObj not shared
            raise Http404()
            # raise PermissionDenied()

193
        elif not permission.has_permission(request, anobj):
194
            # AnObj shared but user has no permission yet
195
            if permission.has_interactive_registration:
196
                # Interactive registration exists, call it
197
                return permission.get_interactive_registration_response(request, anobj)
198
            # No interactive registration for this sharing model, deny access
199
200
201
            raise PermissionDenied()

        else:
202
            # AnObj shared, user authorized and registered
203
204
            pass

205
        #  TTP permission may have changed ownership
206
        if permission.ttp:
207
208
209
            clear_function_cache(f='adim.models.annotablesis_owned', args=(anobj, request.user.id))
            is_owner = anobj.is_owned(request.user.id)

210
        membership = AnObjMembership.objects.get(anobj=anobj, user=request.user)
211

212
    # Interactive registration may post credentials, if so redirect to current view with GET method
213
214
215
    if request.method == 'POST':
        return HttpResponseRedirect(reverse('adim_app:annotate', kwargs={'anobj_uuid': anobj_uuid}))

Julien Furrer's avatar
Julien Furrer committed
216
    context.update({
217
        'is_owner': is_owner,
218
        'membership': membership,
Julien Furrer's avatar
Julien Furrer committed
219
220
        'anobj': anobj
    })
221

222
    # ----- Determine if we may display shared annotations
223
    if is_owner:
224
        owner_membership = membership
225
226
    else:
        try:
227
            owner_membership = AnObjMembership.objects.get(anobj=anobj, user=anobj.owner)
228
        except AnObjMembership.DoesNotExist:
229
            owner_membership = None
230

231
232
233
    context.update({'display_shared_annotations':
        (anobj.sharing_mode != SHARING_MODE_NONE) and
        (
234
            anobj.is_owned(request.user.id) or
235
236
            anobj.allow_public_publishing or
            (
237
                owner_membership and owner_membership.publish_mode == 2
238
            )
239
240
        )
    })
241

242
    # ----- Environment specific settings
243
244
    template_path = ['adim']
    if anobj.env:
245
        # select template from adim/env/<env_name>/
246
        template_path.extend(['env', anobj.env])
247
248
249
250
        # add env-settings to the context if it exists
        env_settings = settings.ADIM_ENV.get(anobj.env)
        if env_settings:
            context.update({'env_settings': env_settings})
251
252
253

    template_path.append("annotation.html")
    return render(request, "/".join(template_path), context)
Julien Furrer's avatar
Julien Furrer committed
254
255


256
257
@csrf_exempt
@attp_login
Julien Furrer's avatar
Julien Furrer committed
258
259
260
261
262
263
264
265
266
267
268
269
270
@login_required
def upload_file(request, anobj_uuid=None):
    """
    -- inspired by: https://github.com/miki725/Django-jQuery-File-Uploader-Integration-demo/blob/master/upload/views.py
    :param request:
    :return:
    """
    if request.method != 'POST':
        return HttpResponseBadRequest()

    response_type = "application/json"
    response_data = {}

271
272
    user = request.user  # if request.user.is_authenticated() else moodle_meta.get('user')

Julien Furrer's avatar
Julien Furrer committed
273
274
275
276
277
278
279
280
    form = UploadImageFileForm(request.POST, request.FILES)
    if form.is_valid():
        image_file = request.FILES['image_file']
        file_response = _validate_uploaded_file(image_file)
        response_data.update({
            'error': file_response.get('error'),
            'files': [file_response],
        })
281
        anobj_name = form.cleaned_data['name']
Julien Furrer's avatar
Julien Furrer committed
282
283
284

        # Create AnObj
        if not file_response['error']:
285
286
287
288
289
290
291
292
            anobj = None
            if anobj_uuid:
                try:
                    anobj = _get_anobj(request, anobj_uuid=anobj_uuid)
                except Http404:
                    anobj = None

            if anobj:
Julien Furrer's avatar
Julien Furrer committed
293
                anobj.image = image_file
294
295
                if anobj_name:
                    anobj.name = anobj_name
Julien Furrer's avatar
Julien Furrer committed
296
                anobj.save()
297
            else:
Julien Furrer's avatar
Julien Furrer committed
298
                anobj = AnObj.objects.create(
299
300
                    owner=user,
                    name=anobj_name or os.path.splitext(image_file.name)[0],
Julien Furrer's avatar
Julien Furrer committed
301
302
                    image=image_file
                )
Julien Furrer's avatar
Julien Furrer committed
303

304
305
306
307
308
            if hasattr(request, 'attp_message'):
                ttp_id = request.attp_message.get('attp_id')
                sharing_mode = get_ttp_sharing_mode(ttp_id=ttp_id)
                if sharing_mode:
                    anobj.sharing_mode = sharing_mode
309
                    sharing_opts = request.attp_message.get('sharing_opts')
310
311
312
313
                    if sharing_opts:
                        anobj.sharing_opts = sharing_opts
                    anobj.save()

314
            # Create original thumbnail, returned to user who has not yet annotated
Julien Furrer's avatar
Julien Furrer committed
315
            create_image_thumbnail(anobj.image.path)
316
            response_data['next'] = reverse('adim_app:annotate', kwargs={'anobj_uuid': anobj.uuid})
317
            response_data['uuid'] = anobj.uuid
Julien Furrer's avatar
Julien Furrer committed
318
319
320
321
322
323
324

        # Needed when using iFrame transport
        if "text/html" in request.META["HTTP_ACCEPT"]:
            response_type = "text/html"
    else:
        response_data['error'] = "invalid"

325
    if 'application/json' in request.META.get('HTTP_ACCEPT', ''):
Julien Furrer's avatar
Julien Furrer committed
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
        return HttpResponse(json.dumps(response_data), content_type=response_type)
    else:
        return HttpResponseRedirect(response_data['next'])
    

def _validate_uploaded_file(image_file):
    options = {
        # the maximum file size (must be in bytes)
        "maxfilesize": settings.ADIM_UPLOAD_MAX_FILESIZE * 2 ** 20,  # 2 Mb
        # the file types which are going to be allowed for upload
        # must be a mimetype
        "acceptedformats": (
            "image/jpeg",
            "image/jpg",
            "image/png",
        )
    }

    error_id = False
    if image_file.size > options["maxfilesize"]:
        error_id = "maxFileSize"
    # allowed file type
    if image_file.content_type not in options["acceptedformats"]:
        error_id = "acceptFileTypes"

    response_data = {
        "name": image_file.name,
        "size": image_file.size,
        "type": image_file.content_type,
        "error": error_id,
    }

    return response_data


@login_required
@require_POST
363
364
365
366
367
368
369
370
371
def upload_anobj_thumb(request, anobj_uuid=None):
    if anobj_uuid:
        anobj = _get_anobj(request, anobj_uuid=anobj_uuid)
    else:
        try:
            anobj_id = int(request.POST.get('aid'))
            anobj = _get_anobj(request, anobj_id=anobj_id)
        except TypeError:
            return HttpResponseBadRequest()
Julien Furrer's avatar
Julien Furrer committed
372

373
374
    thumb_name = "{name}__{user}.png".format(name=os.path.splitext(anobj.image.name)[0], user=request.user.id)
    # thumb_name = "{name}__.png".format(name=os.path.splitext(anobj.image.name)[0])
Julien Furrer's avatar
Julien Furrer committed
375
    thumb_path = os.path.join(settings.MEDIA_ROOT, thumb_name)
376

Julien Furrer's avatar
Julien Furrer committed
377
    # thumb_url = reverse('adim.app:ao_thumb', kwargs={'anobj_uuid': anobj.uuid})
Julien Furrer's avatar
Julien Furrer committed
378
379
380
381
382
383
384
385
386
387

    thumb_file = request.FILES['file']
    response_data = _validate_uploaded_file(thumb_file)
    if response_data['error']:
        return HttpResponseBadRequest()

    with open(thumb_path, 'wb+') as destination:
        for chunk in thumb_file.chunks():
            destination.write(chunk)

Julien Furrer's avatar
Julien Furrer committed
388
389
    add_image_border(thumb_path, save=True)
    return HttpResponse()
Julien Furrer's avatar
Julien Furrer committed
390
391
392
393
394
395
396


def _handle_uploaded_file(image_file, destination):
    destination_path = os.path.join(settings.MEDIA_ROOT, destination, image_file.name)
    with open(destination_path, 'wb+') as destination:
        for chunk in image_file.chunks():
            destination.write(chunk)
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416


@login_required
def suggest_users(request):
    """
    Return a list of usernames that match a query passed in as a query string
    This is the end point for the Bloodhound suggestion engine used for user suggestion
    while adding users to a shared AnObj
    :param request:
    :return:
    """
    query_str = request.GET.get('q', "")
    # tokens = filter(bool, re.compile("\W+").split(query_str))  ## Use this for nonword limit instead of whitespace
    tokens = query_str.split()
    matching_users = []
    usernames = []

    if not tokens:
        return HttpResponse(content=json.dumps(matching_users), content_type="application/json")

Julien Furrer's avatar
Julien Furrer committed
417
    # -- Search for local users
418
419
420
421
422
423
424
425
    q = Q()
    for token in tokens:
        q = q & Q(username__icontains=token)

    for user in User.objects.filter(q):
        matching_users.append({'username': user.username, 'id': user.id})
        usernames.append(user.username)

Julien Furrer's avatar
Julien Furrer committed
426
    # -- Search for ldap users
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
    if len(matching_users) < settings.ADIM_SUGGESTION['LIMIT']:
        cache_key = "ldapusers_" + "_".join(tokens)
        ldap_users = cache.get(cache_key)

        if ldap_users is None:
            filter_str = "(mail=*{}*)".format("*".join(tokens))
            print "\n{h} HIT LDAP: {q} {h}\n".format(h="#" * 30, q=filter_str)

            ldap_object = ldap.initialize(settings.ADIM_SUGGESTION['LDAP']['URL'])
            try:
                results = ldap_object.search_st(
                    base=settings.ADIM_SUGGESTION['LDAP']['BASE'],
                    scope=ldap.SCOPE_SUBTREE,
                    filterstr=filter_str,
                    attrlist=(str("mail"),),
                    timeout=settings.ADIM_SUGGESTION['LDAP']['TIMEOUT']
                )
            except ldap.TIMEOUT:
                results = []
            ldap_users = map(lambda r: r[1].get('mail', [""])[0], results)

            # ldap_users = [
            #     "Julien.Furrer@unil.ch",
            #     "Julien.Furrer.1@unil.ch",
            #     "Julien.Furrer.2@unil.ch",
            # ]

            cache.set(cache_key, ldap_users, 3600 * 24)

        matching_users += [
            {'username': user}
            for user in ldap_users if user not in usernames
        ]

    return HttpResponse(content=json.dumps(matching_users), content_type="application/json")