views:

66

answers:

3

Hello everybody,

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

+1  A: 

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.

Manoj Govindan
thank you. this is also a way how i can do it.
Tom
+3  A: 

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.

Aaron Digulla
thank you. it works. i will write a few tests!
Tom
+2  A: 

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.

zovision