You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

747 lines
27 KiB

7 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2017 Marcos Pereira <marcospereira.mpj@gmail.com>
  4. #
  5. # This program is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU Lesser General Public License as published by
  7. # the Free Software Foundation, either version 3 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU Lesser General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU Lesser General Public License
  16. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. # Unless otherwise stated in the comments, "id", in e.g. user_id, refers to the
  18. # internal Keycloak server ID, usually a uuid string
  19. from keycloak.urls_patterns import URL_ADMIN_CLIENT_ROLE
  20. from .urls_patterns import \
  21. URL_ADMIN_USERS_COUNT, URL_ADMIN_USER, URL_ADMIN_USER_CONSENTS, \
  22. URL_ADMIN_SEND_UPDATE_ACCOUNT, URL_ADMIN_RESET_PASSWORD, URL_ADMIN_SEND_VERIFY_EMAIL, URL_ADMIN_GET_SESSIONS, \
  23. URL_ADMIN_SERVER_INFO, URL_ADMIN_CLIENTS, URL_ADMIN_CLIENT, URL_ADMIN_CLIENT_ROLES, URL_ADMIN_REALM_ROLES, \
  24. URL_ADMIN_GROUP, URL_ADMIN_GROUPS, URL_ADMIN_GROUP_CHILD, URL_ADMIN_USER_GROUP, URL_ADMIN_GROUP_MEMBERS, \
  25. URL_ADMIN_USER_GROUPS, URL_ADMIN_GROUP_PERMISSIONS, URL_ADMIN_USER_CLIENT_ROLES, URL_ADMIN_USER_STORAGE, \
  26. URL_ADMIN_CLIENT_AUTHZ_SETTINGS, URL_ADMIN_CLIENT_AUTHZ_RESOURCES, URL_ADMIN_IDPS
  27. from .keycloak_openid import KeycloakOpenID
  28. from .exceptions import raise_error_from_response, KeycloakGetError
  29. from .urls_patterns import (
  30. URL_ADMIN_USERS,
  31. )
  32. from .connection import ConnectionManager
  33. import json
  34. class KeycloakAdmin:
  35. def __init__(self, server_url, username, password, realm_name='master', client_id='admin-cli', verify=True):
  36. """
  37. :param server_url: Keycloak server url
  38. :param username: admin username
  39. :param password: admin password
  40. :param realm_name: realm name
  41. :param client_id: client id
  42. :param verify: True if want check connection SSL
  43. """
  44. self._username = username
  45. self._password = password
  46. self._client_id = client_id
  47. self._realm_name = realm_name
  48. # Get token Admin
  49. keycloak_openid = KeycloakOpenID(server_url=server_url, client_id=client_id, realm_name=realm_name,
  50. verify=verify)
  51. self._token = keycloak_openid.token(username, password)
  52. self._connection = ConnectionManager(base_url=server_url,
  53. headers={'Authorization': 'Bearer ' + self.token.get('access_token'),
  54. 'Content-Type': 'application/json'},
  55. timeout=60,
  56. verify=verify)
  57. @property
  58. def realm_name(self):
  59. return self._realm_name
  60. @realm_name.setter
  61. def realm_name(self, value):
  62. self._realm_name = value
  63. @property
  64. def connection(self):
  65. return self._connection
  66. @connection.setter
  67. def connection(self, value):
  68. self._connection = value
  69. @property
  70. def client_id(self):
  71. return self._client_id
  72. @client_id.setter
  73. def client_id(self, value):
  74. self._client_id = value
  75. @property
  76. def username(self):
  77. return self._username
  78. @username.setter
  79. def username(self, value):
  80. self._username = value
  81. @property
  82. def password(self):
  83. return self._password
  84. @password.setter
  85. def password(self, value):
  86. self._password = value
  87. @property
  88. def token(self):
  89. return self._token
  90. @token.setter
  91. def token(self, value):
  92. self._token = value
  93. def get_users(self, query=None):
  94. """
  95. Get users Returns a list of users, filtered according to query parameters
  96. :return: users list
  97. """
  98. params_path = {"realm-name": self.realm_name}
  99. data_raw = self.connection.raw_get(URL_ADMIN_USERS.format(**params_path), **query)
  100. return raise_error_from_response(data_raw, KeycloakGetError)
  101. def get_idps(self):
  102. """
  103. Returns a list of ID Providers,
  104. IdentityProviderRepresentation
  105. https://www.keycloak.org/docs-api/3.3/rest-api/index.html#_identityproviderrepresentation
  106. :return: array IdentityProviderRepresentation
  107. """
  108. params_path = {"realm-name": self.realm_name}
  109. data_raw = self.connection.raw_get(URL_ADMIN_IDPS.format(**params_path))
  110. return raise_error_from_response(data_raw, KeycloakGetError)
  111. def create_user(self, payload):
  112. """
  113. Create a new user Username must be unique
  114. UserRepresentation
  115. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_userrepresentation
  116. :param payload: UserRepresentation
  117. :return: UserRepresentation
  118. """
  119. params_path = {"realm-name": self.realm_name}
  120. exists = self.get_user_id(username=payload['username'])
  121. if exists is not None:
  122. return str(exists)
  123. data_raw = self.connection.raw_post(URL_ADMIN_USERS.format(**params_path),
  124. data=json.dumps(payload))
  125. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201)
  126. def users_count(self):
  127. """
  128. User counter
  129. :return: counter
  130. """
  131. params_path = {"realm-name": self.realm_name}
  132. data_raw = self.connection.raw_get(URL_ADMIN_USERS_COUNT.format(**params_path))
  133. return raise_error_from_response(data_raw, KeycloakGetError)
  134. def get_user_id(self, username):
  135. """
  136. Get internal keycloak user id from username
  137. This is required for further actions against this user.
  138. UserRepresentation
  139. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_userrepresentation
  140. :param username: id in UserRepresentation
  141. :return: user_id
  142. """
  143. params_path = {"realm-name": self.realm_name, "username": username}
  144. data_raw = self.connection.raw_get(URL_ADMIN_USERS.format(**params_path))
  145. data_content = raise_error_from_response(data_raw, KeycloakGetError)
  146. for user in data_content:
  147. this_use_rname = json.dumps(user["username"]).strip('"')
  148. if this_use_rname == username:
  149. return json.dumps(user["id"]).strip('"')
  150. return None
  151. def get_user(self, user_id):
  152. """
  153. Get representation of the user
  154. :param user_id: User id
  155. UserRepresentation: http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_userrepresentation
  156. :return: UserRepresentation
  157. """
  158. params_path = {"realm-name": self.realm_name, "id": user_id}
  159. data_raw = self.connection.raw_get(URL_ADMIN_USER.format(**params_path))
  160. return raise_error_from_response(data_raw, KeycloakGetError)
  161. def get_user_groups(self, user_id):
  162. """
  163. Get user groups Returns a list of groups of which the user is a member
  164. :param user_id: User id
  165. :return: user groups list
  166. """
  167. params_path = {"realm-name": self.realm_name, "id": user_id}
  168. data_raw = self.connection.raw_get(URL_ADMIN_USER_GROUPS.format(**params_path))
  169. return raise_error_from_response(data_raw, KeycloakGetError)
  170. def update_user(self, user_id, payload):
  171. """
  172. Update the user
  173. :param user_id: User id
  174. :param payload: UserRepresentation
  175. :return: Http response
  176. """
  177. params_path = {"realm-name": self.realm_name, "id": user_id}
  178. data_raw = self.connection.raw_put(URL_ADMIN_USER.format(**params_path),
  179. data=json.dumps(payload))
  180. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  181. def delete_user(self, user_id):
  182. """
  183. Delete the user
  184. :param user_id: User id
  185. :return: Http response
  186. """
  187. params_path = {"realm-name": self.realm_name, "id": user_id}
  188. data_raw = self.connection.raw_delete(URL_ADMIN_USER.format(**params_path))
  189. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  190. def set_user_password(self, user_id, password, temporary=True):
  191. """
  192. Set up a password for the user. If temporary is True, the user will have to reset
  193. the temporary password next time they log in.
  194. http://www.keycloak.org/docs-api/3.2/rest-api/#_users_resource
  195. http://www.keycloak.org/docs-api/3.2/rest-api/#_credentialrepresentation
  196. :param user_id: User id
  197. :param password: New password
  198. :param temporary: True if password is temporary
  199. :return:
  200. """
  201. payload = {"type": "password", "temporary": temporary, "value": password}
  202. params_path = {"realm-name": self.realm_name, "id": user_id}
  203. data_raw = self.connection.raw_put(URL_ADMIN_RESET_PASSWORD.format(**params_path),
  204. data=json.dumps(payload))
  205. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  206. def consents_user(self, user_id):
  207. """
  208. Get consents granted by the user
  209. :param user_id: User id
  210. :return: consents
  211. """
  212. params_path = {"realm-name": self.realm_name, "id": user_id}
  213. data_raw = self.connection.raw_get(URL_ADMIN_USER_CONSENTS.format(**params_path))
  214. return raise_error_from_response(data_raw, KeycloakGetError)
  215. def send_update_account(self, user_id, payload, client_id=None, lifespan=None, redirect_uri=None):
  216. """
  217. Send a update account email to the user An email contains a
  218. link the user can click to perform a set of required actions.
  219. :param user_id:
  220. :param payload:
  221. :param client_id:
  222. :param lifespan:
  223. :param redirect_uri:
  224. :return:
  225. """
  226. params_path = {"realm-name": self.realm_name, "id": user_id}
  227. params_query = {"client_id": client_id, "lifespan": lifespan, "redirect_uri": redirect_uri}
  228. data_raw = self.connection.raw_put(URL_ADMIN_SEND_UPDATE_ACCOUNT.format(**params_path),
  229. data=payload, **params_query)
  230. return raise_error_from_response(data_raw, KeycloakGetError)
  231. def send_verify_email(self, user_id, client_id=None, redirect_uri=None):
  232. """
  233. Send a update account email to the user An email contains a
  234. link the user can click to perform a set of required actions.
  235. :param user_id: User id
  236. :param client_id: Client id
  237. :param redirect_uri: Redirect uri
  238. :return:
  239. """
  240. params_path = {"realm-name": self.realm_name, "id": user_id}
  241. params_query = {"client_id": client_id, "redirect_uri": redirect_uri}
  242. data_raw = self.connection.raw_put(URL_ADMIN_SEND_VERIFY_EMAIL.format(**params_path),
  243. data={}, **params_query)
  244. return raise_error_from_response(data_raw, KeycloakGetError)
  245. def get_sessions(self, user_id):
  246. """
  247. Get sessions associated with the user
  248. :param user_id: id of user
  249. UserSessionRepresentation
  250. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_usersessionrepresentation
  251. :return: UserSessionRepresentation
  252. """
  253. params_path = {"realm-name": self.realm_name, "id": user_id}
  254. data_raw = self.connection.raw_get(URL_ADMIN_GET_SESSIONS.format(**params_path))
  255. return raise_error_from_response(data_raw, KeycloakGetError)
  256. def get_server_info(self):
  257. """
  258. Get themes, social providers, auth providers, and event listeners available on this server
  259. ServerInfoRepresentation
  260. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_serverinforepresentation
  261. :return: ServerInfoRepresentation
  262. """
  263. data_raw = self.connection.raw_get(URL_ADMIN_SERVER_INFO)
  264. return raise_error_from_response(data_raw, KeycloakGetError)
  265. def get_groups(self):
  266. """
  267. Get groups belonging to the realm. Returns a list of groups belonging to the realm
  268. GroupRepresentation
  269. http://www.keycloak.org/docs-api/3.2/rest-api/#_grouprepresentation
  270. :return: array GroupRepresentation
  271. """
  272. params_path = {"realm-name": self.realm_name}
  273. data_raw = self.connection.raw_get(URL_ADMIN_GROUPS.format(**params_path))
  274. return raise_error_from_response(data_raw, KeycloakGetError)
  275. def get_group(self, group_id):
  276. """
  277. Get group by id. Returns full group details
  278. GroupRepresentation
  279. http://www.keycloak.org/docs-api/3.2/rest-api/#_grouprepresentation
  280. :return: Keycloak server response (GroupRepresentation)
  281. """
  282. params_path = {"realm-name": self.realm_name, "id": group_id}
  283. data_raw = self.connection.raw_get(URL_ADMIN_GROUP.format(**params_path))
  284. return raise_error_from_response(data_raw, KeycloakGetError)
  285. def get_subgroups(self, group, path):
  286. """
  287. Utility function to iterate through nested group structures
  288. GroupRepresentation
  289. http://www.keycloak.org/docs-api/3.2/rest-api/#_grouprepresentation
  290. :param name: group (GroupRepresentation)
  291. :param path: group path (string)
  292. :return: Keycloak server response (GroupRepresentation)
  293. """
  294. for subgroup in group["subGroups"]:
  295. if subgroup['path'] == path:
  296. return subgroup
  297. elif subgroup["subGroups"]:
  298. for subgroup in group["subGroups"]:
  299. return self.get_subgroups(subgroup, path)
  300. return None
  301. def get_group_members(self, group_id):
  302. """
  303. Get members by group id. Returns group members
  304. GroupRepresentation
  305. http://www.keycloak.org/docs-api/3.2/rest-api/#_userrepresentation
  306. :return: Keycloak server response (UserRepresentation)
  307. """
  308. params_path = {"realm-name": self.realm_name, "id": group_id}
  309. data_raw = self.connection.raw_get(URL_ADMIN_GROUP_MEMBERS.format(**params_path))
  310. return raise_error_from_response(data_raw, KeycloakGetError)
  311. def get_group_by_path(self, path, search_in_subgroups=False):
  312. """
  313. Get group id based on name or path.
  314. A straight name or path match with a top-level group will return first.
  315. Subgroups are traversed, the first to match path (or name with path) is returned.
  316. GroupRepresentation
  317. http://www.keycloak.org/docs-api/3.2/rest-api/#_grouprepresentation
  318. :param path: group path
  319. :param search_in_subgroups: True if want search in the subgroups
  320. :return: Keycloak server response (GroupRepresentation)
  321. """
  322. groups = self.get_groups()
  323. # TODO: Review this code is necessary
  324. for group in groups:
  325. if group['path'] == path:
  326. return group
  327. elif search_in_subgroups and group["subGroups"]:
  328. res = self.get_subgroups(group, path)
  329. if res != None:
  330. return res
  331. return None
  332. def create_group(self, payload, parent=None, skip_exists=False):
  333. """
  334. Creates a group in the Realm
  335. :param payload: GroupRepresentation
  336. :param parent: parent group's id. Required to create a sub-group.
  337. GroupRepresentation
  338. http://www.keycloak.org/docs-api/3.2/rest-api/#_grouprepresentation
  339. :return: Http response
  340. """
  341. name = payload['name']
  342. path = payload['path']
  343. exists = None
  344. if name is None and path is not None:
  345. path="/" + name
  346. elif path is not None:
  347. exists = self.get_group_by_path(path=path, search_in_subgroups=True)
  348. if exists is not None:
  349. return str(exists)
  350. if parent is None:
  351. params_path = {"realm-name": self.realm_name}
  352. data_raw = self.connection.raw_post(URL_ADMIN_GROUPS.format(**params_path),
  353. data=json.dumps(payload))
  354. else:
  355. params_path = {"realm-name": self.realm_name, "id": parent,}
  356. data_raw = self.connection.raw_post(URL_ADMIN_GROUP_CHILD.format(**params_path),
  357. data=json.dumps(payload))
  358. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201, skip_exists=skip_exists)
  359. def group_set_permissions(self, group_id, enabled=True):
  360. """
  361. Enable/Disable permissions for a group. Cannot delete group if disabled
  362. :param group_id: id of group
  363. :param enabled: boolean
  364. :return: Keycloak server response
  365. """
  366. params_path = {"realm-name": self.realm_name, "id": group_id}
  367. data_raw = self.connection.raw_put(URL_ADMIN_GROUP_PERMISSIONS.format(**params_path),
  368. data=json.dumps({"enabled": enabled}))
  369. return raise_error_from_response(data_raw, KeycloakGetError)
  370. def group_user_add(self, user_id, group_id):
  371. """
  372. Add user to group (user_id and group_id)
  373. :param group_id: id of group
  374. :param user_id: id of user
  375. :param group_id: id of group to add to
  376. :return: Keycloak server response
  377. """
  378. params_path = {"realm-name": self.realm_name, "id": user_id, "group-id": group_id}
  379. data_raw = self.connection.raw_put(URL_ADMIN_USER_GROUP.format(**params_path), data=None)
  380. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  381. def group_user_remove(self, user_id, group_id):
  382. """
  383. Remove user from group (user_id and group_id)
  384. :param group_id: id of group
  385. :param user_id: id of user
  386. :param group_id: id of group to add to
  387. :return: Keycloak server response
  388. """
  389. params_path = {"realm-name": self.realm_name, "id": user_id, "group-id": group_id}
  390. data_raw = self.connection.raw_delete(URL_ADMIN_USER_GROUP.format(**params_path))
  391. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  392. def delete_group(self, group_id):
  393. """
  394. Deletes a group in the Realm
  395. :param group_id: id of group to delete
  396. :return: Keycloak server response
  397. """
  398. params_path = {"realm-name": self.realm_name, "id": group_id}
  399. data_raw = self.connection.raw_delete(URL_ADMIN_GROUP.format(**params_path))
  400. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  401. def get_clients(self):
  402. """
  403. Get clients belonging to the realm Returns a list of clients belonging to the realm
  404. ClientRepresentation
  405. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_clientrepresentation
  406. :return: Keycloak server response (ClientRepresentation)
  407. """
  408. params_path = {"realm-name": self.realm_name}
  409. data_raw = self.connection.raw_get(URL_ADMIN_CLIENTS.format(**params_path))
  410. return raise_error_from_response(data_raw, KeycloakGetError)
  411. def get_client(self, client_id):
  412. """
  413. Get representation of the client
  414. ClientRepresentation
  415. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_clientrepresentation
  416. :param client_id: id of client (not client-id)
  417. :return: Keycloak server response (ClientRepresentation)
  418. """
  419. params_path = {"realm-name": self.realm_name, "id": client_id}
  420. data_raw = self.connection.raw_get(URL_ADMIN_CLIENT.format(**params_path))
  421. return raise_error_from_response(data_raw, KeycloakGetError)
  422. def get_client_id(self, client_name):
  423. """
  424. Get internal keycloak client id from client-id.
  425. This is required for further actions against this client.
  426. :param client_name: name in ClientRepresentation
  427. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_clientrepresentation
  428. :return: client_id (uuid as string)
  429. """
  430. clients = self.get_clients()
  431. for client in clients:
  432. if client_name == client.get('name') or client_name == client.get('clientId'):
  433. return client["id"]
  434. return None
  435. def get_client_authz_settings(self, client_id):
  436. """
  437. Get authorization json from client.
  438. :param client_id: id in ClientRepresentation
  439. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_clientrepresentation
  440. :return: Keycloak server response
  441. """
  442. params_path = {"realm-name": self.realm_name, "id": client_id}
  443. data_raw = self.connection.raw_get(URL_ADMIN_CLIENT_AUTHZ_SETTINGS.format(**params_path))
  444. return data_raw
  445. def get_client_authz_resources(self, client_id):
  446. """
  447. Get resources from client.
  448. :param client_id: id in ClientRepresentation
  449. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_clientrepresentation
  450. :return: Keycloak server response
  451. """
  452. params_path = {"realm-name": self.realm_name, "id": client_id}
  453. data_raw = self.connection.raw_get(URL_ADMIN_CLIENT_AUTHZ_RESOURCES.format(**params_path))
  454. return data_raw
  455. def create_client(self, payload, skip_exists=False):
  456. """
  457. Create a client
  458. ClientRepresentation: http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_clientrepresentation
  459. :param skip_exists: Skip if client already exist.
  460. :param payload: ClientRepresentation
  461. :return: Keycloak server response (UserRepresentation)
  462. """
  463. params_path = {"realm-name": self.realm_name}
  464. data_raw = self.connection.raw_post(URL_ADMIN_CLIENTS.format(**params_path),
  465. data=json.dumps(payload))
  466. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201, skip_exists=skip_exists)
  467. def delete_client(self, client_id):
  468. """
  469. Get representation of the client
  470. ClientRepresentation
  471. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_clientrepresentation
  472. :param client_id: keycloak client id (not oauth client-id)
  473. :return: Keycloak server response (ClientRepresentation)
  474. """
  475. params_path = {"realm-name": self.realm_name, "id": client_id}
  476. data_raw = self.connection.raw_delete(URL_ADMIN_CLIENT.format(**params_path))
  477. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  478. def get_realm_roles(self):
  479. """
  480. Get all roles for the realm or client
  481. RoleRepresentation
  482. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_rolerepresentation
  483. :return: Keycloak server response (RoleRepresentation)
  484. """
  485. params_path = {"realm-name": self.realm_name}
  486. data_raw = self.connection.raw_get(URL_ADMIN_REALM_ROLES.format(**params_path))
  487. return raise_error_from_response(data_raw, KeycloakGetError)
  488. def get_client_roles(self, client_id):
  489. """
  490. Get all roles for the client
  491. :param client_id: id of client (not client-id)
  492. RoleRepresentation
  493. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_rolerepresentation
  494. :return: Keycloak server response (RoleRepresentation)
  495. """
  496. params_path = {"realm-name": self.realm_name, "id": client_id}
  497. data_raw = self.connection.raw_get(URL_ADMIN_CLIENT_ROLES.format(**params_path))
  498. return raise_error_from_response(data_raw, KeycloakGetError)
  499. def get_client_role(self, client_id, role_name):
  500. """
  501. Get client role id by name
  502. This is required for further actions with this role.
  503. :param client_id: id of client (not client-id)
  504. :param role_name: roles name (not id!)
  505. RoleRepresentation
  506. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_rolerepresentation
  507. :return: role_id
  508. """
  509. params_path = {"realm-name": self.realm_name, "id": client_id, "role-name": role_name}
  510. data_raw = self.connection.raw_get(URL_ADMIN_CLIENT_ROLE.format(**params_path))
  511. return raise_error_from_response(data_raw, KeycloakGetError)
  512. def get_client_role_id(self, client_id, role_name):
  513. """
  514. Warning: Deprecated
  515. Get client role id by name
  516. This is required for further actions with this role.
  517. :param client_id: id of client (not client-id)
  518. :param role_name: roles name (not id!)
  519. RoleRepresentation
  520. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_rolerepresentation
  521. :return: role_id
  522. """
  523. role = self.get_client_role(client_id, role_name)
  524. return role.get("id")
  525. def create_client_role(self, payload, skip_exists=False):
  526. """
  527. Create a client role
  528. RoleRepresentation
  529. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_rolerepresentation
  530. :param payload: id of client (not client-id), role_name: name of role
  531. :return: Keycloak server response (RoleRepresentation)
  532. """
  533. params_path = {"realm-name": self.realm_name, "id": self.client_id}
  534. data_raw = self.connection.raw_post(URL_ADMIN_CLIENT_ROLES.format(**params_path),
  535. data=json.dumps(payload))
  536. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201, skip_exists=skip_exists)
  537. def delete_client_role(self, role_name):
  538. """
  539. Create a client role
  540. RoleRepresentation
  541. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_rolerepresentation
  542. :param role_name: roles name (not id!)
  543. """
  544. params_path = {"realm-name": self.realm_name, "id": self.client_id, "role-name": role_name}
  545. data_raw = self.connection.raw_delete(URL_ADMIN_CLIENT_ROLE.format(**params_path))
  546. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  547. def assign_client_role(self, user_id, client_id, roles):
  548. """
  549. Assign a client role to a user
  550. :param client_id: id of client (not client-id)
  551. :param user_id: id of user
  552. :param client_id: id of client containing role,
  553. :param roles: roles list or role (use RoleRepresentation)
  554. :return Keycloak server response
  555. """
  556. payload = roles if isinstance(roles, list) else [roles]
  557. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  558. data_raw = self.connection.raw_post(URL_ADMIN_USER_CLIENT_ROLES.format(**params_path),
  559. data=json.dumps(payload))
  560. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  561. def sync_users(self, storage_id, action):
  562. """
  563. Function to trigger user sync from provider
  564. :param storage_id:
  565. :param action:
  566. :return:
  567. """
  568. data = {'action': action}
  569. params_query = {"action": action}
  570. params_path = {"realm-name": self.realm_name, "id": storage_id}
  571. data_raw = self.connection.raw_post(URL_ADMIN_USER_STORAGE.format(**params_path),
  572. data=json.dumps(data), **params_query)
  573. return raise_error_from_response(data_raw, KeycloakGetError)