Add new script and some docs

main
decentral1se 2 years ago
parent 7a3af5bc96
commit ab248fb9c3
Signed by: decentral1se
GPG Key ID: 92DAD76BD9567B8A
  1. 2
      .gitignore
  2. 22
      README.md
  3. 69
      add-users-keycloak-api.py
  4. 4
      add-users-keycloak.py

2
.gitignore vendored

@ -1,4 +1,4 @@
*.mkv
*.mp3
*.mp4
emails.txt
*.txt

@ -1,3 +1,25 @@
# toolshed
Bits and bobs.
## add-users-keycloak.py
> **DEPRECATED**: user
Attempt to create users using the local command-line client.
## add-users-keycloak-api.py
Create users using the REST API.
```
$ export KEYCLOAK_DOMAIN=login.lumbung.space
$ export KEYCLOAK_REALM=lumbung-space
$ export KEYCLOAK_CLIENT_SECRET=foobar
$ python3 -m venv .venv && source .venv/bin/activate
$ pip install -r requirements.txt
$ cat mycoolemail@foobar.com > accounts.txt # the data source
$ ./add-users-keycloak-api.py
```
`accounts.txt` just needs an email on each new line.

@ -0,0 +1,69 @@
#!/usr/bin/env python3
# See https://python-keycloak-client.readthedocs.io/en/latest/
import json
from os import environ
from os.path import exists
from pathlib import Path
from keycloak import KeycloakAdmin
def init_keycloak():
KEYCLOAK_DOMAIN = environ.get("KEYCLOAK_DOMAIN")
KEYCLOAK_REALM = environ.get("KEYCLOAK_REALM")
KEYCLOAK_CLIENT_SECRET = environ.get("KEYCLOAK_CLIENT_SECRET")
client = KeycloakAdmin(
server_url=f"https://{KEYCLOAK_DOMAIN}/auth/",
realm_name=KEYCLOAK_REALM,
client_secret_key=KEYCLOAK_CLIENT_SECRET,
verify=True,
)
return client
def confirm():
answer = ""
while answer not in ["y", "n"]:
answer = input("OK to continue [Y/N]? ").lower()
return answer == "y"
if not exists(Path("accounts.txt").absolute()):
print("Missing accounts.txt!")
exit(1)
with open("emails.txt") as handle:
emails = handle.readlines()
keycloak = init_keycloak()
for email in emails:
username = email.split("@")[0].strip()
print(f"processing {email} now...")
print(f"deriving {username} from {email} for account creation...")
payload = {
"email": email,
"username": username,
"enabled": True,
"realmRoles": [
"user_default",
],
}
try:
user_id = keycloak.create_user(payload, exist_ok=False)
keycloak.send_update_account(
user_id=user_id, payload=json.dumps(["UPDATE_PASSWORD", "UPDATE_PROFILE"])
)
keycloak.send_verify_email(user_id=user_id)
except Exception as exception:
print(f"Keycloak user registration failed, saw: {exception}")
if not confirm():
print("Bailing out on request...")
exit(1)

@ -1,5 +1,9 @@
#!/usr/bin/env python3
#######################################################
# WARNING: Use the add-users-keycloak-api.py instead!!!
#######################################################
# See https://www.keycloak.org/docs/latest/server_admin/#user-operations
# The following command must be run beforehand to log into the keycloak:
# /opt/jboss/keycloak/bin/kcadm.sh config credentials --server http://localhost:8080/auth --realm master --user admin

Loading…
Cancel
Save