Alternative Authentifizierung

Eine alternative Authentifizierung kann man in der Datei userauth/backends.py wie folgt implementieren:

from django.conf import settings
from django.contrib.auth.models import User, check_password


class SettingsBackend():
    """Authenticate against the settings ADMIN_LOGIN and ADMIN_PASSWORD.

    Use the login name, and a hash of the password. This example uses "admin"
    as username and password:

    ADMIN_LOGIN = 'admin'
    ADMIN_PASSWORD = 'sha1$4e987$afec41beb01610c713124cac668d0becc75b4d4c'
    """
    def authenticate(self, username=None, password=None):
        login_valid = (settings.ADMIN_LOGIN == username)
        pwd_valid = check_password(password, settings.ADMIN_PASSWORD)
        if login_valid and pwd_valid:
            try:
                user = User.objects.get(username=username)
            except User.DoesNotExist:
                # Create a new user. Note that we can set password
                # to anything, because it won't be checked; the password
                # from settings.py will.
                user = User(username=username, password='get from settings.py')
                user.is_staff = False
                user.is_superuser = False
                user.save()
            return user
        return None

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None

Bemerkung

SettingsBackend nutzt das UserProfile zum Speichern zusätzlicher Informationen.

Um das SettingsBackend zu verwenden muss in cookbook/settings.py folgende Einstellung hinzugefügt werden:

AUTHENTICATION_BACKENDS = (
    'django.contrib.auth.backends.ModelBackend',
    'cookbook.userauth.backends.SettingsBackend'
)

Inhalt

Vorheriges Thema

RESTful Webservice

Nächstes Thema

Caching

Diese Seite