Evgenii Legotckoi
Evgenii LegotckoiSept. 11, 2023, 4:47 p.m.

Django - Protected media content

On one of the resources that I am developing, there was a need to add protected access to media content, checking the user's right to access this media content. Simply put, can the user view the photo that nginx serves as static content.

In fact, in the case of nginx and django, everything is much simpler than it seems at first glance.

Let's look at this using the example of uploading and uploading a photo.

Algorithm for working with photography

  • Uploading a photo to a special protected directory
  • An attempt to get a photo via a direct url to a photo or in a website page (for example, an img tag)
  • Checking photo permissions
  • Creating a redirect in nginx to an internal protected directory on the server
  • Receiving a photo

Everything seems simple, but now let's see what is required for this.

settings.py

Let's set up the site's django configuration file. Usually, to download media content and automatically serve it via nginx, something similar is written in the settings.

MEDIA_ROOT = BASE_DIR.parent / 'media'
MEDIA_URL = '/media/'

However, this time we are using a special protected directory, which I always call protected .

MEDIA_ROOT = BASE_DIR.parent / 'protected'
MEDIA_URL = '/media/'

Thus, we say that in the external space we have "media" , and in the dark halls of the server it is "protected" .

Such code might correspond to the following directory structure.

  • /home/www/django_project_root_folder - this is the main directory where the project, static and honey directories, as well as the virtual environment are located
  • /home/www/django_project_root_folder/protected - protected media directory
  • /home/www/django_project_root_folder/static - directory with static content
  • /home/www/django_project_root_folder/django_project - your django application
  • /home/www/django_project_root_folder/python_venv - virtual environment

I currently like this structure, because if the python version changes, that is, the virtual environment is updated, you can simply initialize the new environment and change a couple of lines in the configuration so that the site application is launched from the new virtual environment. In this case, neither the project repository, nor static files, nor media content will be affected.

Configuration nginx

I will give a small piece of configuration that is directly responsible for setting up nginx access to the protected directory

 server {

     # Other code

     location /protected/ {
        internal;
        root /home/www/django_project_root_folder/;
        expires 30d;
    }
}

With this code we simply indicate where the protected directory is located and that it is internal, that is, the user will not simply receive its contents without special permission.

Uploading photos

To work with photographs, I currently use this data model, of course with modifications for a specific project, but the basis is the same

# -*- coding: utf-8 -*-

import os
import uuid

from django.contrib.gis.db import models
from django.db.models.signals import post_delete
from django.dispatch import receiver
from django.utils.translation import gettext_lazy as _

from photo.fields import WEBPField
from photo.managers import PhotoManager


def image_folder(instance, filename):
    return 'photos/{}.webp'.format(uuid.uuid4().hex)


class Photo(models.Model):
    class Meta:
        verbose_name = _('Photo')
        verbose_name_plural = _('Photos')

    created_at = models.DateTimeField(verbose_name=_('Created at'), auto_now_add=True)
    updated_at = models.DateTimeField(verbose_name=_('Updated at'), auto_now=True)
    height = models.IntegerField(verbose_name=_('Height'), default=0, blank=True, null=True)
    width = models.IntegerField(verbose_name=_('Width'), default=0, blank=True, null=True)
    image = WEBPField(
        verbose_name=_('Image'),
        upload_to=image_folder,
        height_field='height',
        width_field='width',
    )

    def filename(self):
        return os.path.basename(self.image.name)


@receiver(post_delete, sender=Photo)
def auto_delete_image_on_delete(sender, instance, **kwargs):
    if instance.image:
        if os.path.isfile(instance.image.path):
            os.remove(instance.image.path)

A special field WEBPField is used here, which I have already talked about. This is a field that converts an image to webp format on the fly. There is also code for automatically deleting photos from the server. But this is not the most important thing.

The most important thing is this function

def image_folder(instance, filename):
    return 'photos/{}.webp'.format(uuid.uuid4().hex)

This function generates a file name and indicates where to save the file on the server relative to the protected directory.

As a result, the photo will be saved in the following path

