django supplying login credentials in any view url
Question
Is there any way in django to perform login using credentials supplied while accessing any view in the application?
My motivation here is availability monitoring using a service such as Pingdom. Most of the urls I want to validated their availability are decorated with a @login_required
which makes it impossible to access unless I have previously logged in.
My idea solution will be a way to access my views while supplying credentials in GET or POST parameters. Another alternative could probably be a site uptime monitoring service that supports logging in and acquiring a session prior to accessing the URL in question.
Update
Thanks to @Filip Dupanović's direction and the code from here my simple working middleware looks like this:
from django.contrib.auth import authenticate, login
class AuthenticationEverywhereMiddleware(object):
"""
Middleware to allow logging in by supplying login credentials in any URL
"""
def process_request(self, request):
if (request.GET.get('authenticateEverywhere','') == 'GET'):
username = request.GET['username']
password = request.GET['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
I have added the triggering parameter authenticateEverywhere
to prevent any possible clashes with views that might use username
or password
parameters.
Solution
You most certainly can! You'll need to write a custom middleware class that implements a custom process_request
method where you'll be able to inspect the request object, obtain the credentials and sign the user in before the request gets routed to a view that's decorated with login_required
.