import ldap

from webapp import lru, config

class LDAPConnectionPool(lru.LRUPool):
    def __init__(self, url, use_tls=True, **kw):
        lru.LRUPool.__init__(self, **kw)
        self.use_tls = use_tls
        self.url = url
        self.admin_dn = config.admin_dn
        self.admin_pw = config.admin_pw
    @lru.locked
    def bind(self, dn, password):
        conn = ldap.initialize(self.url)
        if(self.use_tls):
            conn.start_tls_s()
        conn.simple_bind_s(dn, password)
        return self._insert(dn, conn)
    def unbind(self, dn):
        return self.drop(dn)

class TokenPool(lru.LRUPool):
    @lru.locked
    def find_owner(self, token):
        for k, v in self.pool.items():
            if v[0] == token:
                return k
        return None


