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.

705 lines
26 KiB

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
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,\
  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_by_path(self, path, search_in_subgroups=False):
  301. """
  302. Get group id based on name or path.
  303. A straight name or path match with a top-level group will return first.
  304. Subgroups are traversed, the first to match path (or name with path) is returned.
  305. GroupRepresentation
  306. http://www.keycloak.org/docs-api/3.2/rest-api/#_grouprepresentation
  307. :param path: group path
  308. :param search_in_subgroups: True if want search in the subgroups
  309. :return: Keycloak server response (GroupRepresentation)
  310. """
  311. groups = self.get_groups()
  312. # TODO: Review this code is necessary
  313. for group in groups:
  314. if group['path'] == path:
  315. return group
  316. elif search_in_subgroups and group["subGroups"]:
  317. res = self.get_subgroups(group, path)
  318. if res != None:
  319. return res
  320. return None
  321. def create_group(self, payload, parent=None, skip_exists=False):
  322. """
  323. Creates a group in the Realm
  324. :param payload: GroupRepresentation
  325. :param parent: parent group's id. Required to create a sub-group.
  326. GroupRepresentation
  327. http://www.keycloak.org/docs-api/3.2/rest-api/#_grouprepresentation
  328. :return: Http response
  329. """
  330. name = payload['name']
  331. path = payload['path']
  332. exists = None
  333. if name is None and path is not None:
  334. path="/" + name
  335. elif path is not None:
  336. exists = self.get_group_by_path(path=path, search_in_subgroups=True)
  337. if exists is not None:
  338. return str(exists)
  339. if parent is None:
  340. params_path = {"realm-name": self.realm_name}
  341. data_raw = self.connection.raw_post(URL_ADMIN_GROUPS.format(**params_path),
  342. data=json.dumps(payload))
  343. else:
  344. params_path = {"realm-name": self.realm_name, "id": parent,}
  345. data_raw = self.connection.raw_post(URL_ADMIN_GROUP_CHILD.format(**params_path),
  346. data=json.dumps(payload))
  347. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201, skip_exists=skip_exists)
  348. def group_set_permissions(self, group_id, enabled=True):
  349. """
  350. Enable/Disable permissions for a group. Cannot delete group if disabled
  351. :param group_id: id of group
  352. :param enabled: boolean
  353. :return: Keycloak server response
  354. """
  355. params_path = {"realm-name": self.realm_name, "id": group_id}
  356. data_raw = self.connection.raw_put(URL_ADMIN_GROUP_PERMISSIONS.format(**params_path),
  357. data=json.dumps({"enabled": enabled}))
  358. return raise_error_from_response(data_raw, KeycloakGetError)
  359. def group_user_add(self, user_id, group_id):
  360. """
  361. Add user to group (user_id and group_id)
  362. :param group_id: id of group
  363. :param user_id: id of user
  364. :param group_id: id of group to add to
  365. :return: Keycloak server response
  366. """
  367. params_path = {"realm-name": self.realm_name, "id": user_id, "group-id": group_id}
  368. data_raw = self.connection.raw_put(URL_ADMIN_USER_GROUP.format(**params_path), data=None)
  369. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  370. def group_user_remove(self, user_id, group_id):
  371. """
  372. Remove user from 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_delete(URL_ADMIN_USER_GROUP.format(**params_path))
  380. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  381. def delete_group(self, group_id):
  382. """
  383. Deletes a group in the Realm
  384. :param group_id: id of group to delete
  385. :return: Keycloak server response
  386. """
  387. params_path = {"realm-name": self.realm_name, "id": group_id}
  388. data_raw = self.connection.raw_delete(URL_ADMIN_GROUP.format(**params_path))
  389. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  390. def get_clients(self):
  391. """
  392. Get clients belonging to the realm Returns a list of clients belonging to the realm
  393. ClientRepresentation
  394. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_clientrepresentation
  395. :return: Keycloak server response (ClientRepresentation)
  396. """
  397. params_path = {"realm-name": self.realm_name}
  398. data_raw = self.connection.raw_get(URL_ADMIN_CLIENTS.format(**params_path))
  399. return raise_error_from_response(data_raw, KeycloakGetError)
  400. def get_client(self, client_id):
  401. """
  402. Get representation of the client
  403. ClientRepresentation
  404. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_clientrepresentation
  405. :param client_id: id of client (not client-id)
  406. :return: Keycloak server response (ClientRepresentation)
  407. """
  408. params_path = {"realm-name": self.realm_name, "id": client_id}
  409. data_raw = self.connection.raw_get(URL_ADMIN_CLIENT.format(**params_path))
  410. return raise_error_from_response(data_raw, KeycloakGetError)
  411. def get_client_id(self, client_name):
  412. """
  413. Get internal keycloak client id from client-id.
  414. This is required for further actions against this client.
  415. :param client_name: name in ClientRepresentation
  416. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_clientrepresentation
  417. :return: client_id (uuid as string)
  418. """
  419. clients = self.get_clients()
  420. for client in clients:
  421. if client_name == client['name']:
  422. return client["id"]
  423. return None
  424. def create_client(self, payload, skip_exists=False):
  425. """
  426. Create a client
  427. ClientRepresentation: http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_clientrepresentation
  428. :param payload: ClientRepresentation
  429. :return: Keycloak server response (UserRepresentation)
  430. """
  431. params_path = {"realm-name": self.realm_name}
  432. data_raw = self.connection.raw_post(URL_ADMIN_CLIENTS.format(**params_path),
  433. data=json.dumps(payload))
  434. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201, skip_exists=skip_exists)
  435. def delete_client(self, client_id):
  436. """
  437. Get representation of the client
  438. ClientRepresentation
  439. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_clientrepresentation
  440. :param client_id: keycloak client id (not oauth client-id)
  441. :return: Keycloak server response (ClientRepresentation)
  442. """
  443. params_path = {"realm-name": self.realm_name, "id": client_id}
  444. data_raw = self.connection.raw_delete(URL_ADMIN_CLIENT.format(**params_path))
  445. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  446. def get_realm_roles(self):
  447. """
  448. Get all roles for the realm or client
  449. RoleRepresentation
  450. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_rolerepresentation
  451. :return: Keycloak server response (RoleRepresentation)
  452. """
  453. params_path = {"realm-name": self.realm_name}
  454. data_raw = self.connection.raw_get(URL_ADMIN_REALM_ROLES.format(**params_path))
  455. return raise_error_from_response(data_raw, KeycloakGetError)
  456. def get_client_roles(self, client_id):
  457. """
  458. Get all roles for the client
  459. :param client_id: id of client (not client-id)
  460. RoleRepresentation
  461. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_rolerepresentation
  462. :return: Keycloak server response (RoleRepresentation)
  463. """
  464. params_path = {"realm-name": self.realm_name, "id": client_id}
  465. data_raw = self.connection.raw_get(URL_ADMIN_CLIENT_ROLES.format(**params_path))
  466. return raise_error_from_response(data_raw, KeycloakGetError)
  467. def get_client_role(self, client_id, role_name):
  468. """
  469. Get client role id by name
  470. This is required for further actions with this role.
  471. :param client_id: id of client (not client-id)
  472. :param role_name: roles name (not id!)
  473. RoleRepresentation
  474. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_rolerepresentation
  475. :return: role_id
  476. """
  477. params_path = {"realm-name": self.realm_name, "id": client_id, "role-name": role_name}
  478. data_raw = self.connection.raw_get(URL_ADMIN_CLIENT_ROLE.format(**params_path))
  479. return raise_error_from_response(data_raw, KeycloakGetError)
  480. def get_client_role_id(self, client_id, role_name):
  481. """
  482. Warning: Deprecated
  483. Get client role id by name
  484. This is required for further actions with this role.
  485. :param client_id: id of client (not client-id)
  486. :param role_name: roles name (not id!)
  487. RoleRepresentation
  488. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_rolerepresentation
  489. :return: role_id
  490. """
  491. role = self.get_client_role(client_id, role_name)
  492. return role.get("id")
  493. def create_client_role(self, payload, skip_exists=False):
  494. """
  495. Create a client role
  496. RoleRepresentation
  497. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_rolerepresentation
  498. :param payload: id of client (not client-id), role_name: name of role
  499. :return: Keycloak server response (RoleRepresentation)
  500. """
  501. params_path = {"realm-name": self.realm_name, "id": self.client_id}
  502. data_raw = self.connection.raw_post(URL_ADMIN_CLIENT_ROLES.format(**params_path),
  503. data=json.dumps(payload))
  504. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=201, skip_exists=skip_exists)
  505. def delete_client_role(self, role_name):
  506. """
  507. Create a client role
  508. RoleRepresentation
  509. http://www.keycloak.org/docs-api/3.3/rest-api/index.html#_rolerepresentation
  510. :param role_name: roles name (not id!)
  511. """
  512. params_path = {"realm-name": self.realm_name, "id": self.client_id, "role-name": role_name}
  513. data_raw = self.connection.raw_delete(URL_ADMIN_CLIENT_ROLE.format(**params_path))
  514. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  515. def assign_client_role(self, user_id, client_id, roles):
  516. """
  517. Assign a client role to a user
  518. :param client_id: id of client (not client-id)
  519. :param user_id: id of user
  520. :param client_id: id of client containing role,
  521. :param roles: roles list or role (use RoleRepresentation)
  522. :return Keycloak server response
  523. """
  524. payload = roles if isinstance(roles, list) else [roles]
  525. params_path = {"realm-name": self.realm_name, "id": user_id, "client-id": client_id}
  526. data_raw = self.connection.raw_post(URL_ADMIN_USER_CLIENT_ROLES.format(**params_path),
  527. data=json.dumps(payload))
  528. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  529. def sync_users(self, storage_id, action):
  530. """
  531. Function to trigger user sync from provider
  532. :param storage_id:
  533. :param action:
  534. :return:
  535. """
  536. data = {'action': action}
  537. params_query = {"action": action}
  538. params_path = {"realm-name": self.realm_name, "id": storage_id}
  539. data_raw = self.connection.raw_post(URL_ADMIN_USER_STORAGE.format(**params_path),
  540. data=json.dumps(data), **params_query)
  541. return raise_error_from_response(data_raw, KeycloakGetError)