简体   繁体   中英

protecting user uploaded files django

How can I allow users to upload files to their own, user designated folder, and only see files that they have uploaded? I am using django file-transfer. Currently it gives me a choice of what file to put the media in, but I can put it in any user's file and view every user's media. Here is my uploads/models.py:

from django.db import models
from django.contrib.auth.models import User, UserManager

def uploadmodel_file_upload_to(instance, filename):
    print 'instance.user.username = '+ str(instance.user.username)
    return 'uploads/%s/%s' % (instance.user.username, filename)

class UploadModel(models.Model):
    user = models.ForeignKey('auth.user')
    file = models.FileField(upload_to=uploadmodel_file_upload_to)

uploadmodel_file_upload_to returns a relative path. To build the full path, django prepends settings.MEDIA_ROOT. MEDIA_ROOT is supposed to be public readable.

So we want to save the file outside MEDIA_ROOT. Add something like this to settings.py:

import os.path
PROJECT_ROOT=os.path.abspath(os.path.dirname(__file__))
PROTECTED_MEDIA_ROOT=os.path.join(PROJECT_ROOT, 'protected_uploads')

Now you can update uploadmodel_file_upload_to to return an absolute path:

def uploadmodel_file_upload_to(instance, filename):
    return '%s/%s/%s' % (settings.PROTECTED_MEDIA_ROOT, instance.user.username,
        filename)

Now that the files are saved in /project/path/protected_uploads, we need to add a view to serve it, for example:

import os 
import mimetypes

from django import shortcuts
from django import http
from django.conf import settings
from django.views.static import was_modified_since
from django.utils.http import http_date

from .models import *

def serve_upload(request, upload_id):
    upload = shortcuts.get_object_or_404(UploadModel, pk=upload_id)
    fullpath = upload.file.path

    if request.user != upload.user:
        return http.HttpResponseForbidden()

    statobj = os.stat(fullpath)
    mimetype, encoding = mimetypes.guess_type(fullpath)
    mimetype = mimetype or 'application/octet-stream'
    if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'),
                              statobj.st_mtime, statobj.st_size):
        return http.HttpResponseNotModified(mimetype=mimetype)
    response = http.HttpResponse(open(fullpath, 'rb').read(), mimetype=mimetype)
    response["Last-Modified"] = http_date(statobj.st_mtime)
    response["Content-Length"] = statobj.st_size
    if encoding:
        response["Content-Encoding"] = encoding
    return response

And a URL:

url(r'serve_upload/(?P<upload_id>\d+)/$', 'serve_upload'),

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM