In my model File I have a pointer and a group field. Only when an authenticated user is in one of the groups of group access is allowed to the file in pointer.
from django.db import models
from django.contrib.auth.models import Group
class File(models.Model):
pointer = models.FileField()
group = models.ManyToManyField(Group)
Now I want Apache to follow this by using the Django authorisation. For this I’ve written a middleware script in Django which works fine when using the Django test webserver (python manage.py runserver).
from django.http import HttpRequest, HttpResponseForbidden
from .models import File
class MediaAccessMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request: HttpRequest):
if request.path_info.startswith('/media/'):
if not request.user.is_authenticated:
return HttpResponseForbidden('You may not enter...')
else:
path = request.path_info.strip('/media/')
file = File.objects.filter(pointer=path)
if file:
f_groups = file[0].group
f_set = set(f_groups.values_list('name', flat=True))
else:
f_set = set()
ug_set = set(request.user.groups.values_list('name', flat=True))
if not ug_set.intersection(f_set):
return HttpResponseForbidden('Access denied because you\'re not in the right group')
return self.get_response(request)
However I cannot get this to work with Apache using mod_wsgi. Below is an excerpt of my Apache conf-script:
WSGIDaemonProcess ${url} python-home=${envPath} python-path=${basePath}:${projectPath} user=${userName} group=${groupName}
WSGIScriptAlias /${url} ${projectPath}/wsgi.py process-group=${url}
WSGIApplicationGroup %{GLOBAL}
<Location /${url}>
WSGIProcessGroup ${url}
</Location>
Alias /${url}/media/ ${mediaPath}
<Directory ${mediaPath}>
Require valid-user
AuthBasicProvider wsgi
WSGIAuthUserScript ${projectPath}/wsgi.py
</Directory>
<Location "/${url}/secret">
AuthType Basic
AuthName "Top Secret"
Require valid-user
AuthBasicProvider wsgi
WSGIAuthUserScript ${projectPath}/wsgi.py
</Location>
<Directory ${projectPath}>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
Can someone help me with this?
Kind regards,
Ronald