User permissions Django for serving media - django

I want to set up a Django server that allows certain users to access certain media. I'm sure this can't be that hard to do and I'm just being a little bit silly.
For example I want USER1 to be able to access JPEG1, JPEG2 and JPEG3 but not JPEG4, and USER2 to be able to access JPEG3 and JPEG 4.
[I know I should be burnt with fire for using Django to serve up media, but that's what I'm doing at the moment, I'll change it over when I start actually running on gas.]

You can send a file using django by returning the file in the request as shown in Vazquez-Abrams link.
However, you would probably do best by using mod_xsendfile in apache (or similar settings in lighttpd) due to efficiency. Django is not as fast at sending it, one way to do so while keeping the option of using the dev server's static function would be http://pypi.python.org/pypi/django-xsendfile/1.0
As to what user should be able to access what jpeg, you will probably have to implement this yourself. A simple way would be to create an Image model with a many-to-many field to users with access and a function to check if the current user is among those users. Something along the line of:
if image.users_with_access.filter(pk=request.user.id).exists():
return HttpResponse(image.get_file())
With lots of other code of course and only as an example. I actually use a modified mod_xsend in my own project for this very purpose.

You just need to frob the response appropriately.

You can put the media in http://foo.com/media/blah.jpg and set up a media/(?P<file>.*) in urls.py to point to a view blahview that checks the user and their permissions within:
from you_shouldve_made_one_anyways import handler404
def blahview(request,*args,**kwargs):
if cannot_use( request.user, kwargs['username'] ): return handler404(request)
...
Though just to be clear, I do not recommend serving media through Django.

Related

Users for multiple sites in Django

I am trying to get multiple sites to use the same database and code but in a way which forces each user to have their own login to each site.
I have seen a few suggestions as to how to make this work but I'm not sure which way to go.
I am using the Sites Framework, using the subdomain to identify the current site so I'm not using SITE_ID at all.
Use the sites framework - This answer (https://stackoverflow.com/a/1405902/1180442) suggests using the sites framework to do it, but I'm having trouble with the get_user() method, as it doesn't have access to the request and that's where my site info is stored.
Use separate databases for users - I'm really not sure about this one but I think it might cause bigger problems down the line.
Change to using SITE_ID - I want to try and avoid this if possible as it will mean having to run many different instances of my app, one for each site, which uses it's own settings.py. This will quickly turn into a nightmare, I think.
Permissions - I'm wondering if this should be something that I get the permissions framework to use? So one set of users for all sites but each user can have permissions to see each site, as long as they've registered with that site?
Can anyone help with this?
I quite like the idea of number 1 but I just need to get the request in the get_user() method so I can do this
def get_user(self, user_id):
try:
# I can't do this because there is no request available here
return User.objects.get(pk=user_id, site=request.site)
except User.DoesNotExist:
return None
to prevent people logged in to one site being able to log into another using the same session.
How I actually do it, not for users but for common databases, Is to design a main, hidden app with a REST API architecture. My other apps, naturally have their own DB and exchange their data via batch or stream process depending on the need. I use django-rest-framework.
For your case what I would do is that whenever a user makes a Log In request I would send it via HTTPS to my main database and get it authenticated in my main app. Whenever I would need to validate the user status I would simply make a get request to the main app.
This architecture is not that different from the one that many mobile apps have.
I hope it helps.

What is safe implementation for sensitive data file file_url in Django

I am providing sensitive username and password file to the authenticated user. I want user to download the file via file_url in template through model.
File_link = models.FileField(upload_to='SAFE_DIRECTORY_PATH')
I don't feel it safe storing it in media directory
Any suggestions keeping them safe ,web app will be generating the link.
Some security notes first.
This is probably a bad idea. Storing sensitive information in plain files is probably not the correct security approach, especially if you plan to use Django's media storage backend for doing that. It leaves all files out-in-the-open.
If however you really, really, and I mean really need to do that, you should encrypt the file first before saving in Django.
Again though, if at all possible I would recommend to store sensitive information in db. In your case of storing passwords, you can use Django techniques to store that information relatively-safely such as correctly hashing passwords via pbkdf function (e.g. pbkdf or bcrypt, etc). If users will need to download that information, you can always generate the file on the fly for them for download.
Some suggestions for uploading files.
I usually assign random filenames to the uploaded files. This way at least its more challenging for the users to guess the filenames to download them. Not very security since this relies on security by obfuscation but its better then nothing. If you need a Django field which does that automatically, you can do that by making upload_to a callable (there are also 3rd party libs for doing that such as django-auxilium although for full disclosure Im the author of that lib).
Now that files are stored with random filenames, you probably never want to provide direct download links to the users for download but instead authenticate them first and then use something like X-Accel in nginx or X-Sendfile in Apache to actually serve the file to the user. The idea being that you first authenticate user in Django. Then however instead of Django serving the file, you return a special header which nginx/apache catches which contains a filepath to the file nginx/apache should serve to the user. This way you dont have to waste resources in Django to serve the file however you still get the advantage of being able to authenticate the request. There are a number of 3rd party apps for doing that as well.
Finally to protect users from downloading the media files you can use nginx (and I imagine apache) by restricting certain parts of the media folder:
location /media/protected {
internal;
alias /var/www/files;
}
In this case nginx will refuse direct user requests to /media/protected and will only allow to serve those files via X-Accel-Redirect header sent by Django. Then all you have to configure in Django is to store files in that path to make them protected:
models.FileField(upload_to='protected/myfiles')
I was looking for a solution to serve files only to authorized users and came across this post. I think it it is top google result for "django storing and providing secure files"
As the answer is rather old I wanted to share my finding:
django-private-storage (https://pypi.org/project/django-private-storage/) seems to be a good solution to this problem.

Restricting access to static files in Django/Nginx

I am building a system that allows users to generate a documents and then download them. The documents are PDFs (not that it matters for the sake of this question) and when they are generated I store them on my local file system that the web server is running on with uuid file names
c7d43358-7532-4812-b828-b10b26694f0f.pdf
but I know "security through obscurity" is not the right solution ...
I want to restrict access to they files on a per account basis if possible. One thing I think I could do is upload them to S3 and provide a signed URL, but I want to avoid that for now if possible.
I am using Nginx/Django/Gunicorn/EC2/S3
What are some other solutions?
If you are serving small files, you can indeed use Django to serve them directly, writing the file into the HttpResponse object.
If you're serving large files however, you might want to leave that task to your webserver, you can use the X-Accel-Redirect header on Nginx (and X-Sendfile for Apache & Lighttpd) to have your webserver serve the file for you.
You can find more information about the header itself in Nginx's documentation here, and you could find some inspiration as to how to use that in Django here.
Once you're done sending files through Django views, enforcing user authentication should be pretty straightfoward using Django's auth framework.
How about enforcing user==owner at the view level, preventing access to the files, storing them as FileFields, and only retrieving the file if that condition is met.
e.g. You could use the #login_required decorator on the view to allow access only if logged in. This could be refined using request.user to check against the owner of the file. The User Auth section of the Django documentation is likely to be helpful here.
The other option, as you mention is via S3 itself, generating urls within Django which have a querystring allowing an authenticated user access to download a particular s3 object with a time limit. Details on that can be found at the s3 documentation. A similar question has been asked before here on SO.
I've used django-private-files with great success, it enforces protection at the view level and uses differente backends to do the actual file transfer.

Django: control access to "static" files

Ok, I know that serving media files through Django is a not recommended. However, I'm in a situation where I'd like to serve "static" files using fine-grained access control through Django models.
Example: I want to serve my movie library to myself over the web. I'm often travelling and I'd like to be able to view any of my movies wherever I am, provided I have internet access. So I rip my DVDs, upload them to my server and build this simple Django application coupled with some embeddable video player.
To avoid any legal repercussions, I'd like to ensure that only logged-on users with the proper permissions (i.e. myself and people living in the same household, which can, like me, access the real DVDs at their convenience), but denies it to other users (i.e. people who posted comments on my blog) and returns an HTTP 404.
Now, serving these files directly using Apache and mod_wsgi is rather troublesome because when an HTTP request for the media files (i.e. http://video.mywebsite.com/my-favorite-movie/) comes in, I need to validate against my user database that the person at the other end has the proper permissions.
Question: can I achieve this effect without serving the media files directly through a Django view? What are my options?
One thing I did think of is to write a simple script that takes a session ID and a video's slug and returns some boolean indicating if the user may (or may not) access the video file. Then, somehow request mod_wsgi to execute this script before accessing the requested URL and return an HTTP 404 if the script failed. However, I don't have a clue if this is even possible.
Edit: Posting this question clarified some of my ideas for search and I've come across mod_python's file wrapper extension. Does anyone have enough experience with that to validate that it is a viable solution?
Yes, you can hook into Django's authentication from Apache. See this how-to:
Authenticating against Django’s user database from Apache

How do I set session variables at login using django-registration and auth?

I'm using django-registration to log users into my application. That part works fine. The part that I cannot figure out is how to set custom session variables when the user logs in. For instance, I'd like to populate variables containing UserProfile data as well as the output of a few other functions. Then I'd be able to use that information in subsequent views/templates.
If anybody can point me to a tutorial online or post some sample code, that would be great.
I'm using django 1.1 and Python 2.6
If you don't want persistent storage of user data (just additional session data) have a look at:
http://docs.djangoproject.com/en/dev/topics/http/sessions/
The sessions framework will most probably be already enabled if you use django.contrib.auth.
If you want persistent storage of additional user data (not only in a session, but in the database), you will store them in another "profile" model:
http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users
I realize #stefanw provided you an alternative solution, but to answer the original question:
Setting session data at login is difficult because the easiest place to set that data is in your view function, and the particular view function you'd want to modify is a part of the contrib.django.auth app.
So your options would be the following:
Create a small middleware class to set your session data.
Create a template tag or other bit of code than can be integrated into the login template or subsequent page that will set the data you want.
Write your own custom login view function (it's really quite easy, actually).
Happy django-ing!