1 from forum.authentication.base import AuthenticationConsumer, ConsumerTemplateContext, InvalidAuthentication
2 from forum.models import User
3 from forum.actions import UserJoinsAction
4 from django.utils.translation import ugettext as _
5 from forum import settings
7 class LDAPAuthConsumer(AuthenticationConsumer):
9 def process_authentication_request(self, request):
10 username = request.POST['username'].strip()
11 password = request.POST['password']
12 uid = str(settings.LDAP_USER_MASK) % username
14 #an empty password will cause ldap to try an anonymous bind. This is picked up here
16 raise InvalidAuthentication(_('Login failed. Please enter valid username and password (both are case-sensitive)'))
18 ldapo = ldap.initialize(str(settings.LDAP_SERVER))
19 if(settings.LDAP_USE_TLS):
21 ldapo.set_option(ldap.OPT_PROTOCOL_VERSION, 3)
23 ldapo.simple_bind_s(str(settings.LDAP_BIND_DN), str(settings.LDAP_BIND_SECRET))
24 search = ldapo.search_s(str(settings.LDAP_BASE_DN), ldap.SCOPE_SUBTREE, uid)
25 except ldap.LDAPError:
26 #could not bind using credentials specified in ldap config
27 raise InvalidAuthentication(_('Login failed - LDAP bind error. Please contact your system administrator'))
33 raise InvalidAuthentication(_('Login failed. Please enter valid username and password (both are case-sensitive)'))
35 #now try to bind as selected user; should raise exception if bind fails
36 ldapo = ldap.initialize(str(settings.LDAP_SERVER))
37 if(settings.LDAP_USE_TLS):
39 ldapo.set_option(ldap.OPT_PROTOCOL_VERSION, 3)
41 ldapo.simple_bind_s(search[0][1][str(settings.LDAP_DN)][0],password)
42 except ldap.LDAPError:
43 #could not bind as user - password is incorrect
44 raise InvalidAuthentication(_('Login failed. Please enter valid username and password (both are case-sensitive)'))
48 return User.objects.get(username=username)
49 except User.DoesNotExist:
50 userinfo = search[0][1]
51 _user = User( username = userinfo[str(settings.LDAP_UID)][0],
52 email = userinfo[str(settings.LDAP_MAIL)][0],
53 real_name = userinfo[str(settings.LDAP_NAME)][0] )
54 _user.email_isvalid = True
55 _user.set_unusable_password()
57 UserJoinsAction(user=_user, ip=request.META['REMOTE_ADDR']).save()
60 class LDAPAuthContext(ConsumerTemplateContext):
63 human_name = 'LDAP authentication'
64 stack_item_template = 'modules/ldapauth/loginform.html'
65 show_to_logged_in_user = False