import logging
import traceback
from django.conf import settings
from django.contrib.auth.hashers import check_password
from django.contrib.auth.models import User
from ldap3 import Server, Connection, ALL, NTLM, ALL_ATTRIBUTES
from ldap3.core.exceptions import LDAPSocketOpenError
import mysite.settings

class LdapBackend(object):
    """
    Authenticate against a LDAP directory.
    """

    log = logging.getLogger('mysite')

    def check_login(self, username, password):
        server = Server(mysite.settings.LDAP_SERVER, connect_timeout=8)
        qualified_user = mysite.settings.LDAP_DOMAIN + '\\' + username

        conn = Connection(server, qualified_user, password=password, authentication=NTLM)

        try:
            conn.bind()
        except LDAPSocketOpenError:
            # LDAP Server nicht erreichbar
            self.log.info("LDAP check_login: Server not reachable.")
            return None
        except:
            var = traceback.format_exc()
            self.log.info("LDAP check_login(bind): Unexpected Error %s" % var)
            return None

        result = None

        try:
            if conn.extend.standard.who_am_i() != None:
                conn.search(
                    search_base='DC=' + mysite.settings.LDAP_DOMAIN + ',DC=fh-nuernberg,DC=de',
                    search_filter='(&(objectclass=user)(CN=' + username + '))', attributes=ALL_ATTRIBUTES)
                info = conn.entries[0]
                result = {'lastname' : str(info.sn),
                          'givenname' : str(info.givenName),
                          'login' : str(info.cn),
                          'department' : str(info.department),
                          'role' : str(info.description)}
                self.log.info("LDAP check_login: %s" % result)
        except:
            var = traceback.format_exc()
            self.log.info("LDAP check_login: Unexpected Error %s" % var)
        conn.unbind()
        return result



    def authenticate(self, request, username=None, password=None):
        ldap_user = self.check_login(username,password)
        if ldap_user:
            # {'lastname': 'Hofmann', 'givenname': 'Oliver', 'login': 'hofmannol', 'department': 'EFI', 'role': 'PF'}
            # {'lastname': 'Wimmer', 'givenname': 'Martin', 'login': 'wimmerma', 'department': 'EFI', 'role': 'MA'}
            # {'lastname': 'Mueller', 'givenname': 'Vincent', 'login': 'muellervi56608', 'department': 'EFI', 'role': 'ST'}
            # {'lastname': 'Poehlau', 'givenname': 'Frank', 'login': 'poehlaufr', 'department': 'EFI', 'role': 'PF'}
            try:
                user = User.objects.get(username=ldap_user['login'])
            except User.DoesNotExist:
                self.log.info("LDAP authenticate: create new user %s" % ldap_user['login'])
                user = User(username=ldap_user['login'])
                user.first_name = ldap_user['givenname']
                user.last_name = ldap_user['lastname']
                user.is_staff = (ldap_user['role'] != 'ST')
                user.is_superuser = False
                user.save()
            return user
        return None

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None


