Advertisement
Guest User

Untitled

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