Debian Codegraph @

adjutantclient/v1/roles.py

raw
1 # Copyright (C) 2016 Catalyst IT Ltd
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License"); you may
4 # not use this file except in compliance with the License. You may obtain
5 # a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 # License for the specific language governing permissions and limitations
13 # under the License.
14
15 from urllib import parse
16
17 from adjutantclient.common import base
18 from adjutantclient import exc
19
20
21 class Role(base.Resource):
22 pass
23
24
25 class ManagableRole(base.Resource):
26 pass
27
28
29 class ManagedRoleManager(base.ManagerWithFind):
30 resource_class = ManagableRole
31
32 def list(self, **kwargs):
33 """Get a list of roles that can be managed.
34
35 :rtype: list of :class:`Role`
36 """
37 params = {}
38 url = '/openstack/roles?%(params)s' % {
39 'params': parse.urlencode(params, True)
40 }
41 return self._list(url, 'roles')
42
43 def get(self, role_id):
44 """Get a role by role_id"""
45 # Right now the only way is to list them all, then iterate.
46 # Perhaps a filter or new endpoint would be useful here.
47 roles = self.list()
48 for role in roles:
49 if role.id == role_id:
50 return role
51 raise exc.HTTPNotFound()
52
53
54 class UserRoleManager(base.BaseManager):
55 resource_class = Role
56
57 def list(self, **kwargs):
58 """List roles for a given user"""
59 # TODO(adriant): Look up user by name/id
60 url = '/openstack/users/%s/roles' % kwargs['user']
61 return self._list(url, 'roles')
62
63 def add(self, user, role=None, roles=None):
64 """Add a role to a user"""
65 # TODO(adriant): resolve the roles and users into id's
66 # user_id = base.getid(user)
67 user_id = user
68 # role_id = role
69 if role:
70 params = {
71 'roles': [role]
72 }
73 elif roles:
74 params = {
75 'roles': roles
76 }
77
78 route = '/openstack/users/%s/roles'
79 url = route % (user_id)
80 try:
81 self._put(url, json=params, response_key=None)
82 except exc.HTTPBadRequest as e:
83 print(e.message)
84 return False
85
86 return True
87
88 def remove(self, user_id, role=None, roles=None):
89 """Remove a role or roles from a user"""
90
91 if role:
92 params = {
93 'roles': [role]
94 }
95 elif roles:
96 params = {
97 'roles': roles
98 }
99
100 route = '/openstack/users/%s/roles'
101 url = route % (user_id)
102 try:
103 self._delete(url, json=params)
104 except exc.HTTPBadRequest as e:
105 print(e.message)
106 return False
107
108 return True