views.py 41.1 KB
Newer Older
BERJON Matthieu's avatar
BERJON Matthieu committed
1
2
3
4
5
6
7
8
9
10
11
# -*- coding: utf-8 -*-
"""Main view module

This module handles most of the front-end for the Allgo system. You'll find
all the logic (controller) in an MVC pattern.

Attributes:
    log: module level variable to save information as a log data.

"""
# Python standard libraries
12
import glob
BERJON Matthieu's avatar
BERJON Matthieu committed
13
import io
14
15
16
import json
import logging
import os
17
import shutil
18
import tempfile
19
import zipfile
20

CAMPION Sebastien's avatar
pep8    
CAMPION Sebastien committed
21
import natsort
BERJON Matthieu's avatar
BERJON Matthieu committed
22
# Third party imports
23
from django.conf import settings
24
from django.contrib import messages
25
from django.contrib.auth.forms import PasswordChangeForm
26
from django.contrib.auth.mixins import LoginRequiredMixin
BERJON Matthieu's avatar
BERJON Matthieu committed
27
from django.contrib.auth.models import User
28
from django.contrib.messages.views import SuccessMessageMixin
29
from django.core.exceptions import ObjectDoesNotExist
CAMPION Sebastien's avatar
CAMPION Sebastien committed
30
from django.core.urlresolvers import reverse
31
from django.db import transaction
BERJON Matthieu's avatar
BERJON Matthieu committed
32
from django.db.models import Count
33
from django.http import HttpResponse, JsonResponse, HttpResponseRedirect, FileResponse
BERJON Matthieu's avatar
BERJON Matthieu committed
34
from django.shortcuts import render, get_object_or_404, redirect
35
from django.urls import reverse, reverse_lazy
36
from django.utils.crypto import get_random_string
37
from django.utils.text import slugify
38
from django.views.decorators.csrf import csrf_exempt
BERJON Matthieu's avatar
BERJON Matthieu committed
39
from django.views.generic import (
CAMPION Sebastien's avatar
pep8    
CAMPION Sebastien committed
40
41
42
43
44
45
46
47
    CreateView,
    DeleteView,
    DetailView,
    ListView,
    RedirectView,
    TemplateView,
    UpdateView,
    View,
BERJON Matthieu's avatar
BERJON Matthieu committed
48
)
49
from django.views.generic.detail import SingleObjectMixin
BERJON Matthieu's avatar
BERJON Matthieu committed
50
from taggit.models import Tag
BERJON Matthieu's avatar
BERJON Matthieu committed
51

BERJON Matthieu's avatar
BERJON Matthieu committed
52
from .forms import (
CAMPION Sebastien's avatar
cosmit    
CAMPION Sebastien committed
53
54
55
56
57
58
    UserForm,
    HomeSignupForm,
    UserWebappForm,
    JobForm,
    SSHForm,
    RunnerForm,
59
60
    WebappForm,
    WebappSandboxForm,
CAMPION Sebastien's avatar
cosmit    
CAMPION Sebastien committed
61
)
CAMPION Sebastien's avatar
pep8    
CAMPION Sebastien committed
62
# Local imports
BAIRE Anthony's avatar
BAIRE Anthony committed
63
import config
64
from .helpers import get_base_url, get_ssh_data, upload_data, notify_controller, lookup_job_file
CAMPION Sebastien's avatar
pep8    
CAMPION Sebastien committed
65
66
67
from .mixins import GroupRequiredMixin
from .models import (
    AllgoUser,
68
    DockerOs,
CAMPION Sebastien's avatar
pep8    
CAMPION Sebastien committed
69
70
71
72
73
74
    Job,
    Quota,
    Runner,
    Webapp,
    WebappVersion,
)
BAIRE Anthony's avatar
BAIRE Anthony committed
75
from .signals import job_post_save
76
from .templatetags.converters import status_icon
BERJON Matthieu's avatar
BERJON Matthieu committed
77

BERJON Matthieu's avatar
BERJON Matthieu committed
78
# Start logger
79
log = logging.getLogger('allgo')
CAMPION Sebastien's avatar
CAMPION Sebastien committed
80

CAMPION Sebastien's avatar
CAMPION Sebastien committed
81

BERJON Matthieu's avatar
BERJON Matthieu committed
82
83
84
85
86
87
88
89
90
91
class IndexDetail(TemplateView):
    """Home view

    Generate the home as a standard `TemplateView` by calling a specific
    template. Most of the data are handled in the template itself, only few
    contexte data are provided for specific use.

    Attributes:
        template_name:  filename of the template used.

92
    """
BERJON Matthieu's avatar
BERJON Matthieu committed
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
    template_name = 'home.html'

    def get_context_data(self, **kwargs):
        """ Generate specific data to pass on in the context of the template.

        Returns:
            user_nb (int): number of users recorded in the database.
            webapp_nb (int): number of webapps recorded in the database.
            job_nb (int): number of jobs recorded in the database.
            signup_form: form specific for signin-up directly on the home page.
        """
        context = super(IndexDetail, self).get_context_data(**kwargs)
        users = User.objects.all().count()
        webapps = Webapp.objects.all().count()
        jobs = Job.objects.all().count()

        context['user_nb'] = users
        context['webapp_nb'] = webapps
        context['job_nb'] = jobs
        context['signup_form'] = HomeSignupForm()

        return context
BERJON Matthieu's avatar
BERJON Matthieu committed
115
116


BAIRE Anthony's avatar
BAIRE Anthony committed
117
118
119
120
121
122
123
124
125
# Legacy views
class LegacyWebappDetail(SingleObjectMixin, RedirectView):
    model = Webapp
    permanent = True
    slug_field = "docker_name"
    def get_redirect_url(self, **kwargs):
        return reverse("main:webapp_detail",
                args=(self.get_object().docker_name,))

126
127
# WEBAPPS
# -----------------------------------------------------------------------------
128
class WebappList(ListView):
BERJON Matthieu's avatar
BERJON Matthieu committed
129
    """ Display a paginated list of available webapps.
130

BERJON Matthieu's avatar
BERJON Matthieu committed
131
132
    The webapps are filtered from the most recent to the oldest and no private
    apps are displayed.
133

BERJON Matthieu's avatar
BERJON Matthieu committed
134
135
136
137
138
139
140
    Attributes:
        model:  Webapp model is used.
        context_object_name:    the name used in the template to display each
                                variable.
        paginate_by: the number of occurences per page
        template_name: name of the template loaded with this view.
        queryset: a specific queryset designed to filter the data.
141

BERJON Matthieu's avatar
BERJON Matthieu committed
142
143
144
    Todo:
        - the number of occurences per page could be loaded from the config
        file.
145
146

    """
