Created
August 29, 2018 19:58
-
-
Save leydson-vieira/e7eb1c23ce0ea0bb348945c1b1df6d88 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
from __future__ import print_function | |
import ldap | |
from apps.parametros.models import ModelParametros | |
class ActiveDirectoryUser: | |
"""Classe para um modelo de usuário com alguns atributos do AD.""" | |
def __init__(self, name='', username='', matricula='', is_rh=False, email=''): | |
self.name = name | |
self.username = username | |
self.email = email | |
self.matricula = matricula | |
self.is_rh = is_rh | |
class LoginLDAP: | |
""" | |
Classe utilizada para a verificar a autenticação do usuário no servidor | |
LDAP condigurado no sistema. | |
Caso o usuário exista e autentique, retorna True. Qualquer outro caso | |
retorna False. | |
> login = LoginLDAP('usuario', 'senha') | |
> login.authenticate() -> tuple(boolean, ActiveDirectoryUser instance.) | |
""" | |
TRACE_LEVEL = 1 | |
def __init__(self, username, passwd): | |
if username and passwd: | |
self.domain = self.get_ldap_domain() | |
self.userPrincipalName = '{0}@{1}'.format(username, self.domain) | |
self.passwd = passwd | |
self.LDAP_URI = 'ldap://{domain}:389/'.format(domain=self.domain) | |
# self.LDAP_URI = 'ldap://10.0.0.70:389/' | |
self.dn_base = self.get_dn_base() | |
self.filter_ = "(&(objectClass=user)(sAMAccountName=" + username + "))" | |
self.attrs = ["*"] | |
self.scope = ldap.SCOPE_SUBTREE | |
else: | |
raise Exception('''Username e Password são parâmetros obrigatórios. | |
Por favor, verifique o modo de utilização dessa classe''') | |
def get_ldap_domain(self): | |
return ModelParametros.get_instance().dominio_ad | |
def get_dn_base(self): | |
base = list() | |
for dc in self.domain.split('.'): | |
base.append('dc={0}'.format(dc)) | |
return ','.join(base) | |
def get_ad_attr(self, user, attr): | |
try: | |
return user[0][1][attr][0] | |
except KeyError: | |
return None | |
def authenticate(self): | |
try: | |
conn = ldap.initialize(self.LDAP_URI, trace_level=self.TRACE_LEVEL) | |
conn.protocol_version = ldap.VERSION3 | |
conn.set_option(ldap.OPT_REFERRALS, 0) | |
except ldap.LDAPError as err: | |
print ('Não foi possível conectar com o servidor LDAP.') | |
print (err) | |
return False, None | |
try: | |
result = conn.simple_bind_s(self.userPrincipalName, self.passwd) | |
except ldap.LDAPError as err: | |
print ('O servidor foi encontrado porém não foi possível autenticar no LDAP.') | |
print (err) | |
return False, None | |
if result: | |
print ('Uma autenticação foi feita com o servidor.') | |
r = conn.search(self.dn_base, self.scope, self.filter_, self.attrs) | |
_type, user = conn.result(r, 60) | |
name = self.get_ad_attr(user, 'name') | |
username = self.get_ad_attr(user, 'userPrincipalName') | |
try: | |
matricula = self.get_ad_attr(user, 'matricula') | |
is_rh = self.get_ad_attr(user, 'isRh') | |
is_rh = True if is_rh == 'TRUE' else False | |
except KeyError as err: | |
print ('Os campos isRh ou matricula não existem no AD.') | |
print (err) | |
return False, None | |
# mail = user[0][1]['mail'][0] | |
ad_user = ActiveDirectoryUser(name, username, matricula, is_rh) | |
conn.unbind_s() # close ldap connections | |
return True, ad_user |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment