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.

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