file permissions, make private, models have changed.

This commit is contained in:
Sanj 2011-07-04 18:07:45 +05:30
parent 83754f26c0
commit d5de68899b
5 changed files with 125 additions and 13 deletions

View File

@ -94,6 +94,7 @@ class File(models.Model):
file_date = models.DateField("Date", blank=True, null=True) file_date = models.DateField("Date", blank=True, null=True)
added = models.DateField("Date Added", auto_now_add=True) added = models.DateField("Date Added", auto_now_add=True)
categories = models.ManyToManyField('Category', verbose_name='Studies') categories = models.ManyToManyField('Category', verbose_name='Studies')
private = models.BooleanField(default=False)
# type = models.ForeignKey('Type', verbose_name='File Type') # type = models.ForeignKey('Type', verbose_name='File Type')
type = models.CharField(max_length=255, choices=TYPE_CHOICES) type = models.CharField(max_length=255, choices=TYPE_CHOICES)
ext = models.CharField(max_length=100, blank=True) ext = models.CharField(max_length=100, blank=True)
@ -144,7 +145,8 @@ class File(models.Model):
'title': self.title, 'title': self.title,
'description': self.description, 'description': self.description,
'type': self.type, 'type': self.type,
'studies': studies 'studies': studies,
'is_private': self.private
} }
def save_chunk(self, chunk, name='data.bin'): def save_chunk(self, chunk, name='data.bin'):
@ -215,6 +217,12 @@ class File(models.Model):
self.save() self.save()
return self return self
def can_edit(self, user):
if user.is_superuser or self.userID == user:
return True
else:
return False
class Category(models.Model): class Category(models.Model):
name = models.CharField(max_length=255) name = models.CharField(max_length=255)
groups = models.ManyToManyField(Group, null=True) groups = models.ManyToManyField(Group, null=True)

View File

@ -10,6 +10,8 @@ urlpatterns = patterns('',
(r'^editFile/', views.editFile), (r'^editFile/', views.editFile),
(r'^deleteFiles/', views.deleteFiles), (r'^deleteFiles/', views.deleteFiles),
(r'^moveFiles/', views.moveFiles), (r'^moveFiles/', views.moveFiles),
(r'makePrivate/', views.makeFilePrivate),
(r'makePublic/', views.makeFilePublic),
(r'json_list', views.fileList), (r'json_list', views.fileList),
(r'browse', views.browse) (r'browse', views.browse)
) )

View File

