1
0
mirror of https://github.com/kakwa/ldapcherry synced 2024-11-22 17:34:21 +01:00

many pep8 fixes thanks to pep8ify

This commit is contained in:
kakwa 2015-07-10 21:06:28 +02:00
parent 2d12335030
commit 3712bb85cb
9 changed files with 178 additions and 152 deletions

View File

@ -32,6 +32,7 @@ from sets import Set
SESSION_KEY = '_cp_username' SESSION_KEY = '_cp_username'
# Custom log function to overrige weird error.log function # Custom log function to overrige weird error.log function
# of cherrypy # of cherrypy
def syslog_error(msg='', context='', def syslog_error(msg='', context='',
@ -44,36 +45,38 @@ def syslog_error(msg='', context='',
else: else:
cherrypy.log.error_log.log(severity, cherrypy.log.error_log.log(severity,
' '.join((context, msg))) ' '.join((context, msg)))
import traceback
if traceback: if traceback:
try: try:
exc = sys.exc_info() exc = sys.exc_info()
if exc == (None, None, None): if exc == (None, None, None):
cherrypy.log.error_log.log(severity, msg) cherrypy.log.error_log.log(severity, msg)
import traceback
# log each line of the exception # log each line of the exception
# in a separate log for lisibility
for l in traceback.format_exception(*exc): for l in traceback.format_exception(*exc):
cherrypy.log.error_log.log(severity, l) cherrypy.log.error_log.log(severity, l)
finally: finally:
del exc del exc
class LdapCherry(object): class LdapCherry(object):
def _handle_exception(self, e): def _handle_exception(self, e):
if hasattr(e, 'log'): if hasattr(e, 'log'):
cherrypy.log.error( cherrypy.log.error(
msg = e.log, msg=e.log,
severity = logging.ERROR severity=logging.ERROR
) )
else: else:
cherrypy.log.error( cherrypy.log.error(
msg = "unkwon exception: '%(e)s'" % { 'e' : str(e) }, msg="unkwon exception: '%(e)s'" % {'e': str(e)},
severity = logging.ERROR severity=logging.ERROR
) )
# log the traceback as 'debug' # log the traceback as 'debug'
cherrypy.log.error( cherrypy.log.error(
msg = '', msg='',
severity = logging.DEBUG, severity=logging.DEBUG,
traceback= True traceback=True
) )
def _get_param(self, section, key, config, default=None): def _get_param(self, section, key, config, default=None):
@ -100,8 +103,8 @@ class LdapCherry(object):
for b in self.backends: for b in self.backends:
ret[b] = self.backends[b].get_groups(username) ret[b] = self.backends[b].get_groups(username)
cherrypy.log.error( cherrypy.log.error(
msg = "user '" + username +"' groups: " + str(ret), msg="user '" + username + "' groups: " + str(ret),
severity = logging.DEBUG, severity=logging.DEBUG,
) )
return ret return ret
@ -114,8 +117,8 @@ class LdapCherry(object):
groups = self._get_groups(username) groups = self._get_groups(username)
user_roles = self.roles.get_roles(groups) user_roles = self.roles.get_roles(groups)
cherrypy.log.error( cherrypy.log.error(
msg = "user '" + username +"' roles: " + str(user_roles), msg="user '" + username + "' roles: " + str(user_roles),
severity = logging.DEBUG, severity=logging.DEBUG,
) )
return user_roles return user_roles
@ -201,12 +204,11 @@ class LdapCherry(object):
self.roles_file = self._get_param('roles', 'roles.file', config) self.roles_file = self._get_param('roles', 'roles.file', config)
cherrypy.log.error( cherrypy.log.error(
msg = "loading roles file '%(file)s'" % { 'file': self.roles_file }, msg="loading roles file '%(file)s'" % {'file': self.roles_file},
severity = logging.DEBUG severity=logging.DEBUG
) )
self.roles = Roles(self.roles_file) self.roles = Roles(self.roles_file)
def _set_access_log(self, config, level): def _set_access_log(self, config, level):
""" Configure access logs """ Configure access logs
""" """
@ -219,7 +221,7 @@ class LdapCherry(object):
# replace access log handler by a syslog handler # replace access log handler by a syslog handler
if access_handler == 'syslog': if access_handler == 'syslog':
cherrypy.log.access_log.handlers = [] cherrypy.log.access_log.handlers = []
handler = logging.handlers.SysLogHandler(address = '/dev/log', handler = logging.handlers.SysLogHandler(address='/dev/log',
facility='user') facility='user')
handler.setFormatter(syslog_formatter) handler.setFormatter(syslog_formatter)
cherrypy.log.access_log.addHandler(handler) cherrypy.log.access_log.addHandler(handler)
@ -256,7 +258,7 @@ class LdapCherry(object):
# (by the way, what's the use of "context"?) # (by the way, what's the use of "context"?)
cherrypy.log.error = syslog_error cherrypy.log.error = syslog_error
handler = logging.handlers.SysLogHandler(address = '/dev/log', handler = logging.handlers.SysLogHandler(address='/dev/log',
facility='user') facility='user')
handler.setFormatter(syslog_formatter) handler.setFormatter(syslog_formatter)
cherrypy.log.error_log.addHandler(handler) cherrypy.log.error_log.addHandler(handler)
@ -334,34 +336,34 @@ class LdapCherry(object):
# definition of the template directory # definition of the template directory
self.template_dir = self._get_param('resources', 'templates.dir', config) self.template_dir = self._get_param('resources', 'templates.dir', config)
cherrypy.log.error( cherrypy.log.error(
msg = "loading templates from dir '%(dir)s'" % { 'dir': self.template_dir }, msg="loading templates from dir '%(dir)s'" % {'dir': self.template_dir},
severity = logging.DEBUG severity=logging.DEBUG
) )
# preload templates # preload templates
self.temp_lookup = lookup.TemplateLookup( self.temp_lookup = lookup.TemplateLookup(
directories=self.template_dir, input_encoding='utf-8' directories=self.template_dir, input_encoding='utf-8'
) )
self.temp_index = self.temp_lookup.get_template('index.tmpl') self.temp_index = self.temp_lookup.get_template('index.tmpl')
self.temp_error = self.temp_lookup.get_template('error.tmpl') self.temp_error = self.temp_lookup.get_template('error.tmpl')
self.temp_login = self.temp_lookup.get_template('login.tmpl') self.temp_login = self.temp_lookup.get_template('login.tmpl')
self.temp_searchadmin = self.temp_lookup.get_template('searchadmin.tmpl') self.temp_searchadmin = self.temp_lookup.get_template('searchadmin.tmpl')
self.temp_searchuser = self.temp_lookup.get_template('searchuser.tmpl') self.temp_searchuser = self.temp_lookup.get_template('searchuser.tmpl')
self.temp_adduser = self.temp_lookup.get_template('adduser.tmpl') self.temp_adduser = self.temp_lookup.get_template('adduser.tmpl')
self.temp_roles = self.temp_lookup.get_template('roles.tmpl') self.temp_roles = self.temp_lookup.get_template('roles.tmpl')
self.temp_groups = self.temp_lookup.get_template('groups.tmpl') self.temp_groups = self.temp_lookup.get_template('groups.tmpl')
self.temp_form = self.temp_lookup.get_template('form.tmpl') self.temp_form = self.temp_lookup.get_template('form.tmpl')
self.temp_selfmodify = self.temp_lookup.get_template('selfmodify.tmpl') self.temp_selfmodify = self.temp_lookup.get_template('selfmodify.tmpl')
self.temp_modify = self.temp_lookup.get_template('modify.tmpl') self.temp_modify = self.temp_lookup.get_template('modify.tmpl')
self._init_auth(config) self._init_auth(config)
self.attributes_file = self._get_param('attributes', 'attributes.file', config) self.attributes_file = self._get_param('attributes', 'attributes.file', config)
cherrypy.log.error( cherrypy.log.error(
msg = "loading attributes file '%(file)s'" % { 'file': self.attributes_file }, msg="loading attributes file '%(file)s'" % {'file': self.attributes_file},
severity = logging.DEBUG severity=logging.DEBUG
) )
def reload(self, config = None): def reload(self, config=None):
""" load/reload configuration """ load/reload configuration
@dict: configuration of ldapcherry @dict: configuration of ldapcherry
""" """
@ -381,14 +383,14 @@ class LdapCherry(object):
self.attributes = Attributes(self.attributes_file) self.attributes = Attributes(self.attributes_file)
cherrypy.log.error( cherrypy.log.error(
msg = "init directories backends", msg="init directories backends",
severity = logging.DEBUG severity=logging.DEBUG
) )
self._init_backends(config) self._init_backends(config)
self._check_backends() self._check_backends()
cherrypy.log.error( cherrypy.log.error(
msg = "application started", msg="application started",
severity = logging.INFO severity=logging.INFO
) )
# loading the ppolicy # loading the ppolicy
@ -397,8 +399,8 @@ class LdapCherry(object):
except Exception as e: except Exception as e:
self._handle_exception(e) self._handle_exception(e)
cherrypy.log.error( cherrypy.log.error(
msg = "application failed to start", msg="application failed to start",
severity = logging.ERROR severity=logging.ERROR
) )
exit(1) exit(1)
@ -439,8 +441,8 @@ class LdapCherry(object):
ret[attrid] = tmp[attr] ret[attrid] = tmp[attr]
cherrypy.log.error( cherrypy.log.error(
msg = "user '" + username + "' attributes " + str(ret), msg="user '" + username + "' attributes " + str(ret),
severity = logging.DEBUG severity=logging.DEBUG
) )
return ret return ret
@ -480,7 +482,7 @@ class LdapCherry(object):
if cherrypy.request.query_string == '': if cherrypy.request.query_string == '':
qs = '' qs = ''
else: else:
qs = '?' + cherrypy.request.query_string qs = '?' + cherrypy.request.query_string
b64requrl = base64.b64encode(cherrypy.url() + qs) b64requrl = base64.b64encode(cherrypy.url() + qs)
if not username: if not username:
raise cherrypy.HTTPRedirect("/signin?url=%(url)s" % {'url': b64requrl}) raise cherrypy.HTTPRedirect("/signin?url=%(url)s" % {'url': b64requrl})
@ -503,8 +505,8 @@ class LdapCherry(object):
def _adduser(self, params): def _adduser(self, params):
cherrypy.log.error( cherrypy.log.error(
msg = "add user form attributes: " + str(params), msg="add user form attributes: " + str(params),
severity = logging.DEBUG severity=logging.DEBUG
) )
badd = {} badd = {}
@ -530,12 +532,12 @@ class LdapCherry(object):
admin = str(sess.get(SESSION_KEY, None)) admin = str(sess.get(SESSION_KEY, None))
cherrypy.log.error( cherrypy.log.error(
msg = "user '" + username + "' added by '" + admin + "'", msg="user '" + username + "' added by '" + admin + "'",
severity = logging.INFO severity=logging.INFO
) )
cherrypy.log.error( cherrypy.log.error(
msg = "user '" + username + "' attributes: " + str(badd), msg="user '" + username + "' attributes: " + str(badd),
severity = logging.DEBUG severity=logging.DEBUG
) )
roles = [] roles = []
@ -547,16 +549,15 @@ class LdapCherry(object):
self.backends[b].add_to_groups(username, Set(groups[b])) self.backends[b].add_to_groups(username, Set(groups[b]))
cherrypy.log.error( cherrypy.log.error(
msg = "user '" + username + "' made member of "\ msg="user '" + username + "' made member of " \
+ str(roles)+ " by '" + admin + "'", + str(roles) + " by '" + admin + "'",
severity = logging.INFO severity=logging.INFO
) )
cherrypy.log.error( cherrypy.log.error(
msg = "user '" + username + "' groups: " + str(groups), msg="user '" + username + "' groups: " + str(groups),
severity = logging.DEBUG severity=logging.DEBUG
) )
def _modify_attrs(self, params, attr_list, username): def _modify_attrs(self, params, attr_list, username):
badd = {} badd = {}
for attr in attr_list: for attr in attr_list:
@ -580,25 +581,25 @@ class LdapCherry(object):
def _selfmodify(self, params): def _selfmodify(self, params):
cherrypy.log.error( cherrypy.log.error(
msg = "modify user form attributes: " + str(params), msg="modify user form attributes: " + str(params),
severity = logging.DEBUG severity=logging.DEBUG
) )
sess = cherrypy.session sess = cherrypy.session
username = str(sess.get(SESSION_KEY, None)) username = str(sess.get(SESSION_KEY, None))
badd = self._modify_attrs(params, self.attributes.get_selfattributes(), username) badd = self._modify_attrs(params, self.attributes.get_selfattributes(), username)
cherrypy.log.error( cherrypy.log.error(
msg = "user '" + username + "' modified his attributes", msg="user '" + username + "' modified his attributes",
severity = logging.INFO severity=logging.INFO
) )
cherrypy.log.error( cherrypy.log.error(
msg = "user '" + username + "' attributes: " + str(badd), msg="user '" + username + "' attributes: " + str(badd),
severity = logging.DEBUG severity=logging.DEBUG
) )
def _modify(self, params): def _modify(self, params):
cherrypy.log.error( cherrypy.log.error(
msg = "modify user form attributes: " + str(params), msg="modify user form attributes: " + str(params),
severity = logging.DEBUG severity=logging.DEBUG
) )
key = self.attributes.get_key() key = self.attributes.get_key()
username = params['attrs'][key] username = params['attrs'][key]
@ -609,12 +610,12 @@ class LdapCherry(object):
admin = str(sess.get(SESSION_KEY, None)) admin = str(sess.get(SESSION_KEY, None))
cherrypy.log.error( cherrypy.log.error(
msg = "user '" + username + "' modified by '" + admin + "'", msg="user '" + username + "' modified by '" + admin + "'",
severity = logging.INFO severity=logging.INFO
) )
cherrypy.log.error( cherrypy.log.error(
msg = "user '" + username + "' attributes: " + str(badd), msg="user '" + username + "' attributes: " + str(badd),
severity = logging.DEBUG severity=logging.DEBUG
) )
tmp = self._get_roles(username) tmp = self._get_roles(username)
@ -659,8 +660,8 @@ class LdapCherry(object):
lonely_groups[b] = [] lonely_groups[b] = []
tmp = Set(groups_add[b]) - Set(groups_keep[b]) - Set(groups_current[b]) - Set(lonely_groups[b]) tmp = Set(groups_add[b]) - Set(groups_keep[b]) - Set(groups_current[b]) - Set(lonely_groups[b])
cherrypy.log.error( cherrypy.log.error(
msg = "user '" + username + "' added to groups: " + str(list(tmp))+ " in backend '" + b + "'", msg="user '" + username + "' added to groups: " + str(list(tmp)) + " in backend '" + b + "'",
severity = logging.DEBUG severity=logging.DEBUG
) )
self.backends[b].add_to_groups(username, tmp) self.backends[b].add_to_groups(username, tmp)
for b in groups_rm: for b in groups_rm:
@ -676,29 +677,29 @@ class LdapCherry(object):
groups_current[b] = [] groups_current[b] = []
if not b in lonely_groups: if not b in lonely_groups:
lonely_groups[b] = [] lonely_groups[b] = []
tmp = ((Set(groups_rm[b]) | Set(groups_remove[b])) - (Set(groups_keep[b]) | Set(groups_add[b]))) & (Set(groups_current[b]) | Set(lonely_groups[b])) tmp = ((Set(groups_rm[b]) | Set(groups_remove[b])) - (Set(groups_keep[b]) | Set(groups_add[b]))) & (Set(groups_current[b]) | Set(lonely_groups[b]))
cherrypy.log.error( cherrypy.log.error(
msg = "user '" + username + "' removed from groups: " + str(list(tmp))+ " in backend '" + b + "'", msg="user '" + username + "' removed from groups: " + str(list(tmp)) + " in backend '" + b + "'",
severity = logging.DEBUG severity=logging.DEBUG
) )
self.backends[b].del_from_groups(username, tmp) self.backends[b].del_from_groups(username, tmp)
cherrypy.log.error( cherrypy.log.error(
msg = "user '" + username + "' made member of " + str(roles_member) + " by '" + admin + "'", msg="user '" + username + "' made member of " + str(roles_member) + " by '" + admin + "'",
severity = logging.INFO severity=logging.INFO
) )
def _deleteuser(self, username): def _deleteuser(self, username):
for b in self.backends: for b in self.backends:
self.backends[b].del_user(username) self.backends[b].del_user(username)
cherrypy.log.error( cherrypy.log.error(
msg = "user '" + username + "' deleted from backend '" + b + "'", msg="user '" + username + "' deleted from backend '" + b + "'",
severity = logging.DEBUG severity=logging.DEBUG
) )
cherrypy.log.error( cherrypy.log.error(
msg = "User '" + username + "' deleted", msg="User '" + username + "' deleted",
severity = logging.INFO severity=logging.INFO
) )
def _checkppolicy(self, password): def _checkppolicy(self, password):
@ -729,8 +730,8 @@ class LdapCherry(object):
'user': login 'user': login
} }
cherrypy.log.error( cherrypy.log.error(
msg = message, msg=message,
severity = logging.INFO severity=logging.INFO
) )
cherrypy.session[SESSION_KEY] = cherrypy.request.login = login cherrypy.session[SESSION_KEY] = cherrypy.request.login = login
if url is None: if url is None:
@ -743,8 +744,8 @@ class LdapCherry(object):
'user': login 'user': login
} }
cherrypy.log.error( cherrypy.log.error(
msg = message, msg=message,
severity = logging.WARNING severity=logging.WARNING
) )
if url is None: if url is None:
qs = '' qs = ''
@ -763,8 +764,8 @@ class LdapCherry(object):
cherrypy.request.login = None cherrypy.request.login = None
cherrypy.log.error( cherrypy.log.error(
msg = "user '%(user)s' logout" % { 'user': username }, msg="user '%(user)s' logout" % {'user': username},
severity = logging.INFO severity=logging.INFO
) )
raise cherrypy.HTTPRedirect("/signin") raise cherrypy.HTTPRedirect("/signin")
@ -786,7 +787,7 @@ class LdapCherry(object):
else: else:
res = None res = None
attrs_list = self.attributes.get_search_attributes() attrs_list = self.attributes.get_search_attributes()
return self.temp_searchuser.render(searchresult = res, attrs_list = attrs_list, is_admin=is_admin) return self.temp_searchuser.render(searchresult=res, attrs_list=attrs_list, is_admin=is_admin)
@cherrypy.expose @cherrypy.expose
def checkppolicy(self, **params): def checkppolicy(self, **params):
@ -803,7 +804,7 @@ class LdapCherry(object):
cherrypy.response.status = 200 cherrypy.response.status = 200
else: else:
cherrypy.response.status = 400 cherrypy.response.status = 400
return json.dumps(ret, separators=(',',':')) return json.dumps(ret, separators=(',', ':'))
@cherrypy.expose @cherrypy.expose
def searchadmin(self, searchstring=None): def searchadmin(self, searchstring=None):
@ -815,7 +816,7 @@ class LdapCherry(object):
else: else:
res = None res = None
attrs_list = self.attributes.get_search_attributes() attrs_list = self.attributes.get_search_attributes()
return self.temp_searchadmin.render(searchresult = res, attrs_list = attrs_list, is_admin=is_admin) return self.temp_searchadmin.render(searchresult=res, attrs_list=attrs_list, is_admin=is_admin)
@cherrypy.expose @cherrypy.expose
def adduser(self, **params): def adduser(self, **params):
@ -830,16 +831,16 @@ class LdapCherry(object):
else: else:
notification = '' notification = ''
graph={} graph = {}
for r in self.roles.graph: for r in self.roles.graph:
s = list(self.roles.graph[r]['sub_roles']) s = list(self.roles.graph[r]['sub_roles'])
p = list(self.roles.graph[r]['parent_roles']) p = list(self.roles.graph[r]['parent_roles'])
graph[r] = { 'sub_roles': s, 'parent_roles': p} graph[r] = {'sub_roles': s, 'parent_roles': p}
graph_js = json.dumps(graph, separators=(',',':')) graph_js = json.dumps(graph, separators=(',', ':'))
display_names = {} display_names = {}
for r in self.roles.flatten: for r in self.roles.flatten:
display_names[r] = self.roles.flatten[r]['display_name'] display_names[r] = self.roles.flatten[r]['display_name']
roles_js = json.dumps(display_names, separators=(',',':')) roles_js = json.dumps(display_names, separators=(',', ':'))
form = self.temp_form.render(attributes=self.attributes.attributes, values=None, modify=False, autofill=True) form = self.temp_form.render(attributes=self.attributes.attributes, values=None, modify=False, autofill=True)
roles = self.temp_roles.render(roles=self.roles.flatten, graph=self.roles.graph, graph_js=graph_js, roles_js=roles_js, current_roles=None) roles = self.temp_roles.render(roles=self.roles.flatten, graph=self.roles.graph, graph_js=graph_js, roles_js=roles_js, current_roles=None)
return self.temp_adduser.render(form=form, roles=roles, is_admin=is_admin, notification=notification) return self.temp_adduser.render(form=form, roles=roles, is_admin=is_admin, notification=notification)
@ -868,12 +869,12 @@ class LdapCherry(object):
else: else:
notification = '' notification = ''
graph={} graph = {}
for r in self.roles.graph: for r in self.roles.graph:
s = list(self.roles.graph[r]['sub_roles']) s = list(self.roles.graph[r]['sub_roles'])
p = list(self.roles.graph[r]['parent_roles']) p = list(self.roles.graph[r]['parent_roles'])
graph[r] = { 'sub_roles': s, 'parent_roles': p} graph[r] = {'sub_roles': s, 'parent_roles': p}
graph_js = json.dumps(graph, separators=(',',':')) graph_js = json.dumps(graph, separators=(',', ':'))
display_names = {} display_names = {}
for r in self.roles.flatten: for r in self.roles.flatten:
display_names[r] = self.roles.flatten[r]['display_name'] display_names[r] = self.roles.flatten[r]['display_name']
@ -881,7 +882,7 @@ class LdapCherry(object):
tmp = self._get_roles(user) tmp = self._get_roles(user)
user_roles = tmp['roles'] user_roles = tmp['roles']
user_lonely_groups = tmp['unusedgroups'] user_lonely_groups = tmp['unusedgroups']
roles_js = json.dumps(display_names, separators=(',',':')) roles_js = json.dumps(display_names, separators=(',', ':'))
key = self.attributes.get_key() key = self.attributes.get_key()
form = self.temp_form.render(attributes=self.attributes.attributes, values=user_attrs, modify=True, keyattr=key, autofill=False) form = self.temp_form.render(attributes=self.attributes.attributes, values=user_attrs, modify=True, keyattr=key, autofill=False)
roles = self.temp_roles.render(roles=self.roles.flatten, graph=self.roles.graph, graph_js=graph_js, roles_js=roles_js, current_roles=user_roles) roles = self.temp_roles.render(roles=self.roles.flatten, graph=self.roles.graph, graph_js=graph_js, roles_js=roles_js, current_roles=user_roles)
@ -896,7 +897,7 @@ class LdapCherry(object):
user = str(sess.get(SESSION_KEY, None)) user = str(sess.get(SESSION_KEY, None))
if self.auth_mode == 'none': if self.auth_mode == 'none':
return self.temp_error.render(is_admin=is_admin, return self.temp_error.render(is_admin=is_admin,
alert = 'warning', alert='warning',
message="Not accessible with authentication disabled." message="Not accessible with authentication disabled."
) )
if cherrypy.request.method.upper() == 'POST': if cherrypy.request.method.upper() == 'POST':