BERJON Matthieu's avatar
BERJON Matthieu committed
147
    model = Webapp
BERJON Matthieu's avatar
BERJON Matthieu committed
148
    context_object_name = 'webapps'
BERJON Matthieu's avatar
BERJON Matthieu committed
149
150
    paginate_by = 10
    template_name = 'webapp_list.html'
151
    queryset = Webapp.objects.filter(private=0).order_by('-created_at')
152

BERJON Matthieu's avatar
BERJON Matthieu committed
153

BERJON Matthieu's avatar
BERJON Matthieu committed
154
class UserWebappList(ListView):
BERJON Matthieu's avatar
BERJON Matthieu committed
155
156
157
158
159
160
161
162
163
164
165
166
167
    """List of user's webapp

    Returns all the webapps owned by a specific user. Only the user can its
    apps.

    Attributes:
        model: database model
        context_object_name: variable name used in the template to display the
                            data.
        paginate_by: number of occurences by page.
        template_name: template filename.
                            
    """
BERJON Matthieu's avatar
BERJON Matthieu committed
168
169
170
171
172
173
174
175
176
177
178
179
180
    model = Webapp
    context_object_name = 'webapps'
    paginate_by = 10
    template_name = 'webapp_list.html'

    def get_queryset(self):
        """Filter apps for a given user"""
        user = User.objects.get(username=self.kwargs['username'])
        queryset = Webapp.objects.filter(user=user)
        return queryset


class WebappUpdate(SuccessMessageMixin, LoginRequiredMixin, UpdateView):
BERJON Matthieu's avatar
BERJON Matthieu committed
181
182
183
184
185
186
187
188
    """Form to update the webapp data

    Attributes:
        form_class: form object.
        template_name: template filename.
        success_message: message when the form is properly submitted.

    """
BERJON Matthieu's avatar
BERJON Matthieu committed
189
    form_class = UserWebappForm
190
    template_name = 'webapp_update.html'
BERJON Matthieu's avatar
BERJON Matthieu committed
191
    success_message = 'Your app has been successfully updated.'
192
    error_message = 'The email doesn\'t belong to any registered user. Please enter a valid owner email address.'
BERJON Matthieu's avatar
BERJON Matthieu committed
193
194

    def get_success_url(self):
BERJON Matthieu's avatar
BERJON Matthieu committed
195
        """If successful redirect to the same page"""
BERJON Matthieu's avatar
BERJON Matthieu committed
196
197
198
        return reverse('main:webapp_update', args=(self.object.docker_name,))

    def get_object(self):
BERJON Matthieu's avatar
BERJON Matthieu committed
199
        """Returns the object according to its docker name or a 404 error"""
BERJON Matthieu's avatar
BERJON Matthieu committed
200
201
202
203
        data = self.kwargs.get('docker_name', None)
        queryset = get_object_or_404(Webapp, docker_name=data, user_id=self.request.user.id)
        return queryset

204
205
206
207
208
209
    def get_form(self):
        form = super().get_form()
        if not self.request.user.is_superuser:
            form.fields['memory_limit_mb'].widget.attrs['readonly'] = True
        return form

BERJON Matthieu's avatar
BERJON Matthieu committed
210
    def form_valid(self, form):
BERJON Matthieu's avatar
BERJON Matthieu committed
211
        """Save data coming from the form in the database """
BERJON Matthieu's avatar
BERJON Matthieu committed
212
213
214
215
        obj = form.save(commit=False)
        try:
            user = User.objects.get(username=form.cleaned_data['owner'])
            obj.user_id = user.id
216
            obj.memory_limit = form.get_memory_limit(self.request)
BERJON Matthieu's avatar
BERJON Matthieu committed
217
            form.save()
BERJON Matthieu's avatar
BERJON Matthieu committed
218
219
            # Add the tag to the database (specific because it's a many to 
            # many relationship)
220
            form.save_m2m()
BERJON Matthieu's avatar
BERJON Matthieu committed
221
            if user != self.request.user:
222
                messages.success(self.request, self.success_message)
BERJON Matthieu's avatar
BERJON Matthieu committed
223
224
225
226
                return redirect('main:user_webapp_list', self.request.user.username)
            else:
                return super(WebappUpdate, self).form_valid(form)
        except User.DoesNotExist:
227
            messages.error(self.request, self.error_message)
BERJON Matthieu's avatar
BERJON Matthieu committed
228
229
230
            return super(WebappUpdate, self).form_invalid(form)


231
class WebappCreate(SuccessMessageMixin, LoginRequiredMixin, GroupRequiredMixin, CreateView):
BERJON Matthieu's avatar
BERJON Matthieu committed
232
233
234
235
236
237
238
239
240
241
    """Create a new webapp

    Attributes:
        model: model to use in this class.
        form_class: form object passed to the template.
        success_message: successfull message sent to the template
        template_name: template filename.
        group_required: groups that user must belong to.

    """
242
243
244
    model = Webapp
    form_class = WebappForm
    success_message = 'Webapp created successfully.'
245
    template_name = 'webapp_add.html'
246
    group_required = ['inria', ]
247
248

    def get_success_url(self):
BERJON Matthieu's avatar
BERJON Matthieu committed
249
        """If successful redirect to the webapp list page"""
250
        return reverse('main:webapp_sandbox_panel', args=(self.webapp.docker_name,))
251

252
253
254
255
256
257
    def get_form(self):
        form = super().get_form()
        if not self.request.user.is_superuser:
            form.fields['memory_limit_mb'].widget.attrs['readonly'] = True
        return form

258
    def form_valid(self, form):
BERJON Matthieu's avatar
BERJON Matthieu committed
259
        """Save data coming from the form in the database """
260
261
262
263
        obj = form.save(commit=False)
        obj.user_id = self.request.user.id
        if not form.cleaned_data['contact']:
            obj.contact = self.request.user.email
264
        obj.sandbox_state = Webapp.IDLE
265
266
267
        # Ensure that all specials characters are removed, spaces are replaced
        # by hyphens and everything is lower-cased
        obj.docker_name = slugify(form.cleaned_data['name'])
