singleton

This commit is contained in:
root 2012-10-25 20:40:44 +02:00
parent f63cc8d5d0
commit 54c2dbb64b

View file

@ -188,33 +188,42 @@ class YunoHostError(Exception):
else: else:
self.desc = code self.desc = code
def singleton(cls):
instances = {}
def get_instance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return get_instance
@singleton
class YunoHostLDAP(object): class YunoHostLDAP(object):
""" Specific LDAP functions for YunoHost """ """ Specific LDAP functions for YunoHost """
conn = None
def __enter__(self, password=False): def __enter__(self, password=False):
self.__init__(password)
return self
def __init__(self, password=False):
""" """
Connect to LDAP base Connect to LDAP base
Initialize to localhost, base yunohost.org, prompt for password Initialize to localhost, base yunohost.org, prompt for password
""" """
if self.conn is None: self.conn = ldap.initialize('ldap://localhost:389')
self.conn = ldap.initialize('ldap://localhost:389') self.base = 'dc=yunohost,dc=org'
self.base = 'dc=yunohost,dc=org' if password:
if password: self.pwd = password
self.pwd = password else:
else:
try:
self.pwd = getpass.getpass(colorize(_('Admin Password: '), 'yellow'))
except KeyboardInterrupt, EOFError:
raise YunoHostError(125, _("Interrupted"))
try: try:
self.conn.simple_bind_s('cn=admin,' + self.base, self.pwd) self.pwd = getpass.getpass(colorize(_('Admin Password: '), 'yellow'))
except ldap.INVALID_CREDENTIALS: except KeyboardInterrupt, EOFError:
raise YunoHostError(13, _('Invalid credentials')) raise YunoHostError(125, _("Interrupted"))
return self try:
self.conn.simple_bind_s('cn=admin,' + self.base, self.pwd)
except ldap.INVALID_CREDENTIALS:
raise YunoHostError(13, _('Invalid credentials'))
def __exit__(self, type, value, traceback): def __exit__(self, type, value, traceback):
self.disconnect() self.disconnect()