File permissions checks

This commit is contained in:
Carl van Tonder 2018-04-30 22:23:36 -04:00
parent e43c32b843
commit 6dc0b51fc3
5 changed files with 41 additions and 14 deletions

View File

@ -6,4 +6,4 @@ from .models import File
class FileForm(forms.ModelForm):
class Meta:
model = File
fields = '__all__'
exclude = ['user',]

View File

@ -0,0 +1,24 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2018-04-29 22:07
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('files', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='file',
name='user',
field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, related_name='files', to=settings.AUTH_USER_MODEL),
preserve_default=False,
),
]

View File

@ -1,3 +1,4 @@
from django.contrib.auth.models import User
from django.db import models
from apps.map.models import CaseStudy, CaseStudyDraft
@ -7,6 +8,9 @@ class BaseFile(models.Model):
file = models.FileField(
upload_to='.',
)
user = models.ForeignKey(
User, related_name='files'
)
class Meta:
abstract = True

View File

@ -1,4 +1,5 @@
from django.shortcuts import render
from django.core.exceptions import PermissionDenied
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import JsonResponse
from django.shortcuts import render
from django.views.generic import FormView, DetailView
@ -6,16 +7,14 @@ from django.views.generic import FormView, DetailView
from .forms import FileForm
from .models import File
class FileUploadView(FormView):
# FIXME require login
class FileUploadView(LoginRequiredMixin, FormView):
model = File
form_class = FileForm
def form_valid(self, form):
self.object = form.save()
# FIXME set File owner
self.object = form.save(commit=False)
self.object.user = self.request.user
self.object.save()
return JsonResponse({
'is_valid': True, 'url': self.object.file.url,
@ -27,18 +26,18 @@ class FileUploadView(FormView):
return JsonResponse({'is_valid': False, 'errors': form.errors})
class FileDeleteView(DetailView):
# FIXME require login
class FileDeleteView(LoginRequiredMixin, DetailView):
model = File
def get(self, request, *args, **kwargs):
return self.post(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
# FIXME check file ownership
self.object = self.get_object()
if request.user != self.object.user:
raise PermissionDenied
self.object.delete()
return JsonResponse({

View File

@ -119,7 +119,7 @@ class SpatialRefSysAutocomplete(autocomplete.Select2QuerySetView):
return qs
class Drafts(View):
class Drafts(LoginRequiredMixin, View):
"""Retrieve or save a draft."""
def get_object(self, request):