268
        obj.memory_limit = form.get_memory_limit(self.request)
269
270
271
272
273
274
275
276
277
278

        # validate the Webapp record before saving
        # (this is a safety measure, do not remove)
        # FIXME: currently this raises an exception if the slugify-generated
        #        docker_name does not comply with the model constraints
        #        (for example: 'root' and 'sshd' are reserved names)
        #        To solve this, i think we should let the user choose the
        #        docker_name
        obj.full_clean()

279
280
281
282
        obj.save()

        # set up the docker container for the app
        Quota.objects.create(user=self.request.user, webapp=obj)
283
284
285
286
        # pass on the webapp data to get_successful_url to redirect with the
        # correct arguments (for instance the docker_name)
        self.webapp = obj
        return super().form_valid(form)
BERJON Matthieu's avatar
BERJON Matthieu committed
287
288


289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
class WebappJson(LoginRequiredMixin, DetailView):
    """json variant of the application details
    
    (used by the /aio/apps/<DOCKER_NAME>/events endpoint)
    """

    def get_object(self):
        """Returns the object according to its docker name or a 404 error"""
        data = self.kwargs.get('docker_name', None)
        queryset = get_object_or_404(Webapp, docker_name=data)
        return queryset

    def render_to_response(self, context, **kwargs):
        webapp = context["webapp"]
        return JsonResponse({
            "id":               webapp.id,
            "sandbox_state":    webapp.get_sandbox_state_display(),
            })

308
class WebappSandboxPanel(LoginRequiredMixin, TemplateView):
BERJON Matthieu's avatar
BERJON Matthieu committed
309
310
311
312
313
314
315
316
    """Create a new sandbox for a given application

    Attributes:
        form_class: form object to pass on the template.
        model: model to use in this class
        template_name: template filename

    """
317
    template_name = 'webapp_sandbox_panel.html'
318
319

    def get_object(self):
BERJON Matthieu's avatar
BERJON Matthieu committed
320
        """Returns the object according to its docker name or a 404 error"""
321
        data = self.kwargs.get('docker_name', None)
322
        queryset = get_object_or_404(Webapp, docker_name=data, user_id=self.request.user.id)
323
324
325
        return queryset

    def get_context_data(self, **kwargs):
BERJON Matthieu's avatar
BERJON Matthieu committed
326
327
328
329
330
331
332
        """Recover data to pass on to the template context
        
        In order to give the user a feedback regarding the way to push its image
        to the registry, we need to pass both the webapp `docker_name` and the
        `registry` URL.

        """
333
        context = super().get_context_data(**kwargs)
334
        context['webapp'] = self.get_object()
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349

        context["ssh_command"] = "ssh%s %s@%s" % (
                (" -p %s" % config.env.ALLGO_SSH_PORT
                    if config.env.ALLGO_SSH_PORT != "22" else ""),
                (kwargs["docker_name"]),
                (config.env.ALLGO_SSH_HOST))

        # candidate docker os (start from scratch)
        context['docker_os_list'] = DockerOs.objects.all()

        # candidate versions (start from an existing version)
        versions = {}
        for state in (WebappVersion.READY, WebappVersion.COMMITTED):
            versions.update((v.number, v) for v in WebappVersion.objects.filter(
                webapp=context["webapp"], state=state))
350
351
        context['versions'] = natsort.versorted(versions.values(), key=lambda v: v.number)
        context['versions'].reverse()
352
353
        return context

354
355
356
    def post(self, request, *, docker_name):
        log.info("POST %r", request.POST)

357
        webapp = self.get_object()
358
359
        action = request.POST["action"]

BAIRE Anthony's avatar
BAIRE Anthony committed
360
361
362
363
364
        def stop_sandbox():
            webapp.sandbox_state = Webapp.STOPPING
            webapp.sandbox_version_id = None
            webapp.save()

365
366
        log.info("action %r", request.POST["action"])
        if action == "start":
BAIRE Anthony's avatar
BAIRE Anthony committed
367
368
369
370
371
            if webapp.sandbox_state != Webapp.IDLE:
                messages.error(request,
                        "unable to start sandbox %r because it not idle"
                        % webapp.name)
            else:
372
373
374
375
376
377
378
379
380
                if "webapp_version_id" in request.POST:
                    # start from an existing version
                    webapp.sandbox_version_id = int(request.POST["webapp_version_id"])
                else:
                    # start from scratch
                    webapp.docker_os_id = request.POST["docker_os_id"]
                    webapp.sandbox_version = None
                webapp.sandbox_state = Webapp.STARTING
                webapp.save()
BAIRE Anthony's avatar
BAIRE Anthony committed
381
                messages.success(request, "starting sandbox %r" % webapp.name)
382
383

        elif action == "commit":
BAIRE Anthony's avatar
BAIRE Anthony committed
384
385
386
387
388
            if webapp.sandbox_state != Webapp.RUNNING:
                messages.error(request,
                        "unable to commit sandbox %r because it is not running"
                        % webapp.name)
            else:
389
390
391
392
393
                # query previous active versions of this webapp
                previous = WebappVersion.objects.filter(webapp=webapp,
                            state__in = (WebappVersion.READY, WebappVersion.COMMITTED))
                extra = {}

394
395
                if request.POST["version-action"] == "replace-version":
                    number = request.POST["version-select"]
396
397
                    # keep the previous 'created_at' timestamp when replacing an image
                    extra["created_at"] = getattr(previous.filter(number=number).first(), "created_at")
398
399
                else:
                    number = request.POST["version-new"]
400
401
402

                    # ensure that this version number does not already exist
                    if previous.filter(number=number).exists():
403
404
405
                        messages.error(request, "unable to commit because version %r already exists"
                                " (if you want to overwrite this version, then use"
                                "  'replace version' instead)" % number)
BAIRE Anthony's avatar
BAIRE Anthony committed
406
                        return HttpResponseRedirect(request.path_info)
407

408
409
                WebappVersion.objects.create(
                        webapp=webapp,
410
                        number=number,
411
412
                        state=WebappVersion.SANDBOX,
                        published=True,
413
                        description=request.POST["description"],
414
                        **extra)
BAIRE Anthony's avatar
BAIRE Anthony committed
415
                stop_sandbox()
416

BAIRE Anthony's avatar
BAIRE Anthony committed
417
418
                messages.success(request, "committing sandbox %r version %r"
                        % (webapp.name, number))
419

