Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 1 #LDAP module that allows AD authentication in the techanswers website
- 2 import ldap
- 3 from forum.authentication.base import AuthenticationConsumer, InvalidAuthentication, ConsumerTemplateContext
- 4 from forms import ClassicLoginForm
- 5 from forum.models import User
- 6
- 7 # ACTIVE DIRECTORY SETTINGS
- 8 AD_DNS_NAME = 'example.com'
- 9 #AD_LDAP_PORT = 389 # port number
- 10 AD_SEARCH_DN = 'ou=people,dc=example,dc=com'#ask somebody for search domain
- 11 #AD_LDAP_URL = 'ldaps://%s:%s' % (AD_DNS_NAME,AD_LDAP_PORT)#in case we have a port number
- 12 AD_LDAP_URL = 'ldap://' + AD_DNS_NAME #no port specified,use default port
- 13
- 14 class LocalAuthConsumer(AuthenticationConsumer):
- 15 def process_authentication_request(self, request):
- 16 try:
- 17 # Autenticate user in LDAP
- 18 con = ldap.initialize(AD_LDAP_URL)
- 19 username = request.POST.get('username', None)
- 20 password = request.POST.get('password', None)
- 21 if not (username and password)
- 23 raise InvalidAuthentication("Invalid data")
- 24 dn = "%s@%s" @ (username, AD_DNS_NAME)
- 25 con.simple_bind_s(dn, password)
- 26 con.unbind_s()
- 27 try:# If user is in datatbase carry on
- 28 user = User.obejcts.get(username=username)
- 29 except User.DoesNotExist:# not in the database add user to database
- 30 user = User(username=username, email=dn)
- user.set_unusable_password()
- user.save()
- 31 return user
- 32 # Case the user is not authentic or something goes wrong
- 33 except ldap.NO_SUCH_OBJECT, e:
- 34 con.unbind_s()
- 35 #return None
- 36 raise InvalidAuthentication("The user does not exist")
- 37 except ldap.INVALID_CREDENTIALS, e:
- 38 con.unbind_s()
- 39 #return None
- 40 raise InvalidAuthentication("Invalid username or password")
- 41 except ldap.LDAPError, e:
- 42 con.unbind_s()
- 43 #return None
- 44 raise InvalidAuthentication("LDAP error")
- 45
- 46 class LocalAuthContext(ConsumerTemplateContext):
- 47 mode = 'STACK_ITEM'
- 48 weight = 1000
- 49 human_name = 'AD authentication'
- 50 stack_item_template = 'modules/localauth/loginform.html'
- 51 show_to_logged_in_user = False
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement