-
Notifications
You must be signed in to change notification settings - Fork 93
/
keycloak.py
190 lines (155 loc) · 5.65 KB
/
keycloak.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
import json
import logging
import os
from urllib.parse import urljoin
import keycloak
import requests
import rich
from _nebari.stages.kubernetes_ingress import CertificateEnum
from nebari import schema
logger = logging.getLogger(__name__)
def do_keycloak(config: schema.Main, *args):
# suppress insecure warnings
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
keycloak_admin = get_keycloak_admin_from_config(config)
if args[0] == "adduser":
if len(args) < 2:
raise ValueError(
"keycloak command 'adduser' requires `username [password]`"
)
username = args[1]
password = args[2] if len(args) >= 3 else None
create_user(keycloak_admin, username, password, domain=config.domain)
elif args[0] == "listusers":
list_users(keycloak_admin)
else:
raise ValueError(f"unknown keycloak command {args[0]}")
def create_user(
keycloak_admin: keycloak.KeycloakAdmin,
username: str,
password: str = None,
groups=None,
email=None,
domain=None,
enabled=True,
):
payload = {
"username": username,
"groups": groups or ["/developer"],
"email": email or f"{username}@{domain or 'example.com'}",
"enabled": enabled,
}
if password:
payload["credentials"] = [
{"type": "password", "value": password, "temporary": False}
]
else:
rich.print(
f"Creating user=[green]{username}[/green] without password (none supplied)"
)
user = keycloak_admin.create_user(payload)
rich.print(f"Created user=[green]{username}[/green]")
return user
def list_users(keycloak_admin: keycloak.KeycloakAdmin):
num_users = keycloak_admin.users_count()
print(f"{num_users} Keycloak Users")
user_format = "{username:32} | {email:32} | {groups}"
print(user_format.format(username="username", email="email", groups="groups"))
print("-" * 120)
for user in keycloak_admin.get_users():
user_groups = [_["name"] for _ in keycloak_admin.get_user_groups(user["id"])]
print(
user_format.format(
username=user["username"], email=user["email"], groups=user_groups
)
)
def get_keycloak_admin_from_config(config: schema.Main):
keycloak_server_url = os.environ.get(
"KEYCLOAK_SERVER_URL", f"https://{config.domain}/auth/"
)
keycloak_username = os.environ.get("KEYCLOAK_ADMIN_USERNAME", "root")
keycloak_password = os.environ.get(
"KEYCLOAK_ADMIN_PASSWORD", config.security.keycloak.initial_root_password
)
should_verify_tls = config.certificate.type != CertificateEnum.selfsigned
try:
keycloak_admin = keycloak.KeycloakAdmin(
server_url=keycloak_server_url,
username=keycloak_username,
password=keycloak_password,
realm_name=os.environ.get("KEYCLOAK_REALM", "nebari"),
user_realm_name="master",
auto_refresh_token=("get", "put", "post", "delete"),
verify=should_verify_tls,
)
except (
keycloak.exceptions.KeycloakConnectionError,
keycloak.exceptions.KeycloakAuthenticationError,
) as e:
raise ValueError(f"Failed to connect to Keycloak server: {e}")
return keycloak_admin
def keycloak_rest_api_call(config: schema.Main = None, request: str = None):
"""Communicate directly with the Keycloak REST API by passing it a request"""
keycloak_server_url = os.environ.get(
"KEYCLOAK_SERVER_URL", f"https://{config.domain}/auth/"
)
keycloak_admin_username = os.environ.get("KEYCLOAK_ADMIN_USERNAME", "root")
keycloak_admin_password = os.environ.get(
"KEYCLOAK_ADMIN_PASSWORD",
config.security.keycloak.initial_root_password,
)
try:
# Get `token` to interact with Keycloak Admin
url = urljoin(
keycloak_server_url, "realms/master/protocol/openid-connect/token"
)
headers = {
"Content-Type": "application/x-www-form-urlencoded",
}
data = {
"username": keycloak_admin_username,
"password": keycloak_admin_password,
"grant_type": "password",
"client_id": "admin-cli",
}
response = requests.post(
url=url,
headers=headers,
data=data,
verify=False,
)
if response.status_code == 200:
token = json.loads(response.content.decode())["access_token"]
else:
raise ValueError(
f"Unable to retrieve Keycloak API token. Status code: {response.status_code}"
)
# Send request to Keycloak REST API
method, endpoint = request.split()
url = urljoin(
urljoin(keycloak_server_url, "admin/realms/"), endpoint.lstrip("/")
)
headers = {
"Accept": "application/json",
"Authorization": f"Bearer {token}",
}
response = requests.request(
method=method, url=url, headers=headers, verify=False
)
if response.status_code == 200:
content = json.loads(response.content.decode())
return content
else:
raise ValueError(
f"Unable to communicate with Keycloak API. Status code: {response.status_code}"
)
except requests.exceptions.RequestException as e:
raise e
def export_keycloak_users(config: schema.Main, realm: str):
request = f"GET /{realm}/users"
users = keycloak_rest_api_call(config, request=request)
return {
"realm": realm,
"users": users,
}