420
421
        elif action == "rollback":
            if webapp.sandbox_state == Webapp.RUNNING:
BAIRE Anthony's avatar
BAIRE Anthony committed
422
                stop_sandbox()
BAIRE Anthony's avatar
BAIRE Anthony committed
423
424
425
426
                messages.success(request, "rolling back sandbox %r" % webapp.name)
            else:
                messages.error(request, "unable to roll back, sandbox %r is not running"
                        % webapp.name)
427
428
429

        elif action == "abort":
            if webapp.sandbox_state == Webapp.START_ERROR:
BAIRE Anthony's avatar
BAIRE Anthony committed
430
                stop_sandbox()
BAIRE Anthony's avatar
BAIRE Anthony committed
431
                messages.success(request, "reset sandbox %r" % webapp.name)
432
433
434
435
436

        elif action == "retry":
            if webapp.sandbox_state == Webapp.START_ERROR:
                webapp.sandbox_state = Webapp.STARTING
                webapp.save()
BAIRE Anthony's avatar
BAIRE Anthony committed
437
                messages.success(request, "starting sandbox %r" % webapp.name)
438
            elif webapp.sandbox_state == Webapp.STOP_ERROR:
BAIRE Anthony's avatar
BAIRE Anthony committed
439
                stop_sandbox()
BAIRE Anthony's avatar
BAIRE Anthony committed
440
                messages.success(request, "stopping sandbox %r" % webapp.name)
441

BAIRE Anthony's avatar
BAIRE Anthony committed
442
443
        log.debug("new sandbox state: %r -> %r",
                webapp.docker_name, webapp.sandbox_state)
444

BAIRE Anthony's avatar
BAIRE Anthony committed
445
446
447
448
449
        # NOTE: we return a 302 redirect to the same page (instead of rendering
        # it directly) to force the browser to make a separate GET request.
        # This prevent reexecuting the POST request if the user refreshes the
        # page.
        return HttpResponseRedirect(request.path_info)
450

451
452
453
454
455
456
457
458
459
460
461
462
# TAGS
# -----------------------------------------------------------------------------

class TagList(ListView):
    """List all available tag along with their number of occurences

    Attributes:
        model: database model
        context_object_name: variable name used in the template to display the
                            data.
        template_name: template filename.
    """
BERJON Matthieu's avatar
BERJON Matthieu committed
463
    model = Tag
464
465
466
467
468
    context_object_name = 'tags'
    template_name = 'tag_list.html'

    def get_queryset(self):
        """Return all available tags
BERJON Matthieu's avatar
BERJON Matthieu committed
469

470
471
        Each tag return as well the number of webapps attached to it
        """
BERJON Matthieu's avatar
BERJON Matthieu committed
472
        tags = Tag.objects.annotate(num_tag=Count('taggit_taggeditem_items'))
473
474
475
476
477
478
479
480
481
482
483
484
485
        return tags


class TagWebappList(ListView):
    """List all available webapps for a given tag

    Attributes:
        model: database model
        context_object_name: variable name used in the template to display the
                            data.
        paginated_by: number of occurences per page.
        template_name: template filename.
    """
BERJON Matthieu's avatar
BERJON Matthieu committed
486
    model = Webapp
487
488
489
490
491
    context_object_name = 'webapps'
    paginated_by = 10
    template_name = 'tag_webapp_list.html'

    def get_queryset(self):
BERJON Matthieu's avatar
BERJON Matthieu committed
492
        return Webapp.objects.filter(tags__slug=self.kwargs['slug'])
493

494
495
496
    def get_context_data(self, **kwargs):
        return super().get_context_data(tag=self.kwargs["slug"], **kwargs)

497

498
499
500
# PROFILE
# -----------------------------------------------------------------------------
class UserUpdate(SuccessMessageMixin, LoginRequiredMixin, UpdateView):
BERJON Matthieu's avatar
BERJON Matthieu committed
501
502
503
504
505
506
507
    """Update the user profile

    Attributes:
        form_class: form object to pass on the template.
        template_name: template filename
        success_message: successfull message sent to the template
    """
508
    form_class = UserForm
509
    template_name = "user_update.html"
510
511
512
    success_message = 'Profile updated successfully.'

    def get_success_url(self):
BERJON Matthieu's avatar
BERJON Matthieu committed
513
        """If successful redirect to the user page"""
514
515
516
        return reverse('main:user_detail')

    def get_object(self):
BERJON Matthieu's avatar
BERJON Matthieu committed
517
        """Only get the User record for the user making the request"""
518
519
520
        return User.objects.get(username=self.request.user.username)

    def get_context_data(self, **kwargs):
BERJON Matthieu's avatar
BERJON Matthieu committed
521
522
523
524
525
526
527
        """Recover data to pass on to the template

        In order to display specific data, I process the SSH key to get its
        fingerprint and comment. Both the SSH key, fingerprint, comment and
        token to context template.

        """
528
529
530
531
532
        queryset = AllgoUser.objects.get(user_id=self.request.user.id)
        key = queryset.sshkey
        token = queryset.token
        if key:
            fingerprint, comment = get_ssh_data(key)
BERJON Matthieu's avatar
BERJON Matthieu committed
533
            kwargs['sshkey'] = True
534
535
536
537
538
539
540
541
            kwargs['ssh_comment'] = comment
            kwargs['ssh_fingerprint'] = fingerprint
        if token:
            kwargs['token'] = token
        return super(UserUpdate, self).get_context_data(**kwargs)


class UserToken(LoginRequiredMixin, RedirectView):
BERJON Matthieu's avatar
BERJON Matthieu committed
542
    """Regenerate the user token"""
543

544
545
    success_message = 'Token generated successfully.'

546
    def dispatch(self, request, *args, **kwargs):
BERJON Matthieu's avatar
BERJON Matthieu committed
547
        """Generate the token and save it into the database"""
548
549
550
551
552
553
        queryset = AllgoUser.objects.get(user_id=self.request.user.id)
        queryset.token = get_random_string(length=32)
        queryset.save()
        return super(UserToken, self).dispatch(request, *args, **kwargs)

    def get_redirect_url(self, *args, **kwargs):
BERJON Matthieu's avatar
BERJON Matthieu committed
554
        """Redirect the user to the user page and display a successful message"""
555
        messages.success(self.request, self.success_message)
556
557
        return reverse('main:user_detail')

BERJON Matthieu's avatar
BERJON Matthieu committed
558
559

class UserSSHAdd(SuccessMessageMixin, LoginRequiredMixin, UpdateView):
BERJON Matthieu's avatar
BERJON Matthieu committed
560
561
562
563
564
565
566
    """Save a SSH key to the database.
    
    Attributes:
        form_class: form object to pass on the template.
        template_name: template filename
        success_message: successfull message sent to the template
    """
BERJON Matthieu's avatar
BERJON Matthieu committed
567
    form_class = SSHForm
568
    template_name = 'user_ssh_add.html'
BERJON Matthieu's avatar
BERJON Matthieu committed
569
570
571
    success_message = 'SSH key added successfully.'

    def get_success_url(self):
BERJON Matthieu's avatar
BERJON Matthieu committed
572
        """If successful redirect to the user page"""
BERJON Matthieu's avatar
BERJON Matthieu committed
573
574
575
        return reverse('main:user_detail')

    def get_object(self):
BERJON Matthieu's avatar
BERJON Matthieu committed
576
        """Only get the User record for the user making the request"""
BERJON Matthieu's avatar
BERJON Matthieu committed
577
        return AllgoUser.objects.get(user_id=self.request.user.id)
578
579
580


class UserSSHDelete(LoginRequiredMixin, RedirectView):
BERJON Matthieu's avatar
BERJON Matthieu committed
581
    """Delete the user SSH key"""
582

583
584
    success_message = 'The SSH key has been successfully deleted.'

585
    def dispatch(self, request, *args, **kwargs):
BERJON Matthieu's avatar
BERJON Matthieu committed
586
        """Generate an empty SSH key and save it into the database"""
587
588
589
590
591
592
        queryset = AllgoUser.objects.get(user_id=request.user.id)
        queryset.sshkey = ''
        queryset.save()
        return super(UserSSHDelete, self).dispatch(request, *args, **kwargs)

    def get_redirect_url(self, *args, **kwargs):
BERJON Matthieu's avatar
BERJON Matthieu committed
593
        """If successful redirect to the user page"""
594
        messages.success(self.request, self.success_message)
595
596
597
        return reverse('main:user_detail')


598
class UserPasswordUpdate(SuccessMessageMixin, LoginRequiredMixin, UpdateView):
BERJON Matthieu's avatar
BERJON Matthieu committed
599
    """Update the user's password.
600
601
602

    We reuse the Django password form system in order to keep something robust
    even if it dedicates a specific view for it.
BERJON Matthieu's avatar
BERJON Matthieu committed
603
604
605
606
607
608

    Attributes:
        success_url: URL or handle where the user will be redirected.
        form_class: form object to pass on the template.
        template_name: template filename
        success_message: successfull message sent to the template
609
610
611
    """
    success_url = reverse_lazy('main:user_detail')
    form_class = PasswordChangeForm
612
    template_name = "user_password_update.html"
613
614
615
    success_message = 'Password updated successfully.'

    def get_object(self, queryset=None):
BERJON Matthieu's avatar
BERJON Matthieu committed
616
617
618
619
620
        """Return the user data
        
        Todo:
            - Not sure the relevance of getting this information to the template
        """
621
622
623
        return self.request.user

    def get_form_kwargs(self):
BERJON Matthieu's avatar
BERJON Matthieu committed
624
        """Return the arguments related to the user"""
625
626
627
628
629
        kwargs = super(UserPasswordUpdate, self).get_form_kwargs()
        kwargs['user'] = kwargs.pop('instance')
        return kwargs

    def dispatch(self, request, *args, **kwargs):
BERJON Matthieu's avatar
BERJON Matthieu committed
630
631
632
633
634
635
        """
        Todo:
            - I'm not sure why I wrote that and why it is useful in the present
              case. It needs to be investigated.

        """
636
637
        return super(UserPasswordUpdate, self) \
            .dispatch(request, *args, **kwargs)
BERJON Matthieu's avatar
BERJON Matthieu committed
638

BERJON Matthieu's avatar
BERJON Matthieu committed
639
640
641
642
# JOBS
# -----------------------------------------------------------------------------

class JobList(LoginRequiredMixin, ListView):
BERJON Matthieu's avatar
BERJON Matthieu committed
643
644
645
646
647
648
649
650
651
652
653
654
    """Display the list of jobs for a given identified user

    Attributes:
        model:  model used in the view.
        context_object_name:    the name used in the template to display each
                                variable.
        paginate_by: the number of occurences per page
        template_name: name of the template loaded with this view.
        redirect_field_name: None

    Todo:
        - Check the relevance of `redirect_field_name` and delete it if necessary
BERJON Matthieu's avatar
BERJON Matthieu committed
655
656
657
658
659
660
661
662
663
    """
    model = Job
    context_object_name = 'job_list'
    template_name = 'job_list.html'
    paginate_by = 10
    redirect_field_name = 'redirect_to'

    def get_queryset(self):
        """Filter jobs for a given user"""
664
665
        queryset = Job.objects.filter(user_id=self.request.user.id
                ).exclude(state__in=(Job.DELETED, Job.ARCHIVED)).order_by('-id')
BERJON Matthieu's avatar
BERJON Matthieu committed
666
        return queryset
BERJON Matthieu's avatar
BERJON Matthieu committed
667

668

669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
class JobDetail(LoginRequiredMixin, DetailView):
    """Get a job detail for a specific user

    Attributes:
        model:  model used in the view.
        context_object_name:    the name used in the template to display each
                                variable.
        template_name: name of the template loaded with this view.

    """
    model = Job
    template_name = 'job_detail.html'
    context_object_name = 'job'

    def get_context_data(self, **kwargs):
        """Recover the logs and files related to this job"""
BERJON Matthieu's avatar
BERJON Matthieu committed
685
686
        job = Job.objects.get(pk=self.object.pk)

687
688
689
        if job.state == Job.DONE:
            # job is done
            # -> read the `allgo.log` file
690
            log_file = os.path.join(job.data_dir, 'allgo.log')
691
            try:
692
                with open(log_file, 'r', errors="replace") as log_data:
BERJON Matthieu's avatar
BERJON Matthieu committed
693
                    logs = log_data.read()
694
695
696
697
698
699
700
            except OSError as e:
                logs = '(logs not available)'
                log.error("Log file not available for job #%d (%s)", job.id, e)
        else:
            # job is pending
            # -> logs will be streamed (ajax request)
            logs = ""
