# Authentication backend using a Windows NT domain controller.
# To activate, store this file as mysite/winauth.py and use:
# AUTHENTICATION_BACKENDS = ('mysite.winauth.DomainControllerAuthBackend',)
# in your settings.conf.
#
# Needs pywin32 extensions installed (and obviously only runs on Windows).
# Author: Bastian Kleineidam
from django.contrib.auth.models import User
from django.contrib.auth.backends import ModelBackend
import win32security
# Adjust this (you can also store it in settings.py)
DEFAULT_DOMAIN = "INTRANET"
class DomainControllerAuthBackend (ModelBackend):
"""Backend which verifies passwords against a Windows domain controller,
except superusers where the model password is checked."""
def authenticate (self, username=None, password=None):
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
return None
if user.is_superuser:
# superusers are local users, so check native password
if user.check_password(password):
return user
elif auth(username, password):
return user
return None
def auth (username, password, domain=DEFAULT_DOMAIN):
"""Authenticates user credentials to a Windows domain controller
Return True if user is authenticated, else False."""
try:
return win32security.LogonUser(
username, domain, password, win32security.LOGON32_LOGON_NETWORK,
win32security.LOGON32_PROVIDER_DEFAULT)
except win32security.error, msg:
# error should be logged, ignore it in this snippet for simplicity
pass
return False
Comments