View File

@ -16,6 +16,7 @@ import yaml
types = ['string', 'email', 'int', 'stringlist', 'fix', 'password'] types = ['string', 'email', 'int', 'stringlist', 'fix', 'password']
class Attributes: class Attributes:
def __init__(self, attributes_file): def __init__(self, attributes_file):

View File

@ -7,6 +7,7 @@
from ldapcherry.exceptions import MissingParameter from ldapcherry.exceptions import MissingParameter
class Backend: class Backend:
def __init__(self, config, logger, name, attrslist, key): def __init__(self, config, logger, name, attrslist, key):
@ -45,5 +46,4 @@ class Backend:
elif not default is None: elif not default is None:
return default return default
else: else:
raise MissingParameter('backends', self.backend_name+'.'+param) raise MissingParameter('backends', self.backend_name + '.' + param)

View File

@ -13,21 +13,24 @@ import ldapcherry.backend
import os import os
import re import re
class DelUserDontExists(Exception): class DelUserDontExists(Exception):
def __init__(self, user): def __init__(self, user):
self.user = user self.user = user
self.log = "cannot remove user, user <%(user)s> does not exist" % { 'user' : user} self.log = "cannot remove user, user <%(user)s> does not exist" % {'user': user}
class CaFileDontExist(Exception): class CaFileDontExist(Exception):
def __init__(self, cafile): def __init__(self, cafile):
self.cafile = cafile self.cafile = cafile
self.log = "CA file %(cafile)s don't exist" % { 'cafile': cafile } self.log = "CA file %(cafile)s don't exist" % {'cafile': cafile}
NO_ATTR = 0 NO_ATTR = 0
DISPLAYED_ATTRS = 1 DISPLAYED_ATTRS = 1
LISTED_ATTRS = 2 LISTED_ATTRS = 2
ALL_ATTRS = 3 ALL_ATTRS = 3
class Backend(ldapcherry.backend.Backend): class Backend(ldapcherry.backend.Backend):
def __init__(self, config, logger, name, attrslist, key): def __init__(self, config, logger, name, attrslist, key):
@ -64,29 +67,29 @@ class Backend(ldapcherry.backend.Backend):
def _exception_handler(self, e): def _exception_handler(self, e):
et = type(e) et = type(e)
if et is ldap.OPERATIONS_ERROR: if et is ldap.OPERATIONS_ERROR:
self._logger( self._logger(
severity = logging.ERROR, severity=logging.ERROR,
msg = "cannot use starttls with ldaps:// uri (uri: " + self.uri + ")", msg="cannot use starttls with ldaps:// uri (uri: " + self.uri + ")",
) )
elif et is ldap.INVALID_CREDENTIALS: elif et is ldap.INVALID_CREDENTIALS:
self._logger( self._logger(
severity = logging.ERROR, severity=logging.ERROR,
msg = "Configuration error, wrong credentials, unable to connect to ldap with '" + self.binddn + "'", msg="Configuration error, wrong credentials, unable to connect to ldap with '" + self.binddn + "'",
) )
elif et is ldap.SERVER_DOWN: elif et is ldap.SERVER_DOWN:
self._logger( self._logger(
severity = logging.ERROR, severity=logging.ERROR,
msg = "Unable to contact ldap server '" + self.uri + "', check 'auth.ldap.uri' and ssl/tls configuration", msg="Unable to contact ldap server '" + self.uri + "', check 'auth.ldap.uri' and ssl/tls configuration",
) )
elif et is ldap.FILTER_ERROR: elif et is ldap.FILTER_ERROR:
self._logger( self._logger(
severity = logging.ERROR, severity=logging.ERROR,
msg = "Bad search filter, check '" + self.backend_name + ".*_filter_tmpl' params", msg="Bad search filter, check '" + self.backend_name + ".*_filter_tmpl' params",
) )
elif et is ldap.NO_SUCH_OBJECT: elif et is ldap.NO_SUCH_OBJECT:
self._logger( self._logger(
severity = logging.ERROR, severity=logging.ERROR,
msg = "Search DN '" + basedn \ msg="Search DN '" + basedn \
+ "' doesn't exist, check '" \ + "' doesn't exist, check '" \
+ self.backend_name + ".userdn' or '" \ + self.backend_name + ".userdn' or '" \
+ self.backend_name + ".groupdn'", + self.backend_name + ".groupdn'",
@ -95,24 +98,24 @@ class Backend(ldapcherry.backend.Backend):
info = e[0]['info'] info = e[0]['info']
desc = e[0]['desc'] desc = e[0]['desc']
self._logger( self._logger(
severity = logging.ERROR, severity=logging.ERROR,
msg = "Configuration error, " + desc + ", " + info, msg="Configuration error, " + desc + ", " + info,
) )
elif et is ldap.INSUFFICIENT_ACCESS: elif et is ldap.INSUFFICIENT_ACCESS:
self._logger( self._logger(
severity = logging.ERROR, severity=logging.ERROR,
msg = "Access error on '" + self.backend_name + "' backend, please check your acls in this backend", msg="Access error on '" + self.backend_name + "' backend, please check your acls in this backend",
) )
elif et is ldap.ALREADY_EXISTS: elif et is ldap.ALREADY_EXISTS:
desc = e[0]['desc'] desc = e[0]['desc']
self._logger( self._logger(
severity = logging.ERROR, severity=logging.ERROR,
msg = "adding user failed, " + desc, msg="adding user failed, " + desc,
) )
else: else:
self._logger( self._logger(
severity = logging.ERROR, severity=logging.ERROR,
msg = "unknow ldap exception in ldap backend", msg="unknow ldap exception in ldap backend",
) )
raise e raise e
@ -233,7 +236,7 @@ class Backend(ldapcherry.backend.Backend):
dn = self.dn_user_attr + '=' + attrs[self.dn_user_attr] + ',' + self.userdn dn = self.dn_user_attr + '=' + attrs[self.dn_user_attr] + ',' + self.userdn
ldif = modlist.addModlist(attrs_str) ldif = modlist.addModlist(attrs_str)
try: try:
ldap_client.add_s(dn,ldif) ldap_client.add_s(dn, ldif)
except Exception as e: except Exception as e:
ldap_client.unbind_s() ldap_client.unbind_s()
self._exception_handler(e) self._exception_handler(e)
@ -256,9 +259,9 @@ class Backend(ldapcherry.backend.Backend):
for attr in attrs: for attr in attrs:
content = self._str(attrs[attr]) content = self._str(attrs[attr])
attr = self._str(attr) attr = self._str(attr)
new = { attr : content } new = {attr: content}
if attr in old_attrs: if attr in old_attrs:
old = { attr: old_attrs[attr]} old = {attr: old_attrs[attr]}
else: else:
old = {} old = {}
ldif = modlist.modifyModlist(old, new) ldif = modlist.modifyModlist(old, new)
@ -281,18 +284,18 @@ class Backend(ldapcherry.backend.Backend):
for attr in self.group_attrs: for attr in self.group_attrs:
content = self._str(self.group_attrs[attr] % attrs) content = self._str(self.group_attrs[attr] % attrs)
self._logger( self._logger(
severity = logging.DEBUG, severity=logging.DEBUG,
msg = "%(backend)s: adding user '%(user)s' with dn '%(dn)s' to group '%(group)s' by setting '%(attr)s' to '%(content)s'" % \ msg="%(backend)s: adding user '%(user)s' with dn '%(dn)s' to group '%(group)s' by setting '%(attr)s' to '%(content)s'" % \
{ 'user': username, 'dn': dn, 'group': group, 'attr': attr, 'content': content, 'backend': self.backend_name } {'user': username, 'dn': dn, 'group': group, 'attr': attr, 'content': content, 'backend': self.backend_name}
) )
ldif = modlist.modifyModlist({}, { attr : content }) ldif = modlist.modifyModlist({}, {attr: content})
try: try:
ldap_client.modify_s(group, ldif) ldap_client.modify_s(group, ldif)
except ldap.TYPE_OR_VALUE_EXISTS as e: except ldap.TYPE_OR_VALUE_EXISTS as e:
self._logger( self._logger(
severity = logging.INFO, severity=logging.INFO,
msg = "%(backend)s: user '%(user)s' already member of group '%(group)s' (attribute '%(attr)s')" % \ msg="%(backend)s: user '%(user)s' already member of group '%(group)s' (attribute '%(attr)s')" % \
{ 'user': username, 'group': group, 'attr': attr, 'backend': self.backend_name} {'user': username, 'group': group, 'attr': attr, 'backend': self.backend_name}
) )
except Exception as e: except Exception as e:
ldap_client.unbind_s() ldap_client.unbind_s()
@ -309,14 +312,14 @@ class Backend(ldapcherry.backend.Backend):
group = self._str(group) group = self._str(group)
for attr in self.group_attrs: for attr in self.group_attrs:
content = self._str(self.group_attrs[attr] % attrs) content = self._str(self.group_attrs[attr] % attrs)
ldif = [(ldap.MOD_DELETE, attr, content)] ldif = [(ldap.MOD_DELETE, attr, content)]
try: try:
ldap_client.modify_s(group, ldif) ldap_client.modify_s(group, ldif)
except ldap.NO_SUCH_ATTRIBUTE as e: except ldap.NO_SUCH_ATTRIBUTE as e:
self._logger( self._logger(
severity = logging.INFO, severity=logging.INFO,
msg = "%(backend)s: user '%(user)s' wasn't member of group '%(group)s' (attribute '%(attr)s')" % \ msg="%(backend)s: user '%(user)s' wasn't member of group '%(group)s' (attribute '%(attr)s')" % \
{ 'user': username, 'group': group, 'attr': attr, 'backend': self.backend_name} {'user': username, 'group': group, 'attr': attr, 'backend': self.backend_name}
) )
except Exception as e: except Exception as e:
ldap_client.unbind_s() ldap_client.unbind_s()

View File

@ -7,6 +7,7 @@
import ldapcherry.backend import ldapcherry.backend
class Backend(ldapcherry.backend.Backend): class Backend(ldapcherry.backend.Backend):
def __init__(self, config, logger, name, attrslist, key): def __init__(self, config, logger, name, attrslist, key):

View File

@ -7,70 +7,83 @@
import string import string
class MissingParameter(Exception): class MissingParameter(Exception):
def __init__(self, section, key): def __init__(self, section, key):
self.section = section self.section = section
self.key = key self.key = key
self.log = "missing parameter '%(key)s' in section '%(section)s'" % { 'key' : key, 'section' : section } self.log = "missing parameter '%(key)s' in section '%(section)s'" % {'key': key, 'section': section}
class MissingKey(Exception): class MissingKey(Exception):
def __init__(self, key, section, ymlfile): def __init__(self, key, section, ymlfile):
self.key = key self.key = key
self.section = section self.section = section
self.ymlfile = ymlfile self.ymlfile = ymlfile
self.log = "missing key '%(key)s' in section '%(section)s' inside file '%(ymlfile)s'" % {'key': key, 'section': section, 'ymlfile': ymlfile } self.log = "missing key '%(key)s' in section '%(section)s' inside file '%(ymlfile)s'" % {'key': key, 'section': section, 'ymlfile': ymlfile}
class DumplicateRoleKey(Exception): class DumplicateRoleKey(Exception):
def __init__(self, role): def __init__(self, role):
self.role = role self.role = role
self.log = "duplicate role key '%(role)s' in role file" % { 'role' : role} self.log = "duplicate role key '%(role)s' in role file" % {'role': role}
class MissingRole(Exception): class MissingRole(Exception):
def __init__(self, role): def __init__(self, role):
self.role = role self.role = role
self.log = "role '%(role)s' does not exist in role file" % { 'role' : role} self.log = "role '%(role)s' does not exist in role file" % {'role': role}
class MissingBackend(Exception): class MissingBackend(Exception):
def __init__(self, backend): def __init__(self, backend):
self.backend = backend self.backend = backend
self.log = "backend '%(backend)s' does not exist in main config file" % { 'backend' : backend} self.log = "backend '%(backend)s' does not exist in main config file" % {'backend': backend}
class WrongBackend(Exception): class WrongBackend(Exception):
def __init__(self, backend): def __init__(self, backend):
self.backend = backend self.backend = backend
self.log = "backend '%(backend)s' does not exist" % { 'backend' : backend} self.log = "backend '%(backend)s' does not exist" % {'backend': backend}
class DumplicateRoleContent(Exception): class DumplicateRoleContent(Exception):
def __init__(self, role1, role2): def __init__(self, role1, role2):
self.role1 = role1 self.role1 = role1
self.role2 = role2 self.role2 = role2
self.log = "role '%(role1)s' and '%(role2)s' are identical" % { 'role1' : role1, 'role2': role2} self.log = "role '%(role1)s' and '%(role2)s' are identical" % {'role1': role1, 'role2': role2}
class MissingRolesFile(Exception): class MissingRolesFile(Exception):
def __init__(self, rolefile): def __init__(self, rolefile):
self.rolefile = rolefile self.rolefile = rolefile
self.log = "fail to open role file '%(rolefile)s'" % { 'rolefile' : rolefile} self.log = "fail to open role file '%(rolefile)s'" % {'rolefile': rolefile}
class MissingMainFile(Exception): class MissingMainFile(Exception):
def __init__(self, config): def __init__(self, config):
self.rolefile = rolefile self.rolefile = rolefile
self.log = "fail to open main file '%(config)s'" % { 'rolefile' : rolefile} self.log = "fail to open main file '%(config)s'" % {'rolefile': rolefile}
class MissingAttributesFile(Exception): class MissingAttributesFile(Exception):
def __init__(self, attributesfile): def __init__(self, attributesfile):
self.attributesfile = attributesfile self.attributesfile = attributesfile
self.log = "fail to open attributes file '%(attributesfile)s'" % { 'attributesfile' : attributesfile} self.log = "fail to open attributes file '%(attributesfile)s'" % {'attributesfile': attributesfile}
class BackendModuleLoadingFail(Exception): class BackendModuleLoadingFail(Exception):
def __init__(self, module): def __init__(self, module):
self.module = module self.module = module
self.log = "module '%(module)s' not in python path" % {'module': module} self.log = "module '%(module)s' not in python path" % {'module': module}
class BackendModuleInitFail(Exception): class BackendModuleInitFail(Exception):
def __init__(self, module): def __init__(self, module):
self.module = module self.module = module
self.log = "fail to init module '%(module)s'" % {'module': module} self.log = "fail to init module '%(module)s'" % {'module': module}
class WrongParamValue(Exception): class WrongParamValue(Exception):
def __init__(self, param, section, possible_values): def __init__(self, param, section, possible_values):
self.possible_values = possible_values self.possible_values = possible_values
@ -79,19 +92,22 @@ class WrongParamValue(Exception):
possible_values_str = string.join(possible_values, ', ') possible_values_str = string.join(possible_values, ', ')
self.log = "wrong value for param '%(param)s' in section '%(section)s', possible values are [%(values)s]" % {'param': param, 'section': section, 'values': possible_values_str} self.log = "wrong value for param '%(param)s' in section '%(section)s', possible values are [%(values)s]" % {'param': param, 'section': section, 'values': possible_values_str}
class DumplicateUserKey(Exception): class DumplicateUserKey(Exception):
def __init__(self, attrid1, attrid2): def __init__(self, attrid1, attrid2):
self.attrid1 = attrid1 self.attrid1 = attrid1
self.attrid2 = attrid2 self.attrid2 = attrid2
self.log = "duplicate key in '%(attrid1)s' and '%(attrid2)s'" % {'attrid1': attrid1, 'attrid2': attrid2} self.log = "duplicate key in '%(attrid1)s' and '%(attrid2)s'" % {'attrid1': attrid1, 'attrid2': attrid2}
class MissingUserKey(Exception): class MissingUserKey(Exception):
def __init__(self): def __init__(self):
self.log = "missing key" self.log = "missing key"
class WrongAttributeType(Exception): class WrongAttributeType(Exception):
def __init__(self, key, section, ymlfile): def __init__(self, key, section, ymlfile):
self.key = key self.key = key
self.section = section self.section = section
self.ymlfile = ymlfile self.ymlfile = ymlfile
self.log = "wrong attribute type '%(key)s' in section '%(section)s' inside file '%(ymlfile)s'" % {'key': key, 'section': section, 'ymlfile': ymlfile } self.log = "wrong attribute type '%(key)s' in section '%(section)s' inside file '%(ymlfile)s'" % {'key': key, 'section': section, 'ymlfile': ymlfile}

View File

@ -31,8 +31,8 @@ class PPolicy(ldapcherry.ppolicy.PPolicy):
def info(self): def info(self):
return \ return \
"* Minimum length: %(len)n\n"\ "* Minimum length: %(len)n\n" \
"* Minimum number of uppercase characters: %(upper)n\n"\ "* Minimum number of uppercase characters: %(upper)n\n" \
"* Minimum number of digits: %(digit)n" % { "* Minimum number of digits: %(digit)n" % {
'upper': self.min_upper, 'upper': self.min_upper,
'len': self.min_length, 'len': self.min_length,

View File

@ -14,20 +14,22 @@ from yaml.resolver import *
class RelationError(Exception): class RelationError(Exception):
def __init__(self, key, value): def __init__(self, key, value):
self.key = key self.key = key
self.value = value self.value = value
class DumplicatedKey(Exception): class DumplicatedKey(Exception):
def __init__(self, host, key): def __init__(self, host, key):
self.host = host self.host = host
self.key = key self.key = key
import yaml import yaml
try: try:
from yaml import CLoader as Loader, CDumper as Dumper from yaml import CLoader as Loader, CDumper as Dumper
except ImportError: except ImportError:
from yaml import Loader, Dumper from yaml import Loader, Dumper
# PyYaml wrapper that loads yaml files throwing an exception # PyYaml wrapper that loads yaml files throwing an exception
#if a key is dumplicated #if a key is dumplicated

View File

@ -15,12 +15,14 @@ from ldapcherry.pyyamlwrapper import DumplicatedKey
from ldapcherry.exceptions import DumplicateRoleKey, MissingKey, DumplicateRoleContent, MissingRolesFile, MissingRole from ldapcherry.exceptions import DumplicateRoleKey, MissingKey, DumplicateRoleContent, MissingRolesFile, MissingRole
import yaml import yaml
class CustomDumper(yaml.SafeDumper): class CustomDumper(yaml.SafeDumper):
"A custom YAML dumper that never emits aliases" "A custom YAML dumper that never emits aliases"
def ignore_aliases(self, _data): def ignore_aliases(self, _data):
return True return True
class Roles: class Roles:
def __init__(self, role_file): def __init__(self, role_file):
@ -141,7 +143,7 @@ class Roles:
self.group2roles[b][g] = Set([]) self.group2roles[b][g] = Set([])
self.group2roles[b][g].add(roleid) self.group2roles[b][g].add(roleid)
parent_roles[roleid]=[] parent_roles[roleid] = []
for roleid2 in self.flatten: for roleid2 in self.flatten:
role2 = copy.deepcopy(self.flatten[roleid2]) role2 = copy.deepcopy(self.flatten[roleid2])
if self._is_parent(roleid, roleid2): if self._is_parent(roleid, roleid2):