I used the code from http://djangosnippets.org/snippets/901/ and expanded the code to have the possibility to map AD groups to the superuser attribute of Django's users. The code updates the Django users database every time a user connects, so every change in the AD is replicated to the Django database.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 | ### settings.py ###
# active directory authentication module
AD_DNS_NAME = 'dc.com' # FQDN of your DC
If using non-SSL use these
#AD_LDAP_PORT=389
#AD_LDAP_URL='ldap://%s:%s' %
(AD_DNS_NAME,AD_LDAP_PORT)
# If using SSL use these:
AD_LDAP_PORT=636
AD_LDAP_URL='ldaps://%s:%s' % (AD_DNS_NAME,AD_LDAP_PORT)
AD_SEARCH_DN = 'ou=Staff,dc=example,dc=com'
AD_NT4_DOMAIN = 'YOURDOMAIN'
AD_SEARCH_FIELDS = ['mail','givenName','sn','sAMAccountName','memberOf']
AD_MEMBERSHIP_ADMIN = ['admingroup'] # this ad group gets superuser status in django
AD_MEMBERSHIP_REQ = AD_MEMBERSHIP_ADMIN + ['anothergroup', 'secondarygroup'] # only members of this group can access
AD_CERT_FILE = '/path/to/certile.pem' # this is the certificate of the Certificate Authority issuing your DCs certificate
AD_DEBUG=True
AD_DEBUG_FILE='/tmp/ldap.debug'
AUTHENTICATION_BACKENDS = (
'... .backend.ActiveDirectoryAuthenticationBackend',
'django.contrib.auth.backends.ModelBackend'
)
### backend.py ###
import ldap
import os
import re
import datetime
from django.conf import settings
from django.contrib.auth.models import User
class ActiveDirectoryAuthenticationBackend:
"""
This authentication backend authenticates against Active directory.
It updates the user objects according to the settings in the AD and is
able to map specific groups to give users admin rights.
"""
def __init__(self):
""" initialise a debuging if enabled """
self.debug = settings.AD_DEBUG
if len(settings.AD_DEBUG_FILE) > 0 and self.debug:
self.debugFile = settings.AD_DEBUG_FILE
# is the debug file accessible?
if not os.path.exists(self.debugFile):
open(self.debugFile,'w').close()
elif not os.access(self.debugFile, os.W_OK):
raise IOError("Debug File is not writable")
else:
self.debugFile = None
def authenticate(self,username=None,password=None):
try:
if len(password) == 0:
return None
ldap.set_option(ldap.OPT_X_TLS_CACERTFILE,settings.AD_CERT_FILE)
l = ldap.initialize(settings.AD_LDAP_URL)
l.set_option(ldap.OPT_PROTOCOL_VERSION, 3)
binddn = "%s@%s" % (username,settings.AD_NT4_DOMAIN)
l.simple_bind_s(binddn,password)
l.unbind_s()
return self.get_or_create_user(username,password)
except ImportError:
self.debug_write('import error in authenticate')
except ldap.INVALID_CREDENTIALS:
self.debug_write('%s: Invalid Credentials' % username)
def get_or_create_user(self, username, password):
""" create or update the User object """
# get user info from AD
userInfo = self.get_user_info(username, password)
# is there already a user?
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
if userInfo is not None:
user = User(username=username, password=password)
self.debug_write('create new user %s' % username)
## update the user objects
# group mapping for the access rights
if userInfo['isAdmin']:
user.is_staff = True
user.is_superuser = True
elif userInfo:
user.is_staff = False
user.is_superuser = False
else:
user.is_active = False
# personal data
user.first_name = userInfo['first_name']
user.last_name = userInfo['last_name']
user.mail = userInfo['mail']
# cache the AD password
user.set_password(password)
user.save()
return user
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
def debug_write(self,message):
""" handle debug messages """
if self.debugFile is not None:
fObj = open(self.debugFile, 'a')
now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M')
fObj.write("%s\t%s\n" % (now,message))
fObj.close()
def check_group(self,membership):
""" evaluate ADS group memberships """
self.debug_write("Evaluating group membership")
isValid = False
isAdmin = False
pattern = re.compile(r'^CN=(?P<groupName>[\w|\d]+),')
for group in membership:
groupMatch = pattern.match(group)
if groupMatch:
thisGroup = groupMatch.group('groupName')
if thisGroup in settings.AD_MEMBERSHIP_REQ:
isValid = True
if thisGroup in settings.AD_MEMBERSHIP_ADMIN:
isAdmin = True
if isAdmin:
self.debug_write('is admin user')
elif isValid:
self.debug_write('is normal user')
else:
self.debug_write('does not have the AD group membership needed')
return isAdmin, isValid
def get_user_info(self, username, password):
""" get user info from ADS to a dictionary """
try:
userInfo = {
'username' : username,
'password' : password,
}
# prepare LDAP connection
ldap.set_option(ldap.OPT_X_TLS_CACERTFILE,settings.AD_CERT_FILE)
ldap.set_option(ldap.OPT_REFERRALS,0) # DO NOT TURN THIS OFF OR SEARCH WON'T WORK!
# initialize
self.debug_write('ldap.initialize...')
l = ldap.initialize(settings.AD_LDAP_URL)
l.set_option(ldap.OPT_PROTOCOL_VERSION, 3)
# bind
binddn = "%s@%s" % (username,settings.AD_NT4_DOMAIN)
self.debug_write('ldap.bind %s' % binddn)
l.bind_s(binddn,password)
# search
self.debug_write('search...')
result = l.search_ext_s(settings.AD_SEARCH_DN,ldap.SCOPE_SUBTREE,"sAMAccountName=%s" % username,settings.AD_SEARCH_FIELDS)[0][1]
self.debug_write("results in %s" % result)
# Validate that they are a member of review board group
if result.has_key('memberOf'):
membership = result['memberOf']
else:
self.debug_write('AD user has no group memberships')
return None
# user ADS Groups
isAdmin, isValid = self.check_group(membership)
if not isValid:
return None
userInfo['isAdmin'] = isAdmin
# get user info from ADS
# get email
if result.has_key('mail'):
mail = result['mail'][0]
else:
mail = ""
userInfo['mail'] = mail
self.debug_write("mail=%s" % mail)
# get surname
if result.has_key('sn'):
last_name = result['sn'][0]
else:
last_name = None
userInfo['last_name'] = last_name
self.debug_write("sn=%s" % last_name)
# get display name
if result.has_key('givenName'):
first_name = result['givenName'][0]
else:
first_name = None
userInfo['first_name'] = first_name
self.debug_write("first_name=%s" % first_name)
# LDAP unbind
l.unbind_s()
return userInfo
except Exception, e:
self.debug_write("exception caught!")
self.debug_write(e)
return None
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Please login first before commenting.