Verified Commit 28831266 authored by Jakob Moser's avatar Jakob Moser
Browse files

Add basic proof of concept script

parent 18b79e5d
Loading
Loading
Loading
Loading
+66 −0
Original line number Diff line number Diff line
#!/usr/bin/env -S uv run --script
#
# /// script
# requires-python = ">=3.12"
# dependencies = [
#   "typer",
#   "ldap @ git+https://gitlab.cl.uni-heidelberg.de/moser/ldap.git"
# ]
# ///
from ldap3 import Connection
from ldap3.utils.dn import escape_rdn


import os
from typing import Annotated
import typer

# You could replace this library from the CL GitLab with a few lines of code, so this dependency is highly not necessary.
# It is just more comfortable :)
# https://gitlab.cl.uni-heidelberg.de/moser/ldap/-/blob/master/src/ldap/directories.py
from ldap.directories import uni_id_directory

type UniId = str
type Password = str

def _get_connection(bind_uni_id: UniId, bind_password: Password) -> Connection:
    """
    Return a connection to the Uni LDAP directory, with the given bind user credentials.
    """
    # Get user principal name (UPN).
    # See https://gitlab.cl.uni-heidelberg.de/moser/ldap/-/tree/master?ref_type=heads#user-principal-name
    upn = f"{bind_uni_id}@uni-heidelberg.de"
    return Connection(uni_id_directory.server, user=upn, password=bind_password)


def _get_credentials() -> tuple[UniId, Password]:
    uni_id_from_env = os.getenv("BIND_UNI_ID")
    password_from_env = os.getenv("BIND_PASSWORD")

    if not uni_id_from_env:
        raise ValueError("Please provide a bind Uni ID as env variable, e.g., using: export BIND_UNI_ID=\"ab123\"")
        
    if not password_from_env:
        raise ValueError("Please provide a bind password as env variable, e.g., using: read -s BIND_PASSWORD; export BIND_PASSWORD")

    return uni_id_from_env, password_from_env



def main(
    uni_id: Annotated[
        str, typer.Argument(help="Uni ID to query")
    ],
) -> None:
    """
    """
    credentials = _get_credentials()
    connection = _get_connection(*credentials)

    with connection:
        connection.search("dc=ad,dc=uni-heidelberg,dc=de", f"(cn={escape_rdn(uni_id)})", attributes=["*"])
        print(connection.entries)


if __name__ == "__main__":
    typer.run(main)