215 lines
7.6 KiB
Python
Executable File
215 lines
7.6 KiB
Python
Executable File
#!/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": "kiskaadee@roadtotech.me",
|
||
"displayName": "kiskaadee",
|
||
"firstName": "Andrés",
|
||
"lastName": "Cortés",
|
||
"recoveryEmail": "fcortesbio@gmail.com",
|
||
"groups": ["admins", "dev"],
|
||
},
|
||
{
|
||
"id": "lusm1302",
|
||
"email": "lusm1302@roadtotech.me",
|
||
"displayName": "Lu.",
|
||
"firstName": "Luisa",
|
||
"lastName": "Santos",
|
||
"recoveryEmail": "luisita13029999@gmail.com",
|
||
"groups": ["users"],
|
||
},
|
||
{
|
||
"id": "misa0728",
|
||
"email": "misa0728@roadtotech.me",
|
||
"displayName": "Misa",
|
||
"firstName": "Isabel",
|
||
"lastName": "Anacona",
|
||
"recoveryEmail": "icdf0728@gmail.com",
|
||
"groups": ["users"],
|
||
},
|
||
{
|
||
"id": "valenvg",
|
||
"email": "valenvg@roadtotech.me",
|
||
"displayName": "Valen",
|
||
"firstName": "Valentina",
|
||
"lastName": "Vega",
|
||
"recoveryEmail": "vegavalentina069@gmail.com",
|
||
"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.")
|
||
|
||
# Ensure custom recovery-email attribute exists in schema
|
||
schema_res = query_graphql(LLDAP_URL, token, "{ schema { userSchema { attributes { name } } } }")
|
||
existing_attrs = [
|
||
a["name"]
|
||
for a in schema_res.get("data", {}).get("schema", {}).get("userSchema", {}).get("attributes", [])
|
||
]
|
||
if "recovery-email" not in existing_attrs:
|
||
print(" ➕ Adding custom schema attribute: recovery-email...")
|
||
add_attr_mutation = (
|
||
'mutation { addUserAttribute(name: "recovery-email", attributeType: STRING, '
|
||
'isList: false, isVisible: true, isEditable: true) { ok } }'
|
||
)
|
||
query_graphql(LLDAP_URL, token, add_attr_mutation)
|
||
|
||
# 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"]
|
||
rec_attr = (
|
||
f'insertAttributes: [{{ name: "recovery-email", value: ["{user["recoveryEmail"]}"] }}]'
|
||
if "recoveryEmail" in user
|
||
else ""
|
||
)
|
||
first_name = f'firstName: "{user["firstName"]}",' if "firstName" in user else ""
|
||
last_name = f'lastName: "{user["lastName"]}",' if "lastName" in user else ""
|
||
|
||
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']}",
|
||
{first_name}
|
||
{last_name}
|
||
{rec_attr}
|
||
}}) {{
|
||
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; syncing attributes...")
|
||
update_mutation = f"""
|
||
mutation {{
|
||
updateUser(user: {{
|
||
id: "{uid}",
|
||
email: "{user['email']}",
|
||
displayName: "{user['displayName']}",
|
||
{first_name}
|
||
{last_name}
|
||
{rec_attr}
|
||
}}) {{
|
||
ok
|
||
}}
|
||
}}
|
||
"""
|
||
query_graphql(LLDAP_URL, token, update_mutation)
|
||
|
||
# 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()
|