WhintPy 1.1

https://sourceforge.net/projects/whintpy/

Module whintpy.connection

Class LdapAuthentication

Description

Lightweight Directory Access Protocol authentication method.

The Lightweight Directory Access Protocol (LDAP) is an open, vendor-neutral, industry standard application protocol for accessing and maintaining distributed directory information services over an Internet Protocol (IP) network.

A common use of LDAP is to provide a central place to store usernames and passwords. This allows many different applications and services to connect to the LDAP server to validate users.

Constructor

Create an LdapAuthentication instance.

Parameters
  • domain: (str) the domain of the server
Raises
  • TypeError: given domain is not a string
View Source
def __init__(self, domain: str, **kwargs):
    """Create an LdapAuthentication instance.

    :param domain: (str) the domain of the server
    :raises: TypeError: given ``domain`` is not a string

    """
    super(LdapAuthentication, self).__init__(**kwargs)
    self._available = LDAP
    if self._available is False:
        self.__domain = None
        self.__server = None
        self.__connexion = None
        logging.warning("LdapAuthentication was not initialized: requirement to 'ldap3' module is not satisfied.")
    else:
        if isinstance(domain, str) is False:
            raise TypeError("LdapAuthentication 'domain' must be a string. Got {} instead.".format(type(domain)))
        self.__domain = domain
        self.__server = Server(self.__domain, get_info=ALL)

Public functions

name

Override. Return the name of the authentication method.

Returns
  • (str) The name of the authentication method.
View Source
@staticmethod
def name() -> str:
    """Override. Return the name of the authentication method.

        :return: (str) The name of the authentication method.

        """
    return BaseAuthentication._get_default_name(LdapAuthentication)

get_args

Override. Return the domain of the LDAP authentication.

Returns
  • (str) The LDAP domain or an empty list if LDAP is not available
View Source
def get_args(self) -> list:
    """Override. Return the domain of the LDAP authentication.

        :return: (str) The LDAP domain or an empty list if LDAP is not available

        """
    if self._available is True:
        return [self.__domain]
    return []

authenticate

Authenticate a user from its login and password.

Parameters
  • username: (str) the username of the user
  • password: (str) the password of the user
Returns
  • (bool) User is successfully authenticated
Raises
  • TypeError: given username or password are not strings
View Source
def authenticate(self, username: str, password: str) -> tuple[bool, str]:
    """Authenticate a user from its login and password.

        :param username: (str) the username of the user
        :param password: (str) the password of the user
        :return: (bool) User is successfully authenticated
        :raises: TypeError: given ``username`` or ``password`` are not strings

        """
    if self._available is False:
        return (False, 'LdapAuthentication unavailable')
    if isinstance(username, str) is False:
        raise TypeError("LdapAuthentication 'username' must be a string. Got {} instead.".format(type(username).__name__))
    if isinstance(password, str) is False:
        raise TypeError("LdapAuthentication 'password' must be a string. Got {} instead.".format(type(password)))
    try:
        self.__connexion = self.__create_ldap_connection(username, password)
        return (True, 'User successfully authenticated')
    except Exception as e:
        logging.error("Connection to server '{:s}' in domain '{:s}' failed due to the following error: {:s}".format(repr(self.__server), self.__domain, str(e)))
        return (False, f'User not authenticated due to the following error: {e}')

close

Close the connection.

View Source
def close(self):
    """Close the connection."""
    if self.__connexion is not None:
        self.__connexion.unbind()
        self.__connexion = None

get_full_name

Return the full name of a user.

Parameters
  • username: (str) the username of the user
Returns
  • (str) the full name of the user
View Source
def get_full_name(self, username: str) -> str:
    """Return the full name of a user.

        :param username: (str) the username of the user
        :return: (str) the full name of the user

        """
    if self.__connexion is not None:
        dn_base = ','.join([f'DC={elem}' for elem in self.__domain.split('.')])
        search_filter = '(sAMAccountName=' + username + ')'
        self.__connexion.search(dn_base, search_filter, attributes='displayName')
        for entree in self.__connexion.entries:
            return str(entree.displayName)
    return 'Anonymous'

Protected functions

__create_ldap_connection

Establish a connection to the LDAP server.

Parameters
  • username: (str) the username of the user
  • password: (str) the password of the user
Returns
  • (bool) User is successfully authenticated
Raises
  • Exception: No connection establishment is possible
View Source
def __create_ldap_connection(self, username: str, password: str) -> Connection:
    """Establish a connection to the LDAP server.

        :param username: (str) the username of the user
        :param password: (str) the password of the user
        :return: (bool) User is successfully authenticated
        :raises: Exception: No connection establishment is possible

        """
    if self._available is True:
        c = Connection(self.__server, user=f'{self.__domain}\\{username}', password=password, authentication=NTLM)
        LdapAuthentication.__test_ldap_connection(c)
        return c
    else:
        raise ConnectionError('LdapAuthentication unavailable')

__test_ldap_connection

Test the connection to the LDAP server.

Parameters
  • c
View Source
@staticmethod
def __test_ldap_connection(c: Connection) -> None:
    """Test the connection to the LDAP server."""
    if not c.bind():
        raise ConnectionError(str(c.result))

Overloads

__str__

Return the string representation of the class.

Returns
  • (str) A string representation of the LdapAuthentication
View Source
def __str__(self):
    """Return the string representation of the class.

        :return: (str) A string representation of the LdapAuthentication

        """
    if self._available is False:
        return '{:s} unavailable'.format(self.__class__.__name__)
    return '{:s}(domain: {:s}, id={})'.format(self.__class__.__name__, self.__domain, self.method_id)

__repr__

Return the official string representation of the class.

Returns
  • (str) A string representation of the LdapAuthentication
View Source
def __repr__(self):
    """Return the official string representation of the class.

        :return: (str) A string representation of the LdapAuthentication

        """
    if self._available is False:
        return '{:s} unavailable'.format(self.__class__.__name__)
    return '{:s}({:s})'.format(self.__class__.__name__, ', '.join(["name: '{:s}'".format(self.name()), "id: '{:s}'".format(str(self.method_id)), "domain: '{:s}'".format(self.__domain)]))