@ -17,6 +17,8 @@ try:
import json import json
except: except:
import simplejson as json import simplejson as json
from utils.decorators import user_passes_test_json
from django.db.models import Q
''' '''
class folder_names(object): class folder_names(object):
@ -24,6 +26,36 @@ class folder_names(object):
return iter(map(lambda x: (x,x), os.listdir(UPLOAD_ROOT))) return iter(map(lambda x: (x,x), os.listdir(UPLOAD_ROOT)))
''' '''
def canEditFile(request):
id = request.POST.get("id", 0)
fil = File.objects.get(pk=id)
u = request.user
response = {}
if fil.can_edit(u):
response['status'] = 'pass'
else:
response['status'] = 'fail'
response['error'] = "you do not have permission to edit this file."
return response
def canEditFiles(request):
ids = request.POST.get("ids", "[]")
files = json.loads(ids)
u = request.user
response = {}
for f in files:
fil = File.objects.get(pk=f)
if not fil.can_edit(u):
response['status'] = 'fail'
if response['status'] == 'fail':
response['error'] = 'sorry, you do not have necessary permissions to edit these files'
else:
response['status'] = 'pass'
return response
def getFolderList(): def getFolderList():
os.chdir(FTP_ROOT) os.chdir(FTP_ROOT)
dirs = filter(isdir, os.listdir(FTP_ROOT)) dirs = filter(isdir, os.listdir(FTP_ROOT))
@ -211,7 +243,7 @@ def add(request):
@csrf_exempt @csrf_exempt
@login_required @user_passes_test_json(canEditFile)
def editFile(request): def editFile(request):
errors = [] errors = []
try: try:
@ -226,35 +258,61 @@ def editFile(request):
fil.__setattr__(k, val) fil.__setattr__(k, val)
fil.save() fil.save()
response = { response = {
'errors': errors 'status': 'pass'
} }
return render_to_json_response(response) return render_to_json_response(response)
@csrf_exempt @csrf_exempt
@login_required @user_passes_test_json(canEditFile)
def deleteFiles(request): def deleteFiles(request):
errors = []
files = json.loads(request.POST.get("ids", "[]")) files = json.loads(request.POST.get("ids", "[]"))
for f in files: for f in files:
fil = File.objects.get(pk=f) fil = File.objects.get(pk=f)
fil.delete() fil.delete()
response = { response = {
'errors': errors 'status': 'pass'
}
return render_to_json_response(response)
@csrf_exempt
@user_passes_test_json(canEditFile)
def makeFilePrivate(request):
# errors = []
id = request.POST.get("id", "0")
fil = File.objects.get(pk=id)
fil.private = True
fil.save()
response = {
'status': 'pass'
}
return render_to_json_response(response)
@csrf_exempt
@user_passes_test_json(canEditFile)
def makeFilePublic(request):
errors = []
id = request.POST.get("id", "0")
fil = File.objects.get(pk=id)
fil.private = False
fil.save()
response = {
'status': 'pass'
} }
return render_to_json_response(response) return render_to_json_response(response)
@csrf_exempt @csrf_exempt
@login_required @user_passes_test_json(canEditFiles)
def moveFiles(request): def moveFiles(request):
errors = [] response = {}
files = json.loads(request.POST.get("ids", "[]")) files = json.loads(request.POST.get("ids", "[]"))
study_id = int(request.POST.get("study", "0")) study_id = int(request.POST.get("study", "0"))
study = Category.objects.get(pk=study_id) study = Category.objects.get(pk=study_id)
for f in files: for f in files:
fil = File.objects.get(pk=f) fil = File.objects.get(pk=f)
fil.move_to(study) fil.move_to(study)
response['status'] = 'pass'
return render_to_json_response(errors) return render_to_json_response(errors)
@ -264,7 +322,12 @@ def fileList(request):
typ = request.POST.get("fileType", '') typ = request.POST.get("fileType", '')
search = request.POST.get("search", '') search = request.POST.get("search", '')
page = request.POST.get("page_no", 1) page = request.POST.get("page_no", 1)
qset = File.objects.all() # private = request.POST.get("private", "0")
user = request.user
if user.is_superuser:
qset = File.objects.all()
else:
qset = File.objects.filter(Q(private=False) | (Q(private=True) & Q(userID=user.id)))
if category != '': if category != '':
qset = File.filter_category(category, qset) qset = File.filter_category(category, qset)
if typ != '': if typ != '':
@ -282,6 +345,7 @@ def fileList(request):
files = results.object_list files = results.object_list
d = {} d = {}
d['status'] = 'pass'
d['noOfResults'] = qset.count() d['noOfResults'] = qset.count()
d['noOfPages'] = paginator.num_pages d['noOfPages'] = paginator.num_pages
d['currentPage'] = current_page d['currentPage'] = current_page
@ -289,12 +353,16 @@ def fileList(request):
# d['hasNext'] = paginator.has_next() # d['hasNext'] = paginator.has_next()
d['files'] = [] d['files'] = []
for f in files: for f in files:
d['files'].append(f.get_dict()) fileData = f.get_dict()
fileData['can_edit'] = f.can_edit(user)
d['files'].append(fileData)
return render_to_json_response(d) return render_to_json_response(d)
def browse(request): def browse(request):
form = FileFilterForm() form = FileFilterForm()
return render_to_response("files/browser.html", { return render_to_response("files/browser.html", {
'filterForm': form 'filterForm': form
}) })

View File

