OpenStack Dashboard (Horizon)
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.

keystone.py 35KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994
  1. # Copyright 2012 United States Government as represented by the
  2. # Administrator of the National Aeronautics and Space Administration.
  3. # All Rights Reserved.
  4. #
  5. # Copyright 2012 OpenStack Foundation
  6. # Copyright 2012 Nebula, Inc.
  7. #
  8. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  9. # not use this file except in compliance with the License. You may obtain
  10. # a copy of the License at
  11. #
  12. # http://www.apache.org/licenses/LICENSE-2.0
  13. #
  14. # Unless required by applicable law or agreed to in writing, software
  15. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  16. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  17. # License for the specific language governing permissions and limitations
  18. # under the License.
  19. import collections
  20. import logging
  21. from django.conf import settings
  22. from django.utils.translation import ugettext_lazy as _
  23. import six
  24. import six.moves.urllib.parse as urlparse
  25. from keystoneclient import exceptions as keystone_exceptions
  26. from openstack_auth import backend
  27. from openstack_auth import utils as auth_utils
  28. from horizon import exceptions
  29. from horizon import messages
  30. from horizon.utils import functions as utils
  31. from openstack_dashboard.api import base
  32. from openstack_dashboard import policy
  33. LOG = logging.getLogger(__name__)
  34. DEFAULT_ROLE = None
  35. DEFAULT_DOMAIN = getattr(settings, 'OPENSTACK_KEYSTONE_DEFAULT_DOMAIN',
  36. 'default')
  37. # Set up our data structure for managing Identity API versions, and
  38. # add a couple utility methods to it.
  39. class IdentityAPIVersionManager(base.APIVersionManager):
  40. def upgrade_v2_user(self, user):
  41. if getattr(user, "project_id", None) is None:
  42. user.project_id = getattr(user, "default_project_id",
  43. getattr(user, "tenantId", None))
  44. return user
  45. def get_project_manager(self, *args, **kwargs):
  46. if VERSIONS.active < 3:
  47. manager = keystoneclient(*args, **kwargs).tenants
  48. else:
  49. manager = keystoneclient(*args, **kwargs).projects
  50. return manager
  51. VERSIONS = IdentityAPIVersionManager(
  52. "identity", preferred_version=auth_utils.get_keystone_version())
  53. # Import from oldest to newest so that "preferred" takes correct precedence.
  54. try:
  55. from keystoneclient.v2_0 import client as keystone_client_v2
  56. VERSIONS.load_supported_version(2.0, {"client": keystone_client_v2})
  57. except ImportError:
  58. pass
  59. try:
  60. from keystoneclient.v3 import client as keystone_client_v3
  61. VERSIONS.load_supported_version(3, {"client": keystone_client_v3})
  62. except ImportError:
  63. pass
  64. @six.python_2_unicode_compatible
  65. class Service(base.APIDictWrapper):
  66. """Wrapper for a dict based on the service data from keystone."""
  67. _attrs = ['id', 'type', 'name']
  68. def __init__(self, service, region, *args, **kwargs):
  69. super(Service, self).__init__(service, *args, **kwargs)
  70. self.public_url = base.get_url_for_service(service, region,
  71. 'publicURL')
  72. self.url = base.get_url_for_service(service, region, 'internalURL')
  73. if self.url:
  74. self.host = urlparse.urlparse(self.url).hostname
  75. else:
  76. self.host = None
  77. self.disabled = None
  78. self.region = region
  79. def __str__(self):
  80. if(self.type == "identity"):
  81. return _("%(type)s (%(backend)s backend)") \
  82. % {"type": self.type, "backend": keystone_backend_name()}
  83. else:
  84. return self.type
  85. def __repr__(self):
  86. return "<Service: %s>" % six.text_type(self)
  87. def _get_endpoint_url(request, endpoint_type, catalog=None):
  88. if getattr(request.user, "service_catalog", None):
  89. url = base.url_for(request,
  90. service_type='identity',
  91. endpoint_type=endpoint_type)
  92. else:
  93. auth_url = getattr(settings, 'OPENSTACK_KEYSTONE_URL')
  94. url = request.session.get('region_endpoint', auth_url)
  95. # TODO(gabriel): When the Service Catalog no longer contains API versions
  96. # in the endpoints this can be removed.
  97. url = auth_utils.fix_auth_url_version(url)
  98. return url
  99. def keystoneclient(request, admin=False):
  100. """Returns a client connected to the Keystone backend.
  101. Several forms of authentication are supported:
  102. * Username + password -> Unscoped authentication
  103. * Username + password + tenant id -> Scoped authentication
  104. * Unscoped token -> Unscoped authentication
  105. * Unscoped token + tenant id -> Scoped authentication
  106. * Scoped token -> Scoped authentication
  107. Available services and data from the backend will vary depending on
  108. whether the authentication was scoped or unscoped.
  109. Lazy authentication if an ``endpoint`` parameter is provided.
  110. Calls requiring the admin endpoint should have ``admin=True`` passed in
  111. as a keyword argument.
  112. The client is cached so that subsequent API calls during the same
  113. request/response cycle don't have to be re-authenticated.
  114. """
  115. api_version = VERSIONS.get_active_version()
  116. user = request.user
  117. token_id = user.token.id
  118. if is_multi_domain_enabled:
  119. # Cloud Admin, Domain Admin or Mixed Domain Admin
  120. if is_domain_admin(request):
  121. domain_token = request.session.get('domain_token')
  122. if domain_token:
  123. token_id = getattr(domain_token, 'auth_token', None)
  124. if admin:
  125. if not policy.check((("identity", "admin_required"),), request):
  126. raise exceptions.NotAuthorized
  127. endpoint_type = 'adminURL'
  128. else:
  129. endpoint_type = getattr(settings,
  130. 'OPENSTACK_ENDPOINT_TYPE',
  131. 'internalURL')
  132. # Take care of client connection caching/fetching a new client.
  133. # Admin vs. non-admin clients are cached separately for token matching.
  134. cache_attr = "_keystoneclient_admin" if admin \
  135. else backend.KEYSTONE_CLIENT_ATTR
  136. if (hasattr(request, cache_attr) and
  137. (not user.token.id or
  138. getattr(request, cache_attr).auth_token == user.token.id)):
  139. conn = getattr(request, cache_attr)
  140. else:
  141. endpoint = _get_endpoint_url(request, endpoint_type)
  142. insecure = getattr(settings, 'OPENSTACK_SSL_NO_VERIFY', False)
  143. cacert = getattr(settings, 'OPENSTACK_SSL_CACERT', None)
  144. LOG.debug("Creating a new keystoneclient connection to %s." % endpoint)
  145. remote_addr = request.environ.get('REMOTE_ADDR', '')
  146. conn = api_version['client'].Client(token=token_id,
  147. endpoint=endpoint,
  148. original_ip=remote_addr,
  149. insecure=insecure,
  150. cacert=cacert,
  151. auth_url=endpoint,
  152. debug=settings.DEBUG)
  153. setattr(request, cache_attr, conn)
  154. return conn
  155. def domain_create(request, name, description=None, enabled=None):
  156. manager = keystoneclient(request, admin=True).domains
  157. return manager.create(name=name,
  158. description=description,
  159. enabled=enabled)
  160. def domain_get(request, domain_id):
  161. manager = keystoneclient(request, admin=True).domains
  162. return manager.get(domain_id)
  163. def domain_delete(request, domain_id):
  164. manager = keystoneclient(request, admin=True).domains
  165. return manager.delete(domain_id)
  166. def domain_list(request):
  167. manager = keystoneclient(request, admin=True).domains
  168. return manager.list()
  169. def domain_lookup(request):
  170. if policy.check((("identity", "identity:list_domains"),), request) \
  171. and request.session.get('domain_token'):
  172. try:
  173. domains = domain_list(request)
  174. return dict((d.id, d.name) for d in domains)
  175. except Exception:
  176. LOG.warning("Pure project admin doesn't have a domain token")
  177. return None
  178. else:
  179. domain = get_default_domain(request)
  180. return {domain.id: domain.name}
  181. def domain_update(request, domain_id, name=None, description=None,
  182. enabled=None):
  183. manager = keystoneclient(request, admin=True).domains
  184. try:
  185. response = manager.update(domain_id, name=name,
  186. description=description, enabled=enabled)
  187. except Exception:
  188. LOG.exception("Unable to update Domain: %s" % domain_id)
  189. raise
  190. return response
  191. def tenant_create(request, name, description=None, enabled=None,
  192. domain=None, **kwargs):
  193. manager = VERSIONS.get_project_manager(request, admin=True)
  194. try:
  195. if VERSIONS.active < 3:
  196. return manager.create(name, description, enabled, **kwargs)
  197. else:
  198. return manager.create(name, domain,
  199. description=description,
  200. enabled=enabled, **kwargs)
  201. except keystone_exceptions.Conflict:
  202. raise exceptions.Conflict()
  203. def get_default_domain(request, get_name=True):
  204. """Gets the default domain object to use when creating Identity object.
  205. Returns the domain context if is set, otherwise return the domain
  206. of the logon user.
  207. :param get_name: Whether to get the domain name from Keystone if the
  208. context isn't set. Setting this to False prevents an unnecessary call
  209. to Keystone if only the domain ID is needed.
  210. """
  211. domain_id = request.session.get("domain_context", None)
  212. domain_name = request.session.get("domain_context_name", None)
  213. # if running in Keystone V3 or later
  214. if VERSIONS.active >= 3 and domain_id is None:
  215. # if no domain context set, default to user's domain
  216. domain_id = request.user.user_domain_id
  217. domain_name = request.user.user_domain_name
  218. if get_name and not request.user.is_federated:
  219. try:
  220. domain = domain_get(request, domain_id)
  221. domain_name = domain.name
  222. except exceptions.NotAuthorized:
  223. # NOTE (knasim-wrs): Retrieving domain information
  224. # is an admin URL operation. As a pre-check, such
  225. # operations would be Forbidden if the logon user does
  226. # not have an 'admin' role on the current project.
  227. #
  228. # Since this can be a common occurence and can cause
  229. # incessant warning logging in the horizon logs,
  230. # we recognize this condition and return the user's
  231. # domain information instead.
  232. LOG.debug("Cannot retrieve domain information for "
  233. "user (%s) that does not have an admin role "
  234. "on project (%s)" %
  235. (request.user.username, request.user.project_name))
  236. except Exception:
  237. LOG.warning("Unable to retrieve Domain: %s" % domain_id)
  238. domain = base.APIDictWrapper({"id": domain_id,
  239. "name": domain_name})
  240. return domain
  241. def get_effective_domain_id(request):
  242. """Gets the id of the default domain to use when creating Identity objects.
  243. If the requests default domain is the same as DEFAULT_DOMAIN, return None.
  244. """
  245. domain_id = get_default_domain(request).get('id')
  246. return None if domain_id == DEFAULT_DOMAIN else domain_id
  247. def is_cloud_admin(request):
  248. return policy.check((("identity", "cloud_admin"),), request)
  249. def is_domain_admin(request):
  250. return policy.check(
  251. (("identity", "admin_and_matching_domain_id"),), request)
  252. # TODO(gabriel): Is there ever a valid case for admin to be false here?
  253. # A quick search through the codebase reveals that it's always called with
  254. # admin=true so I suspect we could eliminate it entirely as with the other
  255. # tenant commands.
  256. def tenant_get(request, project, admin=True):
  257. manager = VERSIONS.get_project_manager(request, admin=admin)
  258. return manager.get(project)
  259. def tenant_delete(request, project):
  260. manager = VERSIONS.get_project_manager(request, admin=True)
  261. return manager.delete(project)
  262. def tenant_list(request, paginate=False, marker=None, domain=None, user=None,
  263. admin=True, filters=None):
  264. manager = VERSIONS.get_project_manager(request, admin=admin)
  265. page_size = utils.get_page_size(request)
  266. tenants = []
  267. limit = None
  268. if paginate:
  269. limit = page_size + 1
  270. has_more_data = False
  271. # if requesting the projects for the current user,
  272. # return the list from the cache
  273. if user == request.user.id:
  274. tenants = request.user.authorized_tenants
  275. elif VERSIONS.active < 3:
  276. tenants = manager.list(limit, marker)
  277. if paginate and len(tenants) > page_size:
  278. tenants.pop(-1)
  279. has_more_data = True
  280. # V3 API
  281. else:
  282. domain_id = get_effective_domain_id(request)
  283. kwargs = {
  284. "domain": domain_id,
  285. "user": user
  286. }
  287. if filters is not None:
  288. kwargs.update(filters)
  289. if 'id' in kwargs:
  290. try:
  291. tenants = [tenant_get(request, kwargs['id'])]
  292. except keystone_exceptions.NotFound:
  293. tenants = []
  294. except Exception:
  295. exceptions.handle(request)
  296. else:
  297. tenants = manager.list(**kwargs)
  298. return tenants, has_more_data
  299. def tenant_update(request, project, name=None, description=None,
  300. enabled=None, domain=None, **kwargs):
  301. manager = VERSIONS.get_project_manager(request, admin=True)
  302. try:
  303. if VERSIONS.active < 3:
  304. return manager.update(project, name, description, enabled,
  305. **kwargs)
  306. else:
  307. return manager.update(project, name=name, description=description,
  308. enabled=enabled, domain=domain, **kwargs)
  309. except keystone_exceptions.Conflict:
  310. raise exceptions.Conflict()
  311. def user_list(request, project=None, domain=None, group=None, filters=None):
  312. users = []
  313. if VERSIONS.active < 3:
  314. kwargs = {"tenant_id": project}
  315. else:
  316. kwargs = {
  317. "project": project,
  318. "domain": domain,
  319. "group": group
  320. }
  321. if filters is not None:
  322. kwargs.update(filters)
  323. if 'id' in kwargs:
  324. try:
  325. users = [user_get(request, kwargs['id'])]
  326. except keystone_exceptions.NotFound:
  327. raise exceptions.NotFound()
  328. else:
  329. users = keystoneclient(request, admin=True).users.list(**kwargs)
  330. return [VERSIONS.upgrade_v2_user(user) for user in users]
  331. def user_create(request, name=None, email=None, password=None, project=None,
  332. enabled=None, domain=None, description=None, **data):
  333. manager = keystoneclient(request, admin=True).users
  334. try:
  335. if VERSIONS.active < 3:
  336. user = manager.create(name, password, email, project, enabled)
  337. return VERSIONS.upgrade_v2_user(user)
  338. else:
  339. return manager.create(name, password=password, email=email,
  340. default_project=project, enabled=enabled,
  341. domain=domain, description=description,
  342. **data)
  343. except keystone_exceptions.Conflict:
  344. raise exceptions.Conflict()
  345. def user_delete(request, user_id):
  346. return keystoneclient(request, admin=True).users.delete(user_id)
  347. def user_get(request, user_id, admin=True):
  348. user = keystoneclient(request, admin=admin).users.get(user_id)
  349. return VERSIONS.upgrade_v2_user(user)
  350. def user_update(request, user, **data):
  351. manager = keystoneclient(request, admin=True).users
  352. error = None
  353. if not keystone_can_edit_user():
  354. raise keystone_exceptions.ClientException(
  355. 405, _("Identity service does not allow editing user data."))
  356. # The v2 API updates user model and default project separately
  357. if VERSIONS.active < 3:
  358. # Update user details
  359. try:
  360. user = manager.update(user, **data)
  361. except keystone_exceptions.Conflict:
  362. raise exceptions.Conflict()
  363. except Exception:
  364. error = exceptions.handle(request, ignore=True)
  365. if "project" in data:
  366. project = data.pop('project')
  367. # Update default tenant
  368. try:
  369. user_update_tenant(request, user, project)
  370. user.tenantId = project
  371. except Exception:
  372. error = exceptions.handle(request, ignore=True)
  373. # Check for existing roles
  374. # Show a warning if no role exists for the project
  375. user_roles = roles_for_user(request, user, project)
  376. if not user_roles:
  377. messages.warning(request,
  378. _('User %s has no role defined for '
  379. 'that project.')
  380. % data.get('name', None))
  381. if error is not None:
  382. raise error
  383. # v3 API is so much simpler...
  384. else:
  385. try:
  386. user = manager.update(user, **data)
  387. except keystone_exceptions.Conflict:
  388. raise exceptions.Conflict()
  389. def user_update_enabled(request, user, enabled):
  390. manager = keystoneclient(request, admin=True).users
  391. if VERSIONS.active < 3:
  392. return manager.update_enabled(user, enabled)
  393. else:
  394. return manager.update(user, enabled=enabled)
  395. def user_update_password(request, user, password, admin=True):
  396. if not keystone_can_edit_user():
  397. raise keystone_exceptions.ClientException(
  398. 405, _("Identity service does not allow editing user password."))
  399. manager = keystoneclient(request, admin=admin).users
  400. if VERSIONS.active < 3:
  401. return manager.update_password(user, password)
  402. else:
  403. return manager.update(user, password=password)
  404. def user_verify_admin_password(request, admin_password):
  405. # attempt to create a new client instance with admin password to
  406. # verify if it's correct.
  407. client = keystone_client_v2 if VERSIONS.active < 3 else keystone_client_v3
  408. try:
  409. endpoint = _get_endpoint_url(request, 'internalURL')
  410. insecure = getattr(settings, 'OPENSTACK_SSL_NO_VERIFY', False)
  411. cacert = getattr(settings, 'OPENSTACK_SSL_CACERT', None)
  412. client.Client(
  413. username=request.user.username,
  414. password=admin_password,
  415. insecure=insecure,
  416. cacert=cacert,
  417. auth_url=endpoint
  418. )
  419. return True
  420. except Exception:
  421. exceptions.handle(request, ignore=True)
  422. return False
  423. def user_update_own_password(request, origpassword, password):
  424. client = keystoneclient(request, admin=False)
  425. client.user_id = request.user.id
  426. if VERSIONS.active < 3:
  427. return client.users.update_own_password(origpassword, password)
  428. else:
  429. return client.users.update_password(origpassword, password)
  430. def user_update_tenant(request, user, project, admin=True):
  431. manager = keystoneclient(request, admin=admin).users
  432. if VERSIONS.active < 3:
  433. return manager.update_tenant(user, project)
  434. else:
  435. return manager.update(user, project=project)
  436. def group_create(request, domain_id, name, description=None):
  437. manager = keystoneclient(request, admin=True).groups
  438. return manager.create(domain=domain_id,
  439. name=name,
  440. description=description)
  441. def group_get(request, group_id, admin=True):
  442. manager = keystoneclient(request, admin=admin).groups
  443. return manager.get(group_id)
  444. def group_delete(request, group_id):
  445. manager = keystoneclient(request, admin=True).groups
  446. return manager.delete(group_id)
  447. def group_list(request, domain=None, project=None, user=None, filters=None):
  448. manager = keystoneclient(request, admin=True).groups
  449. groups = []
  450. kwargs = {
  451. "domain": domain,
  452. "user": user,
  453. "name": None
  454. }
  455. if filters is not None:
  456. kwargs.update(filters)
  457. if 'id' in kwargs:
  458. try:
  459. groups = [manager.get(kwargs['id'])]
  460. except keystone_exceptions.NotFound:
  461. raise exceptions.NotFound()
  462. else:
  463. groups = manager.list(**kwargs)
  464. if project:
  465. project_groups = []
  466. for group in groups:
  467. roles = roles_for_group(request, group=group.id, project=project)
  468. if roles and len(roles) > 0:
  469. project_groups.append(group)
  470. groups = project_groups
  471. return groups
  472. def group_update(request, group_id, name=None, description=None):
  473. manager = keystoneclient(request, admin=True).groups
  474. return manager.update(group=group_id,
  475. name=name,
  476. description=description)
  477. def add_group_user(request, group_id, user_id):
  478. manager = keystoneclient(request, admin=True).users
  479. return manager.add_to_group(group=group_id, user=user_id)
  480. def remove_group_user(request, group_id, user_id):
  481. manager = keystoneclient(request, admin=True).users
  482. return manager.remove_from_group(group=group_id, user=user_id)
  483. def get_project_groups_roles(request, project):
  484. """Gets the groups roles in a given project.
  485. :param request: the request entity containing the login user information
  486. :param project: the project to filter the groups roles. It accepts both
  487. project object resource or project ID
  488. :returns group_roles: a dictionary mapping the groups and their roles in
  489. given project
  490. """
  491. groups_roles = collections.defaultdict(list)
  492. project_role_assignments = role_assignments_list(request,
  493. project=project)
  494. for role_assignment in project_role_assignments:
  495. if not hasattr(role_assignment, 'group'):
  496. continue
  497. group_id = role_assignment.group['id']
  498. role_id = role_assignment.role['id']
  499. # filter by project_id
  500. if ('project' in role_assignment.scope and
  501. role_assignment.scope['project']['id'] == project):
  502. groups_roles[group_id].append(role_id)
  503. return groups_roles
  504. def role_assignments_list(request, project=None, user=None, role=None,
  505. group=None, domain=None, effective=False,
  506. include_subtree=True):
  507. if VERSIONS.active < 3:
  508. raise exceptions.NotAvailable
  509. if include_subtree:
  510. domain = None
  511. manager = keystoneclient(request, admin=True).role_assignments
  512. return manager.list(project=project, user=user, role=role, group=group,
  513. domain=domain, effective=effective,
  514. include_subtree=include_subtree)
  515. def role_create(request, name):
  516. manager = keystoneclient(request, admin=True).roles
  517. return manager.create(name)
  518. def role_get(request, role_id):
  519. manager = keystoneclient(request, admin=True).roles
  520. return manager.get(role_id)
  521. def role_update(request, role_id, name=None):
  522. manager = keystoneclient(request, admin=True).roles
  523. return manager.update(role_id, name)
  524. def role_delete(request, role_id):
  525. manager = keystoneclient(request, admin=True).roles
  526. return manager.delete(role_id)
  527. def role_list(request, filters=None):
  528. """Returns a global list of available roles."""
  529. manager = keystoneclient(request, admin=True).roles
  530. roles = []
  531. kwargs = {}
  532. if filters is not None:
  533. kwargs.update(filters)
  534. if 'id' in kwargs:
  535. try:
  536. roles = [manager.get(kwargs['id'])]
  537. except keystone_exceptions.NotFound:
  538. roles = []
  539. except Exception:
  540. exceptions.handle(request)
  541. else:
  542. roles = manager.list(**kwargs)
  543. return roles
  544. def roles_for_user(request, user, project=None, domain=None):
  545. """Returns a list of user roles scoped to a project or domain."""
  546. manager = keystoneclient(request, admin=True).roles
  547. if VERSIONS.active < 3:
  548. return manager.roles_for_user(user, project)
  549. else:
  550. return manager.list(user=user, domain=domain, project=project)
  551. def get_domain_users_roles(request, domain):
  552. users_roles = collections.defaultdict(list)
  553. domain_role_assignments = role_assignments_list(request,
  554. domain=domain,
  555. include_subtree=False)
  556. for role_assignment in domain_role_assignments:
  557. if not hasattr(role_assignment, 'user'):
  558. continue
  559. user_id = role_assignment.user['id']
  560. role_id = role_assignment.role['id']
  561. # filter by domain_id
  562. if ('domain' in role_assignment.scope and
  563. role_assignment.scope['domain']['id'] == domain):
  564. users_roles[user_id].append(role_id)
  565. return users_roles
  566. def add_domain_user_role(request, user, role, domain):
  567. """Adds a role for a user on a domain."""
  568. manager = keystoneclient(request, admin=True).roles
  569. return manager.grant(role, user=user, domain=domain)
  570. def remove_domain_user_role(request, user, role, domain=None):
  571. """Removes a given single role for a user from a domain."""
  572. manager = keystoneclient(request, admin=True).roles
  573. return manager.revoke(role, user=user, domain=domain)
  574. def get_project_users_roles(request, project):
  575. users_roles = collections.defaultdict(list)
  576. if VERSIONS.active < 3:
  577. project_users = user_list(request, project=project)
  578. for user in project_users:
  579. roles = roles_for_user(request, user.id, project)
  580. roles_ids = [role.id for role in roles]
  581. users_roles[user.id].extend(roles_ids)
  582. else:
  583. project_role_assignments = role_assignments_list(request,
  584. project=project)
  585. for role_assignment in project_role_assignments:
  586. if not hasattr(role_assignment, 'user'):
  587. continue
  588. user_id = role_assignment.user['id']
  589. role_id = role_assignment.role['id']
  590. # filter by project_id
  591. if ('project' in role_assignment.scope and
  592. role_assignment.scope['project']['id'] == project):
  593. users_roles[user_id].append(role_id)
  594. return users_roles
  595. def add_tenant_user_role(request, project=None, user=None, role=None,
  596. group=None, domain=None):
  597. """Adds a role for a user on a tenant."""
  598. manager = keystoneclient(request, admin=True).roles
  599. if VERSIONS.active < 3:
  600. return manager.add_user_role(user, role, project)
  601. else:
  602. return manager.grant(role, user=user, project=project,
  603. group=group, domain=domain)
  604. def remove_tenant_user_role(request, project=None, user=None, role=None,
  605. group=None, domain=None):
  606. """Removes a given single role for a user from a tenant."""
  607. manager = keystoneclient(request, admin=True).roles
  608. if VERSIONS.active < 3:
  609. return manager.remove_user_role(user, role, project)
  610. else:
  611. return manager.revoke(role, user=user, project=project,
  612. group=group, domain=domain)
  613. def remove_tenant_user(request, project=None, user=None, domain=None):
  614. """Removes all roles from a user on a tenant, removing them from it."""
  615. client = keystoneclient(request, admin=True)
  616. roles = client.roles.roles_for_user(user, project)
  617. for role in roles:
  618. remove_tenant_user_role(request, user=user, role=role.id,
  619. project=project, domain=domain)
  620. def roles_for_group(request, group, domain=None, project=None):
  621. manager = keystoneclient(request, admin=True).roles
  622. return manager.list(group=group, domain=domain, project=project)
  623. def add_group_role(request, role, group, domain=None, project=None):
  624. """Adds a role for a group on a domain or project."""
  625. manager = keystoneclient(request, admin=True).roles
  626. return manager.grant(role=role, group=group, domain=domain,
  627. project=project)
  628. def remove_group_role(request, role, group, domain=None, project=None):
  629. """Removes a given single role for a group from a domain or project."""
  630. manager = keystoneclient(request, admin=True).roles
  631. return manager.revoke(role=role, group=group, project=project,
  632. domain=domain)
  633. def remove_group_roles(request, group, domain=None, project=None):
  634. """Removes all roles from a group on a domain or project."""
  635. client = keystoneclient(request, admin=True)
  636. roles = client.roles.list(group=group, domain=domain, project=project)
  637. for role in roles:
  638. remove_group_role(request, role=role.id, group=group,
  639. domain=domain, project=project)
  640. def get_default_role(request):
  641. """Gets the default role object from Keystone and saves it as a global.
  642. Since this is configured in settings and should not change from request
  643. to request. Supports lookup by name or id.
  644. """
  645. global DEFAULT_ROLE
  646. default = getattr(settings, "OPENSTACK_KEYSTONE_DEFAULT_ROLE", None)
  647. if default and DEFAULT_ROLE is None:
  648. try:
  649. roles = keystoneclient(request, admin=True).roles.list()
  650. except Exception:
  651. roles = []
  652. exceptions.handle(request)
  653. for role in roles:
  654. if role.id == default or role.name == default:
  655. DEFAULT_ROLE = role
  656. break
  657. return DEFAULT_ROLE
  658. def ec2_manager(request):
  659. client = keystoneclient(request)
  660. if hasattr(client, 'ec2'):
  661. return client.ec2
  662. # Keystoneclient 4.0 was released without the ec2 creds manager.
  663. from keystoneclient.v2_0 import ec2
  664. return ec2.CredentialsManager(client)
  665. def list_ec2_credentials(request, user_id):
  666. return ec2_manager(request).list(user_id)
  667. def create_ec2_credentials(request, user_id, tenant_id):
  668. return ec2_manager(request).create(user_id, tenant_id)
  669. def get_user_ec2_credentials(request, user_id, access_token):
  670. return ec2_manager(request).get(user_id, access_token)
  671. def delete_user_ec2_credentials(request, user_id, access_token):
  672. return ec2_manager(request).delete(user_id, access_token)
  673. def keystone_can_edit_domain():
  674. backend_settings = getattr(settings, "OPENSTACK_KEYSTONE_BACKEND", {})
  675. can_edit_domain = backend_settings.get('can_edit_domain', True)
  676. multi_domain_support = getattr(settings,
  677. 'OPENSTACK_KEYSTONE_MULTIDOMAIN_SUPPORT',
  678. False)
  679. return can_edit_domain and multi_domain_support
  680. def keystone_can_edit_user():
  681. backend_settings = getattr(settings, "OPENSTACK_KEYSTONE_BACKEND", {})
  682. return backend_settings.get('can_edit_user', True)
  683. def keystone_can_edit_project():
  684. backend_settings = getattr(settings, "OPENSTACK_KEYSTONE_BACKEND", {})
  685. return backend_settings.get('can_edit_project', True)
  686. def keystone_can_edit_group():
  687. backend_settings = getattr(settings, "OPENSTACK_KEYSTONE_BACKEND", {})
  688. return backend_settings.get('can_edit_group', True)
  689. def keystone_can_edit_role():
  690. backend_settings = getattr(settings, "OPENSTACK_KEYSTONE_BACKEND", {})
  691. return backend_settings.get('can_edit_role', True)
  692. def keystone_backend_name():
  693. if hasattr(settings, "OPENSTACK_KEYSTONE_BACKEND"):
  694. return settings.OPENSTACK_KEYSTONE_BACKEND['name']
  695. else:
  696. return 'unknown'
  697. def get_version():
  698. return VERSIONS.active
  699. def is_multi_domain_enabled():
  700. return (VERSIONS.active >= 3 and
  701. getattr(settings, 'OPENSTACK_KEYSTONE_MULTIDOMAIN_SUPPORT', False))
  702. def is_federation_management_enabled():
  703. return getattr(settings, 'OPENSTACK_KEYSTONE_FEDERATION_MANAGEMENT', False)
  704. def identity_provider_create(request, idp_id, description=None,
  705. enabled=False, remote_ids=None):
  706. manager = keystoneclient(request, admin=True).federation.identity_providers
  707. try:
  708. return manager.create(id=idp_id,
  709. description=description,
  710. enabled=enabled,
  711. remote_ids=remote_ids)
  712. except keystone_exceptions.Conflict:
  713. raise exceptions.Conflict()
  714. def identity_provider_get(request, idp_id):
  715. manager = keystoneclient(request, admin=True).federation.identity_providers
  716. return manager.get(idp_id)
  717. def identity_provider_update(request, idp_id, description=None,
  718. enabled=False, remote_ids=None):
  719. manager = keystoneclient(request, admin=True).federation.identity_providers
  720. try:
  721. return manager.update(idp_id,
  722. description=description,
  723. enabled=enabled,
  724. remote_ids=remote_ids)
  725. except keystone_exceptions.Conflict:
  726. raise exceptions.Conflict()
  727. def identity_provider_delete(request, idp_id):
  728. manager = keystoneclient(request, admin=True).federation.identity_providers
  729. return manager.delete(idp_id)
  730. def identity_provider_list(request):
  731. manager = keystoneclient(request, admin=True).federation.identity_providers
  732. return manager.list()
  733. def mapping_create(request, mapping_id, rules):
  734. manager = keystoneclient(request, admin=True).federation.mappings
  735. try:
  736. return manager.create(mapping_id=mapping_id, rules=rules)
  737. except keystone_exceptions.Conflict:
  738. raise exceptions.Conflict()
  739. def mapping_get(request, mapping_id):
  740. manager = keystoneclient(request, admin=True).federation.mappings
  741. return manager.get(mapping_id)
  742. def mapping_update(request, mapping_id, rules):
  743. manager = keystoneclient(request, admin=True).federation.mappings
  744. return manager.update(mapping_id, rules=rules)
  745. def mapping_delete(request, mapping_id):
  746. manager = keystoneclient(request, admin=True).federation.mappings
  747. return manager.delete(mapping_id)
  748. def mapping_list(request):
  749. manager = keystoneclient(request, admin=True).federation.mappings
  750. return manager.list()
  751. def protocol_create(request, protocol_id, identity_provider, mapping):
  752. manager = keystoneclient(request).federation.protocols
  753. try:
  754. return manager.create(protocol_id, identity_provider, mapping)
  755. except keystone_exceptions.Conflict:
  756. raise exceptions.Conflict()
  757. def protocol_get(request, identity_provider, protocol):
  758. manager = keystoneclient(request).federation.protocols
  759. return manager.get(identity_provider, protocol)
  760. def protocol_update(request, identity_provider, protocol, mapping):
  761. manager = keystoneclient(request).federation.protocols
  762. return manager.update(identity_provider, protocol, mapping)
  763. def protocol_delete(request, identity_provider, protocol):
  764. manager = keystoneclient(request).federation.protocols
  765. return manager.delete(identity_provider, protocol)
  766. def protocol_list(request, identity_provider):
  767. manager = keystoneclient(request).federation.protocols
  768. return manager.list(identity_provider)