You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
k4ever/k4ever/api2/authentication.py

76 lines
2.5 KiB

# This file is part of k4ever, a point-of-sale system
# Contact............ <k4ever@lists.someserver.de>
# Website............ http://k4ever.someserver.de/
# Bug tracker........ http://k4ever.someserver.de/report
#
# Licensed under GNU Affero General Public License v3 or later
from django.conf import settings
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.http import HttpResponse, HttpResponseRedirect
from django.utils.http import urlquote
# taken and modified from
# https://bitbucket.org/yml/django-piston/src/dfb826a31ca8/piston/authentication.py
class DjangoAuthentication(object):
"""
Django authentication.
"""
def __init__(self, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
if not login_url:
login_url = settings.LOGIN_URL
self.login_url = login_url
self.redirect_field_name = redirect_field_name
self.request = None
def is_authenticated(self, request):
"""
This method call the `is_authenticated` method of django
User in django.contrib.auth.models.
`is_authenticated`: Will be called when checking for
authentication. It returns True if the user is authenticated
False otherwise.
"""
self.request = request
return request.user.is_authenticated()
def challenge(self):
"""
`challenge`: In cases where `is_authenticated` returns
False, the result of this method will be returned.
This will usually be a `HttpResponse` object with
some kind of challenge headers and 401 code on it.
"""
path = urlquote(self.request.get_full_path())
tup = self.login_url, self.redirect_field_name, path
return HttpResponseRedirect('%s?%s=%s' %tup)
# taken from
# http://staer.github.com/2011/01/21/piston-multi-auth.html
class MultiAuthentication(object):
""" Authenticated Django-Piston against multiple types of authentication """
def __init__(self, auth_types):
""" Takes a list of authenication objects to try against, the default
authentication type to try is the first in the list. """
self.auth_types = auth_types
self.selected_auth = auth_types[0]
def is_authenticated(self, request):
""" Try each authentication type in order and use the first that succeeds """
authenticated = False
for auth in self.auth_types:
authenticated = auth.is_authenticated(request)
if authenticated:
selected_auth = auth
break
return authenticated
def challenge(self):
""" Return the challenge for whatever the selected auth type is (or the default
auth type which is the first in the list)"""
return self.selected_auth.challenge()