57 lines
1.4 KiB
Python
57 lines
1.4 KiB
Python
import sys
|
|
import json
|
|
import os
|
|
from ldap3 import Server, Connection, SUBTREE
|
|
from ldap3.utils.conv import escape_filter_chars
|
|
|
|
username = os.environ.get("username", "").strip()
|
|
password = os.environ.get("password", "")
|
|
|
|
if not username or not password:
|
|
sys.exit(1)
|
|
|
|
LDAP_URL = "ldap://127.0.0.1"
|
|
LDAP_PORT = 389
|
|
BASE_DN = "ou=users,dc=zakobar,dc=com"
|
|
RO_DN = "cn=readonly,dc=zakobar,dc=com"
|
|
RO_PASS_FILE = "/run/secrets/ldap-ro-password"
|
|
|
|
try:
|
|
with open(RO_PASS_FILE) as f:
|
|
ro_password = f.read().strip()
|
|
if not ro_password:
|
|
sys.exit(1)
|
|
|
|
server = Server(LDAP_URL, port=LDAP_PORT)
|
|
|
|
# Step 1: search-bind as readonly to find user DN + display name
|
|
ro_conn = Connection(server, user=RO_DN, password=ro_password)
|
|
if not ro_conn.bind():
|
|
sys.exit(1)
|
|
|
|
ro_conn.search(
|
|
BASE_DN,
|
|
f"(uid={escape_filter_chars(username)})",
|
|
search_scope=SUBTREE,
|
|
attributes=["cn", "uid"],
|
|
)
|
|
|
|
if not ro_conn.entries:
|
|
sys.exit(1)
|
|
|
|
user_dn = ro_conn.entries[0].entry_dn
|
|
display_name = str(ro_conn.entries[0].cn)
|
|
ro_conn.unbind()
|
|
|
|
# Step 2: bind as user to verify password
|
|
user_conn = Connection(server, user=user_dn, password=password)
|
|
if not user_conn.bind():
|
|
sys.exit(1)
|
|
user_conn.unbind()
|
|
|
|
print(json.dumps({"name": display_name}))
|
|
sys.exit(0)
|
|
|
|
except Exception:
|
|
sys.exit(1)
|