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.

645 lines
24 KiB

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