1

I am working on a loginMiddleware class for Django. This middleware class must send a user to the login page when it's not logedin. But there are a few exceptions.

Because i run the build-in django server i had to make a media url. But know is de problem that when the login page loads a javascript file, the javascript file is the loginpage, because the user isn't logedin. Because of that reason i made a statement:

from django.http import HttpResponseRedirect
from django.conf import settings
import re
class loginMiddelware:
    def process_request(self,request):
        if request.path != settings.LOGIN_PATH and request.user.is_anonymous():
            if request.path.find('media') <= 0:
                return HttpResponseRedirect(settings.LOGIN_PATH)
            else:
                return None

I mean the line with: if request.path.find('media') <= 0:. It works, but i don't find this a good method. I think that i must use a regex for that. So i looked to the re.match function, and tried different thinks, but nothing worked. I want a regex what allows only al urls beginning with /media/ and ending with one of the next extentions: js, css, png, gif or jpg.

How is this posible?

Thanx!

Tom

3 Answers 3

3

Sure:

DIRECT_ACCESS = re.compile(r'^/media/.*\.(js|css|png|gif|jpg)$')

...

if DIRECT_ACCESS.match(url):
    ...

Hint: If you want to make sure your regexp works, write a couple of unit tests that execute it. That way, you won't get any nasty surprises.

Sign up to request clarification or add additional context in comments.

Comments

2

You don't need a regex:

if request.path.startswith('/path/to/your/media'):
    #do something

should do the trick. You are complaining about the fact, that if the request path contains:

/protected/secure/media/bla

that your implentation will let the user through.

So using a absolute path with the string method startswith is sufficient for your problem.

Comments

1

Take a look at Matt Grayson's Require Login Middleware. It lets you define a bunch of URLs that do not require logging in using a custom LOGIN_REQUIRED_URLS_EXCEPTIONS setting.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.