Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: is there a way to know if a url is valid in the application?

Tags:

python

django

Here's my goal:

  • the user wants to login
  • I make a button on each page with the urlback as a parameter, for example if we are on the page http://olivier.life/today, the button to login will have an url like http://olivier.life/login?back=today
  • the user logs in
  • once the user is logged in, i check if there's a "back" in the "GET" request. if so then I make a redirect to the url in the GET

My problem is a security problem: I just want to know if the URL in the GET is part of my application (is valid for one of the URLs in the urls.py file).

How to do this?

like image 299
Olivier Pons Avatar asked Oct 13 '25 10:10

Olivier Pons


1 Answers

Use resolve. There's an example that's very close to this use case in the docs. I think for your case you want something like:

def some_view(request):
    redirect_target = request.GET.get('back')
    if redirect_target:
        try:
            resolve_match = django.core.urlresolvers.resolve(redirect_target)
        except django.core.urlresolvers.Resolver404:
            # do something on bad input
        else:
            return django.shortcuts.redirect(redirect_target)
    else:
        # empty string redirect target, or not provided at all
        # do something else
like image 165
Peter DeGlopper Avatar answered Oct 15 '25 00:10

Peter DeGlopper