BERJON Matthieu's avatar
BERJON Matthieu committed
701
702
        kwargs['logs'] = logs

703
704
705
        # Hide the logs panel if the job is not yet started
        kwargs["logs_hidden"] = "hidden" if job.state in (Job.NEW, Job.WAITING) else ""

BERJON Matthieu's avatar
BERJON Matthieu committed
706
707
        # Get the files and some metadata such as the webapp version
        webapp = Webapp.objects.get(docker_name=self.object.webapp.docker_name)
708
709
710
711
712
713

        # List all job files
        # NOTE: calling lookup_job_file is a security feature
        kwargs['files'] = [x for x in os.listdir(job.data_dir)
                if lookup_job_file(job.id, x)]

BERJON Matthieu's avatar
BERJON Matthieu committed
714
        return super().get_context_data(**kwargs)
715

716
717
    def render_to_response(self, context, **kwargs):
        if self.request.META.get("HTTP_ACCEPT") == "application/json":
718
719
            # json variant of the job details
            # (used by the /aio/jobs/<ID>/events endpoint)
720
721
722
723
            job = context["job"]
            return JsonResponse({
                "id":           job.id,
                "state":        job.get_state_display(),
724
                "result":       job.get_result_display(),
725
726
727
728
729
                "rendered_status": status_icon(job),
                "exec_time":    job.exec_time,
                })
        else:
            return super().render_to_response(context, **kwargs)
730

BERJON Matthieu's avatar
BERJON Matthieu committed
731
732
733
class JobCreate(SuccessMessageMixin, CreateView):
    """ Display the data related a specific web and create a job instance
        into the database
BERJON Matthieu's avatar
BERJON Matthieu committed
734
735
736
737
738
739
740
741
742

    Attributes:
        model:  model used in the view.
        form_class: form object to pass on the template.
        success_url: URL or handle where the user will be redirected.
        success_message: successfull message sent to the template
        template_name: name of the template loaded with this view.

    """
743
744
745
    model = Job
    form_class = JobForm
    success_message = 'Job created successfully.'
BERJON Matthieu's avatar
BERJON Matthieu committed
746
    template_name = 'webapp_detail.html'
747

748
749
750
    def get_success_url(self):
        return reverse('main:job_detail', args=(self.job_id,))

751
    def form_valid(self, form):
BERJON Matthieu's avatar
BERJON Matthieu committed
752
        """Save data coming from the form in the database """
753
754
        webapp = Webapp.objects.get(docker_name=self.kwargs['docker_name'])

BERJON Matthieu's avatar
BERJON Matthieu committed
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
        # If the user isn't identified, we send back an error message and
        # and redirect the user.
        if self.request.user.is_anonymous():
            messages.add_message(self.request, messages.ERROR, 'You must be identified to create a job.')
            log.warning("Someone tried to run a job without being identified.")
            return redirect('main:webapp_detail', webapp.docker_name)
        else:
            obj = form.save(commit=False)
            obj.queue_id = form.cleaned_data.get('queue_id').id
            obj.state = Job.NEW
            obj.result = 0
            obj.user_id = self.request.user.id
            obj.webapp_id = webapp.id
            obj.version = form.cleaned_data.get('version')
            obj.save()
770

BERJON Matthieu's avatar
BERJON Matthieu committed
771
            # Upload files if there are any
772
            upload_data(self.request.FILES.getlist('files'), obj)
BERJON Matthieu's avatar
BERJON Matthieu committed
773

BERJON Matthieu's avatar
BERJON Matthieu committed
774
775
776
            # start the job
            obj.state = Job.WAITING
            obj.save()
777
            self.job_id = obj.id
778

BERJON Matthieu's avatar
BERJON Matthieu committed
779
            return super().form_valid(form)
780
781

    def get_context_data(self, **kwargs):
BERJON Matthieu's avatar
BERJON Matthieu committed
782
        """Pass on the docker name to the template"""
783
        webapp = Webapp.objects.get(docker_name=self.kwargs['docker_name'])
BERJON Matthieu's avatar
BERJON Matthieu committed
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
        kwargs['webapp'] = webapp

        # Check if a readme is declared in the database
        if webapp.readme:
            readme_file = os.path.join(
                settings.MEDIA_ROOT,
                self.object.docker_name,
                'Readme')
            if os.path.exists(readme_file):
                with open(readme_file, 'r') as md_data:
                    kwargs['readme'] = md_data.read()
            else:
                log.warning("No README available for app %s", self.model.name)
        else:
            readme_file = None
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815

        # select the list of versions to be displayed
        versions = natsort.versorted(set(v for v, in WebappVersion.objects
                .filter(webapp=webapp, state__in=(  WebappVersion.SANDBOX,
                                                    WebappVersion.COMMITTED,
                                                    WebappVersion.READY))
                .values_list("number")))

        # also list 'sandbox' if the sandbox is running and if the current user
        # is allowed to use the sandbox
        if webapp.sandbox_state == Webapp.RUNNING and (
            webapp.is_pushable_by(self.request.user)):
            versions.append("sandbox")
        
        versions.reverse()
        kwargs['versions'] = versions

816
817
818
819
820
821
822
823
824
825
        # build the sample command lines for using the REST API
        base_url = get_base_url(self.request)
        user = self.request.user
        auth = "Authorization: Token token=" + (
                user.allgouser.token if user.is_authenticated else "<your private_token>")

        kwargs["job_create_cmd"] = ["curl", "-H", auth,
                "-X", "POST", base_url + reverse("api:jobs"),
                None, "-F", "job[webapp_id]=" + str(webapp.id),
                None, "-F", "job[param]=",
826
                None, "-F", "job[queue]=" + webapp.job_queue.name,
827
828
829
830
831
832
833
                None, "-F", "files[0]=@test.txt",
                None, "-F", "files[1]=@test2.csv",
                None, "-F", "job[file_url]=<my_file_url>",
                None, "-F", "job[dataset]=<my_dataset_name>",
                ]

        kwargs["job_result_cmd"] = ["curl", "-H", auth,
834
                base_url + reverse("api:job", args=(42,)).replace("42", "<job_id>")]
835

BERJON Matthieu's avatar
BERJON Matthieu committed
836
        return super().get_context_data(**kwargs)
837

838
839
    def get_form_kwargs(self):
        """Return webapp data"""
BERJON Matthieu's avatar
BERJON Matthieu committed
840
        kwargs = super().get_form_kwargs()
