I am in the process of editing the authentication.py file following the LDAP part 2 instructions. I just need some clarification on how to do this exactly. Will simply replacing the contents of the file, allow LDAP auth to start working if I have python-ldap already installed?
Here is the current file/path:
/opt/questions/qa/apps/osqa/forum_modules/localauth$
from forum.authentication.base import AuthenticationConsumer, ConsumerTemplateContext, InvalidAuthentication
from forms import ClassicLoginForm
class LocalAuthConsumer(AuthenticationConsumer):
def process_authentication_request(self, request):
form_auth = ClassicLoginForm(request.POST)
if form_auth.is_valid():
return form_auth.get_user()
else:
raise InvalidAuthentication(" ".join(form_auth.errors.values()[0]))
class LocalAuthContext(ConsumerTemplateContext):
mode = 'STACK_ITEM'
weight = 1000
human_name = 'Local authentication'
stack_item_template = 'modules/localauth/loginform.html'
show_to_logged_in_user = False
What is suggested on the DLAP part 2 page (where I am a bit confused).
import ldap
from forum.authentication.base import AuthenticationConsumer, InvalidAuthentication, ConsumerTemplateContext
from forms import ClassicLoginForm
from forum.models import User
# ACTIVE DIRECTORY SETTINGS
AD_DNS_NAME = 'domain.net'
AD_LDAP_URL = 'ldap://%s' % (AD_DNS_NAME) #no port specified, default port use
class LocalAuthConsumer(AuthenticationConsumer):
def process_authentication_request(self, request):
try:
# Autenticate user in LDAP
con = ldap.initialize(AD_LDAP_URL)
username = request.POST.get('username', None)
password = request.POST.get('password', None)
base_dn = 'ou=All Users,dc=domain,dc=com,dc=au'
filter = '(sAMAccountName=' + username + ')'
attrs = ['mail']
if not (username and password):
raise InvalidAuthentication("Invalid data")
dn = '%s@%s' % (username, AD_DNS_NAME)
#careful there might be a bug here use regex to filter special chars
#ldap behaves wierd with special chars
con.simple_bind_s(dn, password)
mailsearch = con.search_s(base_dn, ldap.SCOPE_SUBTREE, filter, attrs )[0][1]
emailaddress = mailsearch['mail'][0]
con.unbind_s()
try:# If user is in datatbase carry on
user = User.objects.get(username=username)
except User.DoesNotExist:# not in the database add user to database
user = User(username=username, email=emailaddress)
user.set_unusable_password()
user.save()
return user
# Case the user is not authentic or something goes wrong
except ldap.NO_SUCH_OBJECT, e:
con.unbind_s()
raise InvalidAuthentication("The user does not exist")
except ldap.INVALID_CREDENTIALS, e:
con.unbind_s()
raise InvalidAuthentication("Invalid username or password")
except ldap.LDAPError, e:
con.unbind_s()
raise InvalidAuthentication("LDAP error")
class LocalAuthContext(ConsumerTemplateContext):
mode = 'STACK_ITEM'
weight = 1000
human_name = 'AD authentication'
stack_item_template = 'modules/localauth/loginform.html'
show_to_logged_in_user = False