|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +import argparse |
| 4 | +import json |
| 5 | +import sys |
| 6 | +import hashlib |
| 7 | +import base64 |
| 8 | +import os |
| 9 | + |
| 10 | + |
| 11 | +ITERATIONS = 180000 |
| 12 | + |
| 13 | + |
| 14 | +def main(): |
| 15 | + parser = argparse.ArgumentParser() |
| 16 | + parser.add_argument("--external-origin", type=str, required=True) |
| 17 | + parser.add_argument("--admin-email", type=str, required=True) |
| 18 | + parser.add_argument("--admin-password", type=str, required=True) |
| 19 | + args = parser.parse_args() |
| 20 | + |
| 21 | + realm = json.load(sys.stdin) |
| 22 | + |
| 23 | + # Replace admin email placeholder |
| 24 | + for user in realm.get("users", []): |
| 25 | + if user.get("id") == "admin": |
| 26 | + user["username"] = args.admin_email |
| 27 | + user["email"] = args.admin_email |
| 28 | + |
| 29 | + # Update password credentials |
| 30 | + for credential in user.get("credentials", []): |
| 31 | + if credential.get("type") == "password": |
| 32 | + # Generate a random salt |
| 33 | + salt = os.urandom(16) |
| 34 | + salt_b64 = base64.b64encode(salt).decode('utf-8') |
| 35 | + |
| 36 | + # Hash the password with the salt |
| 37 | + pwd_hash = hashlib.pbkdf2_hmac('sha256', args.admin_password.encode('utf-8'), salt, ITERATIONS) |
| 38 | + pwd_hash_b64 = base64.b64encode(pwd_hash).decode('utf-8') |
| 39 | + |
| 40 | + # Set credential data in Keycloak format |
| 41 | + credential["credentialData"] = json.dumps({"hashIterations": ITERATIONS, "algorithm": "pbkdf2-sha256"}) |
| 42 | + credential["secretData"] = json.dumps({"salt": salt_b64, "value": pwd_hash_b64}) |
| 43 | + |
| 44 | + # Replace EXTERNAL_ORIGIN placeholders in clients |
| 45 | + for client in realm.get("clients", []): |
| 46 | + # Update redirectUris |
| 47 | + if "redirectUris" in client: |
| 48 | + client["redirectUris"] = [uri.replace("{EXTERNAL_ORIGIN}", args.external_origin) |
| 49 | + for uri in client["redirectUris"]] |
| 50 | + |
| 51 | + # Update webOrigins |
| 52 | + if "webOrigins" in client: |
| 53 | + client["webOrigins"] = [origin.replace("{EXTERNAL_ORIGIN}", args.external_origin) |
| 54 | + for origin in client["webOrigins"]] |
| 55 | + |
| 56 | + # Output the modified realm configuration |
| 57 | + json.dump(realm, sys.stdout, indent=2) |
| 58 | + |
| 59 | + |
| 60 | +if __name__ == "__main__": |
| 61 | + main() |
0 commit comments