Commit f670bec1 authored by Recteur LP's avatar Recteur LP

Python 3 and 2

parent 3462c9da
__all__ = ['ldapauth2']
\ No newline at end of file
__all__ = ['ldapauth']
\ No newline at end of file
#!/usr/bin/python
# -*- coding: utf-8 -*-
import ldap
import ldif
import sys
import urllib
import hashlib
import pyrmin
try:
import ldap
import ldif
import urllib
except ImportError:
from ldap3 import Server, Connection, AUTO_BIND_NO_TLS, SUBTREE, ALL_ATTRIBUTES
import urllib.parse
###################################
__name__ = "LDAP Authentification"
__description__ = "Module to authenticate user with Active Directory Server"
__version__ = "0.2.0"
__pyrmin_version__ = "0.3.0"
__namespace__ = "ldapauth2"
__pyrmin_version__ = "0.3.1"
__namespace__ = "ldapauth"
###################################
class auth():
"LDAP auth module"
def __init__(self, config):
self.config = config
pyrmin.log.debug(config)
if 'server' not in self.config:
pyrmin.returnerror("No ldap server in config")
elif 'port' not in self.config:
pyrmin.returnerror("No ldap port in config")
self.ld = ldap.initialize('ldap://' + self.config['server'] + ':' + self.config['port'])
self.ld.protocol_version = self.config['version']
self.ld.set_option(ldap.OPT_REFERRALS, 0)
self.ld.simple_bind_s(self.config['user'], self.config['password'])
if sys.version_info >= (3,0):
self.connection = Connection(
Server(
self.config['server'],
port=int(self.config['port']),
use_ssl=self.config['ssl']
),
auto_bind=AUTO_BIND_NO_TLS,
read_only=True,
check_names=True,
user=self.config['user'],
password=self.config['password']
)
else:
self.ld = ldap.initialize('ldap://' + self.config['server'] + ':' + self.config['port'])
self.ld.protocol_version = self.config['version']
self.ld.set_option(ldap.OPT_REFERRALS, 0)
self.ld.simple_bind_s(self.config['user'], self.config['password'])
def __del__(self):
try:
self.ld.unbind_s()
except:
pass
if sys.version_info < (3,0):
try:
self.ld.unbind_s()
except:
pass
def __getresults(self, filter):
results = self.ld.search_s(self.config['basedn'],ldap.SCOPE_SUBTREE,filter)
if sys.version_info >= (3,0):
pyrmin.log.debug(filter)
self.connection.search(
search_base=self.config['basedn'],
search_filter=filter,
search_scope=SUBTREE,
attributes=ALL_ATTRIBUTES,
get_operational_attributes=True
)
results = self.connection.response
else:
results = self.ld.search_s(self.config['basedn'],ldap.SCOPE_SUBTREE,filter)
return results
def __getgroup(self, group):
results = self.ld.search_s(group,ldap.SCOPE_SUBTREE)
if sys.version_info >= (3,0):
self.connection.search(
search_base=self.config['basedn'],
search_filter=group,
search_scope=SUBTREE,
attributes=ALL_ATTRIBUTES,
get_operational_attributes=True
)
results = self.connection.response
else:
results = self.ld.search_s(group,ldap.SCOPE_SUBTREE)
return results
def getusersfromgroup(self, group):
users = []
for dn,attrs in self.__getresults(group):
if dn and attrs:
for entry in self.__getresults(group):
if "attributes" in entry:
attrs = entry['attributes']
users.append({ "name": attrs.get('sAMAccountName', [ 'Guest' ])[0], "uid": attrs.get('uidNumber', [ 'None' ])[0] })
return users
def get(self, name):
filter = "(&(cn=" + name + ")(!(objectClass=computer)))"
for dn,attrs in self.__getresults(filter):
if dn and attrs:
#filter = "(&(cn=" + name + ")(!(objectClass=computer)))"
filter = "(&(samAccountName=" + name + "))"
for entry in self.__getresults(filter):
if "attributes" in entry:
attrs = entry['attributes']
name = attrs.get('sAMAccountName', [ 'Guest' ])[0]
mail = str(attrs.get('mail')[0]).decode('utf-8').lower()
gravatar_url = "http://www.gravatar.com/avatar/" + hashlib.md5(mail).hexdigest() + "?"
gravatar_url += urllib.urlencode({'d':"identicon", 's':str(50)})
if sys.version_info >= (3,0):
mail = str(attrs.get('mail')[0]).lower()
gravatar_url = "//www.gravatar.com/avatar/" + hashlib.md5(mail.encode('utf-8')).hexdigest() + "?"
gravatar_url += urllib.parse.urlencode({'d':"identicon", 's':str(50)})
division = attrs.get('division', [ 'Guest' ])[0]
displayname = attrs.get('displayName', [ 'Guest' ])[0]
company = attrs.get('company', [ '' ])[0]
else:
mail = str(attrs.get('mail')[0]).decode('utf-8').lower()
gravatar_url = "//www.gravatar.com/avatar/" + hashlib.md5(mail).hexdigest() + "?"
gravatar_url += urllib.urlencode({'d':"identicon", 's':str(50)})
division = attrs.get('division', [ 'Guest' ])[0].decode("utf-8")
displayname = attrs.get('displayName', [ 'Guest' ])[0].decode("utf-8")
company = attrs.get('company', [ '' ])[0].decode("utf-8")
isadmin = False
admins = []
for group in self.config['admin']:
admins = self.getusersfromgroup("memberOf=" + group)
admins = self.getusersfromgroup("(&(memberOf=" + group + "))")
for admin in admins:
pyrmin.log.debug(admin)
if 'name' in admin and name.lower() == admin['name'].lower():
......@@ -76,10 +130,10 @@ class auth():
"username": name,
"auth": True,
"admin": isadmin,
"division": attrs.get('division', [ 'Guest' ])[0].decode("utf-8"),
"displayname": attrs.get('displayName', [ 'Guest' ])[0].decode("utf-8"),
"division": division,
"displayname": displayname,
"mobile": attrs.get('otherMobile', [ '' ])[0],
"company": attrs.get('company', [ '' ])[0].decode("utf-8"),
"company": company,
"mail": mail,
"img": gravatar_url
}
\ No newline at end of file
......@@ -4,6 +4,8 @@
{{ forms.input('port', label="LDAP Port", value=config.port) }}
{{ forms.input('ssl', label="Enable SSL", value=config.ssl) }}
{{ forms.input('version', label="Protocol Version", value=config.version) }}
{{ forms.input('user', label="LDAP Username", value=config.user) }}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment