ldapweb/webapp/context.py

58 lines
1.4 KiB
Python

import random
import string
import hashlib
import flask
import ldap
from webapp import app, config, validation, avatar
class Attr(object):
def __init__(self, name, value):
name = validation.sanitize_ldap(name)
self.name = name
self.readable_name = config.readable_names.get(name, name)
self.value = value
self.uid = hashlib.sha1(name.encode('utf-8') + value).hexdigest()
def __str__(self):
return self.value.decode('utf-8')
def get_dn():
return flask.session.get('dn')
def get_connection(dn = None):
dn = dn or get_dn()
return app.connections[dn]
def get_admin_connection():
conn = app.connections[config.ldap_admin_dn]
if not conn:
conn = app.connections.bind(config.ldap_admin_dn, config.ldap_admin_password)
return conn
def get_profile():
return app.profiles[get_dn()]
def refresh_profile(dn=None):
dn = dn or get_dn()
conn = get_connection(dn)
if not conn:
return # no session, nothing to refresh i guess
res = conn.search_s(dn, ldap.SCOPE_SUBTREE)
assert(len(res) == 1)
profile = {}
for attr, vs in res[0][1].items():
for v in vs:
a = Attr(attr, v)
profile[a.uid] = a
if attr == 'uid':
user_uid = v.decode('utf-8')
app.profiles[dn] = profile
# bust avatar cache
if user_uid:
avatar.cache.reset_user(user_uid)
avatar.hash_cache.reset()
return profile