pyceo/ceod/model/UWLDAPService.py

49 lines
1.6 KiB
Python
Raw Normal View History

2021-08-03 10:09:07 -04:00
from typing import Union, List
2021-07-23 20:08:22 -04:00
2021-08-15 01:04:49 -04:00
import ldap3
2021-07-23 20:08:22 -04:00
from zope import component
from zope.interface import implementer
from .UWLDAPRecord import UWLDAPRecord
2021-08-15 01:04:49 -04:00
from .utils import dn_to_uid
2021-07-23 20:08:22 -04:00
from ceo_common.interfaces import IUWLDAPService, IConfig
@implementer(IUWLDAPService)
class UWLDAPService:
def __init__(self):
cfg = component.getUtility(IConfig)
self.uwldap_server_url = cfg.get('uwldap_server_url')
self.uwldap_base = cfg.get('uwldap_base')
2021-08-15 01:04:49 -04:00
def _get_conn(self) -> ldap3.Connection:
return ldap3.Connection(
self.uwldap_server_url, auto_bind=True, read_only=True,
raise_exceptions=True)
2021-08-03 10:09:07 -04:00
def get_user(self, username: str) -> Union[UWLDAPRecord, None]:
2021-08-15 01:04:49 -04:00
conn = self._get_conn()
conn.search(
self.uwldap_base, f'(uid={username})',
attributes=UWLDAPRecord.ldap_attributes, size_limit=1)
if not conn.entries:
2021-07-23 20:08:22 -04:00
return None
2021-08-15 01:04:49 -04:00
return UWLDAPRecord.deserialize_from_ldap(conn.entries[0])
2021-08-03 10:09:07 -04:00
def get_programs_for_users(self, usernames: List[str]) -> List[Union[str, None]]:
filter_str = '(|' + ''.join([f'(uid={uid})' for uid in usernames]) + ')'
programs = [None] * len(usernames)
user_indices = {uid: i for i, uid in enumerate(usernames)}
2021-08-15 01:04:49 -04:00
conn = self._get_conn()
conn.search(
self.uwldap_base, filter_str, attributes=['ou'],
size_limit=len(usernames))
for entry in conn.entries:
uid = dn_to_uid(entry.entry_dn)
2021-08-03 10:09:07 -04:00
idx = user_indices[uid]
2021-08-15 01:04:49 -04:00
program = entry.ou.value
2021-08-03 10:09:07 -04:00
if program:
programs[idx] = program
return programs