/home/www/django_project_root_folder/protected/photos/0aec484a6ff246d7ad5eb1b06c0a698e.webp

In this case, the code for the img tag in the template will look like this:

<img src="{{ photo.image.url }}"/>

And the result will look like this

<img src="/media/photos/0aec484a6ff246d7ad5eb1b06c0a698e.webp"/>

## urls.py

I'll start by specifying the url manager to access the content

# -*- coding: utf-8 -*-

from django.urls import path

from photo.views import photo_access

urlpatterns = [
    path('media/photos/<str:path>', photo_access, name='photo'),
]

As you can see, here is a url that matches the result for the img tag.

Function photo_access

And now the most interesting thing is how exactly access to protected content is carried out

# -*- coding: utf-8 -*-

from django.http import HttpResponse, HttpResponseForbidden

from photo.models import Photo
from utils.shortcuts import get_object_or_none


def photo_access(request, path):
    def create_x_accel_redirect(path):
        response = HttpResponse()
        # Content-type will be detected by nginx
        del response['Content-Type']
        response['X-Accel-Redirect'] = '/protected/photos/' + path
        return response

    photo = get_object_or_none(Photo, image='photos/' + path)
    if photo is None:
        return HttpResponseForbidden('Not authorized to access this media.')

    # Some another check code
    if condition is True:
        return create_x_accel_redirect(path)

    if request.user.is_authenticated and request.user.is_staff:
        return create_x_accel_redirect(path)

    return HttpResponseForbidden('Not authorized to access this media.')

In this function, we check whether the user is an authorized representative of the resource administration and whether the photo object exists. You can also add any other conditions you like.

If they are executed, then using the create_x_accel_redirect function we add a directive that redirects the request inside nginx to the image.

That is, we replace /media/photos/0aec484a6ff246d7ad5eb1b06c0a698e.webp with /protected/photos/0aec484a6ff246d7ad5eb1b06c0a698e.webp and redirect the request with the X-Accel-Redirect directive.
Thus, nginx serves content from a protected directory via media url.

More details about the X-Accel-Redirect directive can be found on the official nginx wiki

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
m

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:80points,
  • Rating points4
m

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:20points,
  • Rating points-10

C++ - Тест 003. Условия и циклы

  • Result:42points,
  • Rating points-8
Last comments
A
ALO1ZEOct. 19, 2024, 8:19 a.m.
Fb3 file reader on Qt Creator Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
ИМ
Игорь МаксимовOct. 5, 2024, 7:51 a.m.
Django - Lesson 064. How to write a Python Markdown extension Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
d
dblas5July 5, 2024, 11:02 a.m.
QML - Lesson 016. SQLite database and the working with it in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
k
kmssrFeb. 8, 2024, 6:43 p.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
Now discuss on the forum
jd
jasmine disouzaOct. 28, 2024, 4:58 a.m.
GeForce Now India: Unlocking the Future of Cloud Gaming GeForce Now India has a major impact on the gaming scene by introducing NVIDIA's cloud gaming service to Indian gamers. GeForce Now India lets you stream top-notch PC games on any device, from b…
9
9AnonimOct. 25, 2024, 9:10 a.m.
Машина тьюринга // Начальное состояние 0 0, ,<,1 // Переход в состояние 1 при пустом символе 0,0,>,0 // Остаемся в состоянии 0, двигаясь вправо при встрече 0 0,1,>…
J
JacobFibOct. 17, 2024, 3:27 a.m.
добавить qlineseries в функции Пользователь может получить любые разъяснения по интересующим вопросам, касающимся обработки его персональных данных, обратившись к Оператору с помощью электронной почты https://topdecorpro.ru…
JW
Jhon WickOct. 1, 2024, 3:52 p.m.
Indian Food Restaurant In Columbus OH| Layla’s Kitchen Indian Restaurant If you're looking for a truly authentic https://www.laylaskitchenrestaurantohio.com/ , Layla’s Kitchen Indian Restaurant is your go-to destination. Located at 6152 Cleveland Ave, Colu…

Follow us in social networks