#!/usr/bin/env python3 """ Bootstrap LLDAP directory with baseline groups and users. Zero external dependencies (uses standard library urllib and json). """ import json import os import sys import urllib.error import urllib.request LLDAP_URL = os.environ.get("LLDAP_URL", "http://127.0.0.1:17170") ADMIN_USER = os.environ.get("LLDAP_ADMIN_USER", "admin") ADMIN_PASS = os.environ.get("LLDAP_LDAP_USER_PASS") or os.environ.get("AUTHELIA_LDAP_PASSWORD", "") INITIAL_GROUPS = ["admins", "dev", "users"] INITIAL_USERS = [ { "id": "kiskaadee", "email": "fcortesbio@gmail.com", "displayName": "kiskaadee", "groups": ["admins", "dev"], }, { "id": "misa", "email": "icdf0728@gmail.com", "displayName": "misa", "groups": ["users"], }, { "id": "valenvg", "email": "vegavalentina069@gmail.com", "displayName": "valenvg", "groups": ["users"], }, ] def post_json(url, data, token=None): body = json.dumps(data).encode("utf-8") headers = {"Content-Type": "application/json"} if token: headers["Authorization"] = f"Bearer {token}" req = urllib.request.Request(url, data=body, headers=headers, method="POST") try: with urllib.request.urlopen(req, timeout=10) as resp: return json.loads(resp.read().decode("utf-8")) except urllib.error.HTTPError as e: error_body = e.read().decode("utf-8") try: return json.loads(error_body) except (json.JSONDecodeError, UnicodeDecodeError): return {"error": str(e), "details": error_body} def login(base_url, username, password): url = f"{base_url}/auth/simple/login" res = post_json(url, {"username": username, "password": password}) if "token" in res: return res["token"] raise RuntimeError(f"Authentication to LLDAP failed: {res}") def query_graphql(base_url, token, query_str, variables=None): url = f"{base_url}/api/graphql" payload = {"query": query_str} if variables: payload["variables"] = variables res = post_json(url, payload, token=token) return res def bootstrap(): if not ADMIN_PASS: print("āŒ Error: Admin password not provided. Set LLDAP_LDAP_USER_PASS or AUTHELIA_LDAP_PASSWORD.") sys.exit(1) print(f"šŸ”— Connecting to LLDAP at {LLDAP_URL}...") try: token = login(LLDAP_URL, ADMIN_USER, ADMIN_PASS) print(" šŸ”‘ Successfully authenticated with LLDAP admin.") except (urllib.error.URLError, RuntimeError, OSError) as e: print(f"āŒ Failed to login to LLDAP: {e}") sys.exit(1) # 1. Fetch existing groups groups_res = query_graphql(LLDAP_URL, token, "{ groups { id displayName } }") existing_groups = {g["displayName"]: g["id"] for g in groups_res.get("data", {}).get("groups", [])} print(f" Existing groups: {list(existing_groups.keys())}") for group_name in INITIAL_GROUPS: if group_name not in existing_groups: print(f" āž• Creating group: {group_name}...") mutation = f'mutation {{ createGroup(name: "{group_name}") {{ id displayName }} }}' res = query_graphql(LLDAP_URL, token, mutation) if "errors" in res: print(f" āš ļø Warning creating group {group_name}: {res['errors']}") else: new_group = res.get("data", {}).get("createGroup", {}) existing_groups[group_name] = new_group.get("id") print(f" āœ… Group {group_name} created (ID: {new_group.get('id')})") else: print(f" ā„¹ļø Group {group_name} already exists.") # 2. Fetch existing users users_res = query_graphql(LLDAP_URL, token, "{ users { id email displayName } }") existing_users = {u["id"]: u for u in users_res.get("data", {}).get("users", [])} print(f" Existing users: {list(existing_users.keys())}") for user in INITIAL_USERS: uid = user["id"] if uid not in existing_users: print(f" āž• Creating user: {uid} ({user['email']})...") mutation = f""" mutation {{ createUser(user: {{ id: "{uid}", email: "{user['email']}", displayName: "{user['displayName']}" }}) {{ id email displayName }} }} """ res = query_graphql(LLDAP_URL, token, mutation) if "errors" in res: print(f" āš ļø Warning creating user {uid}: {res['errors']}") else: print(f" āœ… User {uid} created.") else: print(f" ā„¹ļø User {uid} already exists.") # Assign user to groups for group_name in user.get("groups", []): group_id = existing_groups.get(group_name) if group_id is not None: add_res = query_graphql( LLDAP_URL, token, f'mutation {{ addUserToGroup(userId: "{uid}", groupId: {group_id}) {{ ok }} }}', ) if "errors" in add_res: # Usually errors if user already member pass else: print(f" šŸ”— Associated {uid} with group '{group_name}'") print("\n✨ LLDAP user directory bootstrap completed successfully!") if __name__ == "__main__": bootstrap()