@ -67,6 +67,9 @@ $(function() {
var url = "/files/deleteFiles/"; var url = "/files/deleteFiles/";
var params = {'ids': JSON.stringify(ids)}; var params = {'ids': JSON.stringify(ids)};
$.post(url, params, function(response) { $.post(url, params, function(response) {
if (response.status == 'fail') {
alert(response.error);
}
$this.removeAttr("disabled"); $this.removeAttr("disabled");
$('#filterForm').submit(); $('#filterForm').submit();
}); });
@ -88,6 +91,9 @@ $(function() {
} }
$.post(url, params, function(response) { $.post(url, params, function(response) {
if (response.status == 'fail') {
alert(response.error);
}
$this.removeAttr("disabled"); $this.removeAttr("disabled");
$('#filterForm').submit(); $('#filterForm').submit();
}, "json"); }, "json");
@ -158,12 +164,37 @@ function getItemForm(f) {
var $descriptionLabel = $('<span />').addClass("itemFormLabel").addClass("descriptionLabel").text("Description").appendTo($labelsP); var $descriptionLabel = $('<span />').addClass("itemFormLabel").addClass("descriptionLabel").text("Description").appendTo($labelsP);
var $inputsP = $('<p />').appendTo($form); var $inputsP = $('<p />').appendTo($form);
var $titleInput = $('<input />').addClass("itemTitle").val(f.title).appendTo($inputsP); var $titleInput = $('<input />').addClass("itemTitle").val(f.title).appendTo($inputsP);
if (f.can_edit) {
var $privateLabel = $('<span />').addClass("pvtLabel").text("Private ").appendTo($inputsP);
var $pvtCheckbox = $('<input />').attr("type", "checkbox").attr("checked", f.is_private).appendTo($inputsP);
$pvtCheckbox.change(function() {
var checked = $(this).is(":checked");
if (checked) {
var url = "/files/makePrivate/";
} else {
var url = "/files/makePublic/";
}
var parent = $(this).parents(".itemForm");
var id = parent.find(".itemId").val();
var params = {'id': id}
$.post(url, params, function(response) {
if (response.status == 'fail') {
alert(response.error);
}
}, "json");
});
}
var $descriptionInput = $('<textarea />').addClass("itemDescription").val(f.description).appendTo($inputsP); var $descriptionInput = $('<textarea />').addClass("itemDescription").val(f.description).appendTo($inputsP);
var $hiddenInput = $('<input />').addClass("itemId").attr("type", "hidden").val(f.id).appendTo($inputsP); var $hiddenInput = $('<input />').addClass("itemId").attr("type", "hidden").val(f.id).appendTo($inputsP);
var $submitP = $('<p />').addClass("submitInput").appendTo($form); var $submitP = $('<p />').addClass("submitInput").appendTo($form);
var $submit = $('<input />').addClass("submitItem").attr("type", "submit").val("Submit").appendTo($submitP); var $submit = $('<input />').addClass("submitItem").attr("type", "submit").val("Submit").appendTo($submitP);
var $submitStatus = $('<span />').addClass("submitStatus").appendTo($submitP); var $submitStatus = $('<span />').addClass("submitStatus").appendTo($submitP);
$submit.click(function(e) { $submit.click(function(e) {
if (typeof($(this).attr("disabled")) != 'undefined') {
return false;
}
var url = "/files/editFile/"; var url = "/files/editFile/";
var parent = $(this).parents('.itemForm'); var parent = $(this).parents('.itemForm');
$('.submitStatus').text("Submitting..."); $('.submitStatus').text("Submitting...");
@ -178,6 +209,9 @@ function getItemForm(f) {
$('.submitItem').removeAttr("disabled"); $('.submitItem').removeAttr("disabled");
}, "json"); }, "json");
}); });
if (!f.can_edit) {
$submit.attr("disabled", "disabled");
}
return $form; return $form;
} }

View File

@ -112,12 +112,12 @@ function fileUploadedCallback(jq, data) {
var $error = $('<div />').addClass("fileError").text(data.errors[0]).appendTo(jq); var $error = $('<div />').addClass("fileError").text(data.errors[0]).appendTo(jq);
} else { } else {
var $formContainer = $('<div />').addClass("fileForm"); var $formContainer = $('<div />').addClass("fileForm");
var $title = $('<div />').addClass("formHelp").text("Add Description").appendTo($formContainer); // var $title = $('<div />').addClass("formHelp").text("Add Description").appendTo($formContainer);
// console.log(data); // console.log(data);
var $titleInput = $('<input />').attr("type", "text").addClass("fileTitle").val(d.title); var $titleInput = $('<input />').attr("type", "text").addClass("fileTitle").val(d.title);
// console.log($titleInput); // console.log($titleInput);
$titleInput.appendTo($formContainer); $titleInput.appendTo($formContainer);
var $descInput = $('<textarea />').addClass("fileDesc").appendTo($formContainer); var $descInput = $('<textarea />').attr("placeholder", "Add Description").addClass("fileDesc").appendTo($formContainer);
var $submitBtn = $('<button />').text("Submit").click(function() { var $submitBtn = $('<button />').text("Submit").click(function() {
var $this = $(this); var $this = $(this);
$this.attr("disabled", "disabled"); $this.attr("disabled", "disabled");