841
842
843
844
        queryset = Webapp.objects.get(docker_name=self.kwargs['docker_name'])
        kwargs['webapp'] = queryset
        return kwargs

BAIRE Anthony's avatar
BAIRE Anthony committed
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
class JobAbort(LoginRequiredMixin, View):
    def post(self, request, *, pk):
        job_id = int(pk)
        # switch state to ABORTING if the job is running (this is done
        # atomically to avoid messing up with the controller)
        if Job.objects.filter(id=job_id, state=Job.RUNNING
                ).update(state=Job.ABORTING):
            job_post_save(Job.objects.get(id=job_id))
            messages.success(request, "aborting job %s" % job_id)
        else:
            messages.error(request, "unable to abort job %s because is not running" % job_id)
        return redirect('main:job_detail', job_id)

        

860

861
class JobDelete(LoginRequiredMixin, DeleteView):
BERJON Matthieu's avatar
BERJON Matthieu committed
862
863
864
865
866
867
868
869
    """Delete a job from the database

    Attributes:
        model:  model used in the view.
        success_url: URL or handle where the user will be redirected.
        success_message: successfull message sent to the template
        template_name: name of the template loaded with this view.

870
871
872
873
874
875
876
877
    Note:
        The `success_message` can't be used alone with the
        `SuccessMessageMixin` because it's hooked to `form_valid` method and 
        can't work with a `DeleteView`.

    See also:
        https://code.djangoproject.com/ticket/21926

BERJON Matthieu's avatar
BERJON Matthieu committed
878
879
880
881
882
883
    """
    model = Job
    success_message = 'Job successfully deleted.'
    success_url = reverse_lazy('main:job_list')
    template_name = 'job_delete.html'

884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
    @classmethod
    def as_view(cls, **kw):
        # manage db transactions manually
        return transaction.non_atomic_requests(super().as_view(**kw))

    def delete(self, request, *args, pk, **kwargs):
        # NOTE: if job is in WAITING state, then any state update must be done
        # atomically so as not to mess up with che controller
        if not (Job.objects.filter(id=pk, state=Job.DONE
                    ).update(state=Job.ARCHIVED)
            or  Job.objects.filter(id=pk, state__in=(Job.NEW, Job.WAITING)
                    ).update(state=Job.DELETED)
            or  Job.objects.filter(id=pk, state__in=(Job.DELETED, Job.ARCHIVED)).exists()
            ):

899
            messages.error(self.request, "cannot delete a running job")
900
            return redirect('main:job_detail', pk)
901

902
        transaction.commit()
903

904
        self.object = job = self.get_object()
905
        notify_controller(job) # so that the DELETED/ARCHIVED state is propagated into the redis db
906
907
908

        # delete the data dir if present
        # FIXME: if this fail then we have dangling files staying in the way
909
        job_dir = job.data_dir
910
911
912
        if os.path.exists(job_dir):
            shutil.rmtree(job_dir)

913
914
915
916
917
        if job.state == Job.DELETED:
            job.delete()

        messages.success(self.request, self.success_message)
        return redirect(self.get_success_url())
918

919

BERJON Matthieu's avatar
BERJON Matthieu committed
920
921
922
923
924
925
926
927
928
929

class JobFileDownload(LoginRequiredMixin, View):
    """Download a given file"""

    def get(self, request, *args, **kwargs):
        """Return a file for a given job and filename
        """
        # get file
        job_id = self.kwargs['pk']
        filename = self.kwargs['filename']
930
        return redirect("/datastore/%s/%s" % (job_id, filename))
BERJON Matthieu's avatar
BERJON Matthieu committed
931
932


933
class JobFileDownloadAll(LoginRequiredMixin, SingleObjectMixin, View):
BERJON Matthieu's avatar
BERJON Matthieu committed
934
935
    """Archive and download all files of a given job
    """
936
    model = Job
BERJON Matthieu's avatar
BERJON Matthieu committed
937
938
939
940
941
942
943

    def get(self, request, *args, **kwargs):
        """get all the file for a given job

        The method gets the job ID, recover each file related to this job,
        archive into a ZIP file and return it.

944
945
946
        The ZIP file is stored as an anonymous file in /tmp/ then streamed with
        FileResponse. This is better that keepingthe whole file in memory
        because it may be large (and linux has a quite efficient page cache).
BERJON Matthieu's avatar
BERJON Matthieu committed
947
        """
948
        job = self.get_object()
949
        tmp_file = tempfile.TemporaryFile()
BERJON Matthieu's avatar
BERJON Matthieu committed
950

951
952
        zip_subdir = str(job.id)
        zip_filename = 'job_%s.zip' % zip_subdir
BERJON Matthieu's avatar
BERJON Matthieu committed
953

954
        zip_file = zipfile.ZipFile(tmp_file, 'w')
BERJON Matthieu's avatar
BERJON Matthieu committed
955

956
957
958
959
960
961
        for filename in os.listdir(job.data_dir):
            # NOTE: calling lookup_job_file is a security feature
            real_path = lookup_job_file(job.id, filename)
            if real_path:
                zip_path = os.path.join(zip_subdir, filename)
                zip_file.write(real_path, zip_path)
BERJON Matthieu's avatar
BERJON Matthieu committed
962

963
        zip_file.close()
BERJON Matthieu's avatar
BERJON Matthieu committed
964

965
966
        tmp_file.seek(0)
        response = FileResponse(tmp_file, content_type='application/x-zip-compressed')
967
968
        response["Content-Disposition"] = "attachment; filename={0}".format(zip_filename)
        return response
969
970


BERJON Matthieu's avatar
BERJON Matthieu committed
971
972
973
# RUNNERS
# -----------------------------------------------------------------------------
class RunnerList(LoginRequiredMixin, ListView):
BERJON Matthieu's avatar
BERJON Matthieu committed
974
975
976
977
978
979
980
981
982
983
    """List all runners of a given user

    Attributes:
        model:  model used in the view.
        context_object_name:    the name used in the template to display each
                                variable.
        paginate_by: the number of occurences per page
        template_name: name of the template loaded with this view.

    """
BERJON Matthieu's avatar
BERJON Matthieu committed
984
985
986
987
988
    model = Runner
    context_object_name = 'runner_list'
    paginate_by = 10
    template_name = 'runner_list.html'

