k4ever/k4ever/api2/authentication.py

70 lines
2.1 KiB
Python
Raw Normal View History

2012-01-21 00:21:29 +01:00
# 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
2011-10-02 17:58:54 +02:00
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
class DjangoAuthentication(object):
"""
2012-05-26 17:55:46 +02:00
Authenticate against djangos own authentication backend
2011-10-02 17:58:54 +02:00
"""
2012-05-26 17:55:46 +02:00
2011-10-02 17:58:54 +02:00
def is_authenticated(self, request):
2012-05-26 17:55:46 +02:00
""" Check, if user is already authenticated.
2011-10-02 17:58:54 +02:00
2012-05-26 17:55:46 +02:00
From piston docs:
2011-10-02 17:58:54 +02:00
`is_authenticated`: Will be called when checking for
2012-05-26 17:55:46 +02:00
authentication. Receives a `request` object, please
set your `User` object on `request.user`, otherwise
return False (or something that evaluates to False.)
2011-10-02 17:58:54 +02:00
"""
self.request = request
return request.user.is_authenticated()
2012-05-26 17:55:46 +02:00
2011-10-02 17:58:54 +02:00
def challenge(self):
2012-05-26 17:55:46 +02:00
""" Redirect unauthenticated requests to login form
From piston docs
2011-10-02 17:58:54 +02:00
`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.
"""
2012-05-26 17:55:46 +02:00
loginPage = "%s?%s=%s" % (
settings.LOGIN_URL,
REDIRECT_FIELD_NAME,
urlquote(self.request.get_full_path()),
)
return HttpResponseRedirect(loginPage)
2011-10-02 17:58:54 +02:00
class MultiAuthentication(object):
2012-05-26 17:55:46 +02:00
""" """
def __init__(self, authenticators):
if len(authenticators) ==0:
raise ValueError("MultiAuthentication needs at least one authenticator in list")
self.authenticators = authenticators
self.currentAuthenticator = self.authenticators[0]
2011-10-02 17:58:54 +02:00
def is_authenticated(self, request):
2012-05-26 17:55:46 +02:00
""" Try to authenticate against all given authenticators. """
for authenticator in self.authenticators:
if authenticator.is_authenticated(request):
# success!
self.currentAuthenticator = authenticator
return True
return False
2011-10-02 17:58:54 +02:00
def challenge(self):
2012-05-26 17:55:46 +02:00
""" Return challenge for current or default authenticator. """
return self.currentAuthenticator.challenge()
2011-10-02 17:58:54 +02:00