BERJON Matthieu's avatar
BERJON Matthieu committed
989
990
991
992
993
994
995
    def get_queryset(self):
        """Returns all runners of a given user
        
        Returns all runners for a given user from the most recent to the
        oldest one.
        """
        queryset = Runner.objects.filter(user=self.request.user).order_by('-created_at')
BERJON Matthieu's avatar
BERJON Matthieu committed
996
        return queryset
BERJON Matthieu's avatar
BERJON Matthieu committed
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
    
    def get_context_data(self, **kwargs):
        """Return the number of webapps of a given user
        
        This method returns the number of webapps of a given user and pass it
        onto the template in order to display or not the link to add a runner
        or not. There are no reasons of adding a runner if the user doesn't
        manage any applications.
        """
        webapp_count = Webapp.objects.filter(user=self.request.user).count()
        kwargs['webapp_count'] = webapp_count
        return super().get_context_data(**kwargs)
1009
1010


BERJON Matthieu's avatar
BERJON Matthieu committed
1011
class RunnerCreate(SuccessMessageMixin, LoginRequiredMixin, GroupRequiredMixin, CreateView):
BERJON Matthieu's avatar
BERJON Matthieu committed
1012
1013
1014
1015
1016
1017
1018
1019
1020
    """Create a runner and save it into the database

    Attributes:
        model:  model used in the view.
        form_class: form object to pass on the template.
        success_message: successfull message sent to the template
        template_name: name of the template loaded with this view.

    """
1021
1022
1023
    model = Runner
    form_class = RunnerForm
    success_message = 'Runner saved successfully.'
1024
    error_message = 'You don\'t have sufficient privileges to create an open bar runner.'
1025
    success_url = reverse_lazy('main:runner_list')
1026
    template_name = 'runner_add_update.html'
BERJON Matthieu's avatar
BERJON Matthieu committed
1027
    group_required = ['inria', ]
1028

1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
    def form_valid(self, form):
        """ Validate some fields before saving them."""
        obj = form.save(commit=False)

        # If the open-bar argument is true and the user is a superuser.
        # We setup the field as True
        if form.cleaned_data.get('open_bar') and self.request.user.is_superuser:
            obj.open_bar = True

        # If the open-bar argument is true but the user isn't
        # We send an error message and force the field to False
        if form.cleaned_data.get('open_bar') and not self.request.user.is_superuser:
            obj.open_bar = False
1042
            messages.error(self.request, self.error_message)
1043

1044
        obj.user = self.request.user
1045
1046
1047
        obj.save()
        return super().form_valid(form)

1048
    def get_form_kwargs(self):
BERJON Matthieu's avatar
BERJON Matthieu committed
1049
        """Pass on the request data onto the template"""
1050
        kwargs = super().get_form_kwargs()
1051
1052
        kwargs['request'] = self.request
        return kwargs
1053

1054
1055
1056
1057
    def get_success_url(self):
        """If successful redirect to the runner update page"""
        return reverse_lazy('main:runner_update', args=(self.object.pk,))

1058
1059

class RunnerUpdate(SuccessMessageMixin, LoginRequiredMixin, UpdateView):
BERJON Matthieu's avatar
BERJON Matthieu committed
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
    """Update a runner and save it into the database

    Attributes:
        model:  model used in the view.
        form_class: form object to pass on the template.
        success_message: successfull message sent to the template
        success_url: URL or handle where the user will be redirected.
        template_name: name of the template loaded with this view.

    """
1070
1071
1072
1073
    model = Runner
    form_class = RunnerForm
    success_message = 'Runner updated successfully.'
    success_url = reverse_lazy('main:runner_list')
1074
    template_name = 'runner_add_update.html'
1075
1076

    def get_form_kwargs(self):
BERJON Matthieu's avatar
BERJON Matthieu committed
1077
        """Pass on the request data onto the template"""
1078
1079
1080
        kwargs = super(RunnerUpdate, self).get_form_kwargs()
        kwargs['request'] = self.request
        return kwargs
1081

1082
    def get_context_data(self, **kwargs):
1083
1084
1085
        kwargs["runner_launch_cmd"] = ["docker", "run",
                "-v", "/var/run/docker.sock:/var/run/docker.sock", "--net=host",
                "allgo/runner", "-", self.object.token, get_base_url(self.request)]
1086
        return super().get_context_data(**kwargs)
1087

1088
class RunnerDelete(LoginRequiredMixin, DeleteView):
BERJON Matthieu's avatar
BERJON Matthieu committed
1089
1090
1091
1092
1093
1094
1095
1096
1097
    """Delete a runner

    Attributes:
        model:  model used in the view.
        success_message: successfull message sent to the template
        success_url: URL or handle where the user will be redirected.
        template_name: name of the template loaded with this view.

    """
1098
1099
1100
1101
    model = Runner
    success_message = 'Runner successfully deleted.'
    success_url = reverse_lazy('main:runner_list')
    template_name = 'runner_delete.html'
1102
1103
1104
1105

    def delete(self, request, *args, **kwargs):
        messages.success(self.request, self.success_message)
        return super().delete(request, *args, **kwargs)
1106
1107


1108
1109
1110
1111
1112
1113
1114
1115
1116
@csrf_exempt
def auth(request):
    """
    nginx route /datastore/jobid/filename ask an authorization here with auth_request module

    we must play with two kind of auth, with django and by token
    :param request:
    :return:
    """
1117
    log.debug("Auth request for %r", request.META.get('HTTP_X_ORIGINAL_URI'))
1118

1119
    # authenticate the user
1120
    user = None
1121
1122
1123
1124
1125
    if request.user and request.user.is_authenticated(): # django authentification
        user = request.user
    elif request.META.get('HTTP_AUTHORIZATION', ''):  # token authentification
        _, credentials = request.META.get('HTTP_AUTHORIZATION', '').split(' ')
        _, token = credentials.split('=')
1126
1127
1128
1129
        try:
            user = AllgoUser.objects.get(token=token)
        except AllgoUser.DoesNotExist:
            pass
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
    if user is None:
        return HttpResponse(status=401)

    # find the relevant job
    params = request.META['HTTP_X_ORIGINAL_URI'].split('/')
    try:
        job = Job.objects.get(id=int(params[2]))
    except ObjectDoesNotExist:
        # technically this should be a 404, but nginx auth_request only
        # understands 401 & 403
        return HttpResponse(status=403)
1141

1142
    if user.id == job.user.id:
1143
1144
        return HttpResponse(status=200)
    else:
1145
        return HttpResponse(status=403)