blob: b77bc9188a60ed4e68d8d0f2ba53c283451ea163 [file] [log] [blame]
tiernob24258a2018-10-04 18:39:49 +02001# -*- coding: utf-8 -*-
2
tiernod125caf2018-11-22 16:05:54 +00003# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain 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,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
12# implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
tiernob24258a2018-10-04 18:39:49 +020016# import logging
17from uuid import uuid4
18from hashlib import sha256
19from http import HTTPStatus
Eduardo Sousa5c01e192019-05-08 02:35:47 +010020from time import time
tiernob24258a2018-10-04 18:39:49 +020021from validation import user_new_schema, user_edit_schema, project_new_schema, project_edit_schema
22from validation import vim_account_new_schema, vim_account_edit_schema, sdn_new_schema, sdn_edit_schema
Eduardo Sousa5c01e192019-05-08 02:35:47 +010023from validation import wim_account_new_schema, wim_account_edit_schema, roles_new_schema, roles_edit_schema
24from validation import validate_input
25from validation import ValidationError
delacruzramoc061f562019-04-05 11:00:02 +020026from validation import is_valid_uuid # To check that User/Project Names don't look like UUIDs
tiernob24258a2018-10-04 18:39:49 +020027from base_topic import BaseTopic, EngineException
28
29__author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
30
31
32class UserTopic(BaseTopic):
33 topic = "users"
34 topic_msg = "users"
35 schema_new = user_new_schema
36 schema_edit = user_edit_schema
tierno65ca36d2019-02-12 19:27:52 +010037 multiproject = False
tiernob24258a2018-10-04 18:39:49 +020038
39 def __init__(self, db, fs, msg):
40 BaseTopic.__init__(self, db, fs, msg)
41
42 @staticmethod
tierno65ca36d2019-02-12 19:27:52 +010043 def _get_project_filter(session):
tiernob24258a2018-10-04 18:39:49 +020044 """
45 Generates a filter dictionary for querying database users.
46 Current policy is admin can show all, non admin, only its own user.
tierno65ca36d2019-02-12 19:27:52 +010047 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +020048 :return:
49 """
50 if session["admin"]: # allows all
51 return {}
52 else:
53 return {"username": session["username"]}
54
tierno65ca36d2019-02-12 19:27:52 +010055 def check_conflict_on_new(self, session, indata):
tiernob24258a2018-10-04 18:39:49 +020056 # check username not exists
57 if self.db.get_one(self.topic, {"username": indata.get("username")}, fail_on_empty=False, fail_on_more=False):
58 raise EngineException("username '{}' exists".format(indata["username"]), HTTPStatus.CONFLICT)
59 # check projects
tierno65ca36d2019-02-12 19:27:52 +010060 if not session["force"]:
61 for p in indata.get("projects"):
delacruzramoc061f562019-04-05 11:00:02 +020062 # To allow project addressing by Name as well as ID
63 if not self.db.get_one("projects", {BaseTopic.id_field("projects", p): p}, fail_on_empty=False,
64 fail_on_more=False):
65 raise EngineException("project '{}' does not exist".format(p), HTTPStatus.CONFLICT)
tiernob24258a2018-10-04 18:39:49 +020066
tiernob4844ab2019-05-23 08:42:12 +000067 def check_conflict_on_del(self, session, _id, db_content):
68 """
69 Check if deletion can be done because of dependencies if it is not force. To override
70 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
71 :param _id: internal _id
72 :param db_content: The database content of this item _id
73 :return: None if ok or raises EngineException with the conflict
74 """
tiernob24258a2018-10-04 18:39:49 +020075 if _id == session["username"]:
76 raise EngineException("You cannot delete your own user", http_code=HTTPStatus.CONFLICT)
77
78 @staticmethod
79 def format_on_new(content, project_id=None, make_public=False):
80 BaseTopic.format_on_new(content, make_public=False)
delacruzramoc061f562019-04-05 11:00:02 +020081 # Removed so that the UUID is kept, to allow User Name modification
82 # content["_id"] = content["username"]
tiernob24258a2018-10-04 18:39:49 +020083 salt = uuid4().hex
84 content["_admin"]["salt"] = salt
85 if content.get("password"):
86 content["password"] = sha256(content["password"].encode('utf-8') + salt.encode('utf-8')).hexdigest()
Eduardo Sousa339ed782019-05-28 14:25:00 +010087 if content.get("project_role_mappings"):
88 projects = [mapping[0] for mapping in content["project_role_mappings"]]
89
90 if content.get("projects"):
91 content["projects"] += projects
92 else:
93 content["projects"] = projects
tiernob24258a2018-10-04 18:39:49 +020094
95 @staticmethod
96 def format_on_edit(final_content, edit_content):
97 BaseTopic.format_on_edit(final_content, edit_content)
98 if edit_content.get("password"):
99 salt = uuid4().hex
100 final_content["_admin"]["salt"] = salt
101 final_content["password"] = sha256(edit_content["password"].encode('utf-8') +
102 salt.encode('utf-8')).hexdigest()
103
tierno65ca36d2019-02-12 19:27:52 +0100104 def edit(self, session, _id, indata=None, kwargs=None, content=None):
tiernob24258a2018-10-04 18:39:49 +0200105 if not session["admin"]:
106 raise EngineException("needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED)
delacruzramoc061f562019-04-05 11:00:02 +0200107 # Names that look like UUIDs are not allowed
108 name = (indata if indata else kwargs).get("username")
109 if is_valid_uuid(name):
110 raise EngineException("Usernames that look like UUIDs are not allowed",
111 http_code=HTTPStatus.UNPROCESSABLE_ENTITY)
tierno65ca36d2019-02-12 19:27:52 +0100112 return BaseTopic.edit(self, session, _id, indata=indata, kwargs=kwargs, content=content)
tiernob24258a2018-10-04 18:39:49 +0200113
tierno65ca36d2019-02-12 19:27:52 +0100114 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +0200115 if not session["admin"]:
116 raise EngineException("needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED)
delacruzramoc061f562019-04-05 11:00:02 +0200117 # Names that look like UUIDs are not allowed
118 name = indata["username"] if indata else kwargs["username"]
119 if is_valid_uuid(name):
120 raise EngineException("Usernames that look like UUIDs are not allowed",
121 http_code=HTTPStatus.UNPROCESSABLE_ENTITY)
tierno65ca36d2019-02-12 19:27:52 +0100122 return BaseTopic.new(self, rollback, session, indata=indata, kwargs=kwargs, headers=headers)
tiernob24258a2018-10-04 18:39:49 +0200123
124
125class ProjectTopic(BaseTopic):
126 topic = "projects"
127 topic_msg = "projects"
128 schema_new = project_new_schema
129 schema_edit = project_edit_schema
tierno65ca36d2019-02-12 19:27:52 +0100130 multiproject = False
tiernob24258a2018-10-04 18:39:49 +0200131
132 def __init__(self, db, fs, msg):
133 BaseTopic.__init__(self, db, fs, msg)
134
tierno65ca36d2019-02-12 19:27:52 +0100135 @staticmethod
136 def _get_project_filter(session):
137 """
138 Generates a filter dictionary for querying database users.
139 Current policy is admin can show all, non admin, only its own user.
140 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
141 :return:
142 """
143 if session["admin"]: # allows all
144 return {}
145 else:
146 return {"_id.cont": session["project_id"]}
147
148 def check_conflict_on_new(self, session, indata):
tiernob24258a2018-10-04 18:39:49 +0200149 if not indata.get("name"):
150 raise EngineException("missing 'name'")
151 # check name not exists
152 if self.db.get_one(self.topic, {"name": indata.get("name")}, fail_on_empty=False, fail_on_more=False):
153 raise EngineException("name '{}' exists".format(indata["name"]), HTTPStatus.CONFLICT)
154
155 @staticmethod
156 def format_on_new(content, project_id=None, make_public=False):
157 BaseTopic.format_on_new(content, None)
delacruzramoc061f562019-04-05 11:00:02 +0200158 # Removed so that the UUID is kept, to allow Project Name modification
159 # content["_id"] = content["name"]
tiernob24258a2018-10-04 18:39:49 +0200160
tiernob4844ab2019-05-23 08:42:12 +0000161 def check_conflict_on_del(self, session, _id, db_content):
162 """
163 Check if deletion can be done because of dependencies if it is not force. To override
164 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
165 :param _id: internal _id
166 :param db_content: The database content of this item _id
167 :return: None if ok or raises EngineException with the conflict
168 """
tierno65ca36d2019-02-12 19:27:52 +0100169 if _id in session["project_id"]:
tiernob24258a2018-10-04 18:39:49 +0200170 raise EngineException("You cannot delete your own project", http_code=HTTPStatus.CONFLICT)
tierno65ca36d2019-02-12 19:27:52 +0100171 if session["force"]:
tiernob24258a2018-10-04 18:39:49 +0200172 return
173 _filter = {"projects": _id}
174 if self.db.get_list("users", _filter):
175 raise EngineException("There is some USER that contains this project", http_code=HTTPStatus.CONFLICT)
176
tierno65ca36d2019-02-12 19:27:52 +0100177 def edit(self, session, _id, indata=None, kwargs=None, content=None):
tiernob24258a2018-10-04 18:39:49 +0200178 if not session["admin"]:
179 raise EngineException("needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED)
delacruzramoc061f562019-04-05 11:00:02 +0200180 # Names that look like UUIDs are not allowed
181 name = (indata if indata else kwargs).get("name")
182 if is_valid_uuid(name):
183 raise EngineException("Project names that look like UUIDs are not allowed",
184 http_code=HTTPStatus.UNPROCESSABLE_ENTITY)
tierno65ca36d2019-02-12 19:27:52 +0100185 return BaseTopic.edit(self, session, _id, indata=indata, kwargs=kwargs, content=content)
tiernob24258a2018-10-04 18:39:49 +0200186
tierno65ca36d2019-02-12 19:27:52 +0100187 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +0200188 if not session["admin"]:
189 raise EngineException("needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED)
delacruzramoc061f562019-04-05 11:00:02 +0200190 # Names that look like UUIDs are not allowed
191 name = indata["name"] if indata else kwargs["name"]
192 if is_valid_uuid(name):
193 raise EngineException("Project names that look like UUIDs are not allowed",
194 http_code=HTTPStatus.UNPROCESSABLE_ENTITY)
tierno65ca36d2019-02-12 19:27:52 +0100195 return BaseTopic.new(self, rollback, session, indata=indata, kwargs=kwargs, headers=headers)
tiernob24258a2018-10-04 18:39:49 +0200196
197
198class VimAccountTopic(BaseTopic):
199 topic = "vim_accounts"
200 topic_msg = "vim_account"
201 schema_new = vim_account_new_schema
202 schema_edit = vim_account_edit_schema
tierno92c1c7d2018-11-12 15:22:37 +0100203 vim_config_encrypted = ("admin_password", "nsx_password", "vcenter_password")
tierno65ca36d2019-02-12 19:27:52 +0100204 multiproject = True
tiernob24258a2018-10-04 18:39:49 +0200205
206 def __init__(self, db, fs, msg):
207 BaseTopic.__init__(self, db, fs, msg)
208
tierno65ca36d2019-02-12 19:27:52 +0100209 def check_conflict_on_new(self, session, indata):
tiernob24258a2018-10-04 18:39:49 +0200210 self.check_unique_name(session, indata["name"], _id=None)
211
tierno65ca36d2019-02-12 19:27:52 +0100212 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
213 if not session["force"] and edit_content.get("name"):
tiernob24258a2018-10-04 18:39:49 +0200214 self.check_unique_name(session, edit_content["name"], _id=_id)
215
tierno92c1c7d2018-11-12 15:22:37 +0100216 # encrypt passwords
217 schema_version = final_content.get("schema_version")
218 if schema_version:
219 if edit_content.get("vim_password"):
220 final_content["vim_password"] = self.db.encrypt(edit_content["vim_password"],
221 schema_version=schema_version, salt=_id)
222 if edit_content.get("config"):
223 for p in self.vim_config_encrypted:
224 if edit_content["config"].get(p):
225 final_content["config"][p] = self.db.encrypt(edit_content["config"][p],
226 schema_version=schema_version, salt=_id)
227
228 def format_on_new(self, content, project_id=None, make_public=False):
229 BaseTopic.format_on_new(content, project_id=project_id, make_public=make_public)
230 content["schema_version"] = schema_version = "1.1"
231
232 # encrypt passwords
233 if content.get("vim_password"):
234 content["vim_password"] = self.db.encrypt(content["vim_password"], schema_version=schema_version,
235 salt=content["_id"])
236 if content.get("config"):
237 for p in self.vim_config_encrypted:
238 if content["config"].get(p):
239 content["config"][p] = self.db.encrypt(content["config"][p], schema_version=schema_version,
240 salt=content["_id"])
241
tiernob24258a2018-10-04 18:39:49 +0200242 content["_admin"]["operationalState"] = "PROCESSING"
243
tierno65ca36d2019-02-12 19:27:52 +0100244 def delete(self, session, _id, dry_run=False):
tiernob24258a2018-10-04 18:39:49 +0200245 """
246 Delete item by its internal _id
tierno65ca36d2019-02-12 19:27:52 +0100247 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +0200248 :param _id: server internal id
tiernob24258a2018-10-04 18:39:49 +0200249 :param dry_run: make checking but do not delete
250 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
251 """
252 # TODO add admin to filter, validate rights
tierno65ca36d2019-02-12 19:27:52 +0100253 if dry_run or session["force"]: # delete completely
254 return BaseTopic.delete(self, session, _id, dry_run)
tiernob24258a2018-10-04 18:39:49 +0200255 else: # if not, sent to kafka
tierno65ca36d2019-02-12 19:27:52 +0100256 v = BaseTopic.delete(self, session, _id, dry_run=True)
tiernob24258a2018-10-04 18:39:49 +0200257 self.db.set_one("vim_accounts", {"_id": _id}, {"_admin.to_delete": True}) # TODO change status
258 self._send_msg("delete", {"_id": _id})
259 return v # TODO indicate an offline operation to return 202 ACCEPTED
260
261
tierno55ba2e62018-12-11 17:22:22 +0000262class WimAccountTopic(BaseTopic):
263 topic = "wim_accounts"
264 topic_msg = "wim_account"
265 schema_new = wim_account_new_schema
266 schema_edit = wim_account_edit_schema
tierno65ca36d2019-02-12 19:27:52 +0100267 multiproject = True
tierno55ba2e62018-12-11 17:22:22 +0000268 wim_config_encrypted = ()
269
270 def __init__(self, db, fs, msg):
271 BaseTopic.__init__(self, db, fs, msg)
272
tierno65ca36d2019-02-12 19:27:52 +0100273 def check_conflict_on_new(self, session, indata):
tierno55ba2e62018-12-11 17:22:22 +0000274 self.check_unique_name(session, indata["name"], _id=None)
275
tierno65ca36d2019-02-12 19:27:52 +0100276 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
277 if not session["force"] and edit_content.get("name"):
tierno55ba2e62018-12-11 17:22:22 +0000278 self.check_unique_name(session, edit_content["name"], _id=_id)
279
280 # encrypt passwords
281 schema_version = final_content.get("schema_version")
282 if schema_version:
283 if edit_content.get("wim_password"):
284 final_content["wim_password"] = self.db.encrypt(edit_content["wim_password"],
285 schema_version=schema_version, salt=_id)
286 if edit_content.get("config"):
287 for p in self.wim_config_encrypted:
288 if edit_content["config"].get(p):
289 final_content["config"][p] = self.db.encrypt(edit_content["config"][p],
290 schema_version=schema_version, salt=_id)
291
292 def format_on_new(self, content, project_id=None, make_public=False):
293 BaseTopic.format_on_new(content, project_id=project_id, make_public=make_public)
294 content["schema_version"] = schema_version = "1.1"
295
296 # encrypt passwords
297 if content.get("wim_password"):
298 content["wim_password"] = self.db.encrypt(content["wim_password"], schema_version=schema_version,
299 salt=content["_id"])
300 if content.get("config"):
301 for p in self.wim_config_encrypted:
302 if content["config"].get(p):
303 content["config"][p] = self.db.encrypt(content["config"][p], schema_version=schema_version,
304 salt=content["_id"])
305
306 content["_admin"]["operationalState"] = "PROCESSING"
307
tierno65ca36d2019-02-12 19:27:52 +0100308 def delete(self, session, _id, dry_run=False):
tierno55ba2e62018-12-11 17:22:22 +0000309 """
310 Delete item by its internal _id
tierno65ca36d2019-02-12 19:27:52 +0100311 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tierno55ba2e62018-12-11 17:22:22 +0000312 :param _id: server internal id
tierno55ba2e62018-12-11 17:22:22 +0000313 :param dry_run: make checking but do not delete
314 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
315 """
316 # TODO add admin to filter, validate rights
tierno65ca36d2019-02-12 19:27:52 +0100317 if dry_run or session["force"]: # delete completely
318 return BaseTopic.delete(self, session, _id, dry_run)
tierno55ba2e62018-12-11 17:22:22 +0000319 else: # if not, sent to kafka
tierno65ca36d2019-02-12 19:27:52 +0100320 v = BaseTopic.delete(self, session, _id, dry_run=True)
tierno55ba2e62018-12-11 17:22:22 +0000321 self.db.set_one("wim_accounts", {"_id": _id}, {"_admin.to_delete": True}) # TODO change status
322 self._send_msg("delete", {"_id": _id})
323 return v # TODO indicate an offline operation to return 202 ACCEPTED
324
325
tiernob24258a2018-10-04 18:39:49 +0200326class SdnTopic(BaseTopic):
327 topic = "sdns"
328 topic_msg = "sdn"
329 schema_new = sdn_new_schema
330 schema_edit = sdn_edit_schema
tierno65ca36d2019-02-12 19:27:52 +0100331 multiproject = True
tiernob24258a2018-10-04 18:39:49 +0200332
333 def __init__(self, db, fs, msg):
334 BaseTopic.__init__(self, db, fs, msg)
335
tierno65ca36d2019-02-12 19:27:52 +0100336 def check_conflict_on_new(self, session, indata):
tiernob24258a2018-10-04 18:39:49 +0200337 self.check_unique_name(session, indata["name"], _id=None)
338
tierno65ca36d2019-02-12 19:27:52 +0100339 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
340 if not session["force"] and edit_content.get("name"):
tiernob24258a2018-10-04 18:39:49 +0200341 self.check_unique_name(session, edit_content["name"], _id=_id)
342
tierno92c1c7d2018-11-12 15:22:37 +0100343 # encrypt passwords
344 schema_version = final_content.get("schema_version")
345 if schema_version and edit_content.get("password"):
346 final_content["password"] = self.db.encrypt(edit_content["password"], schema_version=schema_version,
347 salt=_id)
348
349 def format_on_new(self, content, project_id=None, make_public=False):
350 BaseTopic.format_on_new(content, project_id=project_id, make_public=make_public)
351 content["schema_version"] = schema_version = "1.1"
352 # encrypt passwords
353 if content.get("password"):
354 content["password"] = self.db.encrypt(content["password"], schema_version=schema_version,
355 salt=content["_id"])
356
tiernob24258a2018-10-04 18:39:49 +0200357 content["_admin"]["operationalState"] = "PROCESSING"
358
tierno65ca36d2019-02-12 19:27:52 +0100359 def delete(self, session, _id, dry_run=False):
tiernob24258a2018-10-04 18:39:49 +0200360 """
361 Delete item by its internal _id
tierno65ca36d2019-02-12 19:27:52 +0100362 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +0200363 :param _id: server internal id
tiernob24258a2018-10-04 18:39:49 +0200364 :param dry_run: make checking but do not delete
365 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
366 """
tierno65ca36d2019-02-12 19:27:52 +0100367 if dry_run or session["force"]: # delete completely
368 return BaseTopic.delete(self, session, _id, dry_run)
tiernob24258a2018-10-04 18:39:49 +0200369 else: # if not sent to kafka
tierno65ca36d2019-02-12 19:27:52 +0100370 v = BaseTopic.delete(self, session, _id, dry_run=True)
tiernob24258a2018-10-04 18:39:49 +0200371 self.db.set_one("sdns", {"_id": _id}, {"_admin.to_delete": True}) # TODO change status
372 self._send_msg("delete", {"_id": _id})
373 return v # TODO indicate an offline operation to return 202 ACCEPTED
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100374
375
376class UserTopicAuth(UserTopic):
tierno65ca36d2019-02-12 19:27:52 +0100377 # topic = "users"
378 # topic_msg = "users"
Eduardo Sousaa16a4fa2019-05-23 01:41:18 +0100379 schema_new = user_new_schema
380 schema_edit = user_edit_schema
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100381
382 def __init__(self, db, fs, msg, auth):
383 UserTopic.__init__(self, db, fs, msg)
384 self.auth = auth
385
tierno65ca36d2019-02-12 19:27:52 +0100386 def check_conflict_on_new(self, session, indata):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100387 """
388 Check that the data to be inserted is valid
389
tierno65ca36d2019-02-12 19:27:52 +0100390 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100391 :param indata: data to be inserted
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100392 :return: None or raises EngineException
393 """
394 username = indata.get("username")
395 user_list = list(map(lambda x: x["username"], self.auth.get_user_list()))
396
Eduardo Sousa339ed782019-05-28 14:25:00 +0100397 if "projects" in indata.keys():
398 raise EngineException("Format invalid: the keyword \"projects\" is not allowed for Keystone",
399 HTTPStatus.BAD_REQUEST)
400
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100401 if username in user_list:
402 raise EngineException("username '{}' exists".format(username), HTTPStatus.CONFLICT)
403
tierno65ca36d2019-02-12 19:27:52 +0100404 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100405 """
406 Check that the data to be edited/uploaded is valid
407
tierno65ca36d2019-02-12 19:27:52 +0100408 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100409 :param final_content: data once modified
410 :param edit_content: incremental data that contains the modifications to apply
411 :param _id: internal _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100412 :return: None or raises EngineException
413 """
414 users = self.auth.get_user_list()
415 admin_user = [user for user in users if user["name"] == "admin"][0]
416
417 if _id == admin_user["_id"] and edit_content["project_role_mappings"]:
418 elem = {
419 "project": "admin",
420 "role": "system_admin"
421 }
422 if elem not in edit_content:
423 raise EngineException("You cannot remove system_admin role from admin user",
424 http_code=HTTPStatus.FORBIDDEN)
425
tiernob4844ab2019-05-23 08:42:12 +0000426 def check_conflict_on_del(self, session, _id, db_content):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100427 """
428 Check if deletion can be done because of dependencies if it is not force. To override
tierno65ca36d2019-02-12 19:27:52 +0100429 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100430 :param _id: internal _id
tiernob4844ab2019-05-23 08:42:12 +0000431 :param db_content: The database content of this item _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100432 :return: None if ok or raises EngineException with the conflict
433 """
434 if _id == session["username"]:
435 raise EngineException("You cannot delete your own user", http_code=HTTPStatus.CONFLICT)
436
437 @staticmethod
438 def format_on_new(content, project_id=None, make_public=False):
439 """
440 Modifies content descriptor to include _id.
441
442 NOTE: No password salt required because the authentication backend
443 should handle these security concerns.
444
445 :param content: descriptor to be modified
446 :param make_public: if included it is generated as public for reading.
447 :return: None, but content is modified
448 """
449 BaseTopic.format_on_new(content, make_public=False)
450 content["_id"] = content["username"]
451 content["password"] = content["password"]
452
453 @staticmethod
454 def format_on_edit(final_content, edit_content):
455 """
456 Modifies final_content descriptor to include the modified date.
457
458 NOTE: No password salt required because the authentication backend
459 should handle these security concerns.
460
461 :param final_content: final descriptor generated
462 :param edit_content: alterations to be include
463 :return: None, but final_content is modified
464 """
465 BaseTopic.format_on_edit(final_content, edit_content)
466 if "password" in edit_content:
467 final_content["password"] = edit_content["password"]
468 else:
469 final_content["project_role_mappings"] = edit_content["project_role_mappings"]
470
Eduardo Sousaa16a4fa2019-05-23 01:41:18 +0100471 @staticmethod
472 def format_on_show(content):
473 """
474 Modifies the content of the role information to separate the role
475 metadata from the role definition.
476 """
477 project_role_mappings = []
478
479 for project in content["projects"]:
480 for role in project["roles"]:
Eduardo Sousa88d58a42019-05-30 13:18:36 +0100481 project_role_mappings.append({"project": project, "role": role})
Eduardo Sousaa16a4fa2019-05-23 01:41:18 +0100482
483 del content["projects"]
484 content["project_role_mappings"] = project_role_mappings
485
Eduardo Sousa0b1d61b2019-05-30 19:55:52 +0100486 return content
487
tierno65ca36d2019-02-12 19:27:52 +0100488 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100489 """
490 Creates a new entry into the authentication backend.
491
492 NOTE: Overrides BaseTopic functionality because it doesn't require access to database.
493
494 :param rollback: list to append created items at database in case a rollback may to be done
tierno65ca36d2019-02-12 19:27:52 +0100495 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100496 :param indata: data to be inserted
497 :param kwargs: used to override the indata descriptor
498 :param headers: http request headers
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100499 :return: _id: identity of the inserted data.
500 """
501 try:
502 content = BaseTopic._remove_envelop(indata)
503
504 # Override descriptor with query string kwargs
505 BaseTopic._update_input_with_kwargs(content, kwargs)
tierno65ca36d2019-02-12 19:27:52 +0100506 content = self._validate_input_new(content, session["force"])
507 self.check_conflict_on_new(session, content)
508 self.format_on_new(content, session["project_id"], make_public=session["public"])
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100509 _id = self.auth.create_user(content["username"], content["password"])
510 rollback.append({"topic": self.topic, "_id": _id})
511 del content["password"]
512 # self._send_msg("create", content)
513 return _id
514 except ValidationError as e:
515 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
516
517 def show(self, session, _id):
518 """
519 Get complete information on an topic
520
tierno65ca36d2019-02-12 19:27:52 +0100521 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100522 :param _id: server internal id
523 :return: dictionary, raise exception if not found.
524 """
525 users = [user for user in self.auth.get_user_list() if user["_id"] == _id]
526
527 if len(users) == 1:
Eduardo Sousaa16a4fa2019-05-23 01:41:18 +0100528 return self.format_on_show(users[0])
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100529 elif len(users) > 1:
530 raise EngineException("Too many users found", HTTPStatus.CONFLICT)
531 else:
532 raise EngineException("User not found", HTTPStatus.NOT_FOUND)
533
tierno65ca36d2019-02-12 19:27:52 +0100534 def edit(self, session, _id, indata=None, kwargs=None, content=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100535 """
536 Updates an user entry.
537
tierno65ca36d2019-02-12 19:27:52 +0100538 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100539 :param _id:
540 :param indata: data to be inserted
541 :param kwargs: used to override the indata descriptor
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100542 :param content:
543 :return: _id: identity of the inserted data.
544 """
545 indata = self._remove_envelop(indata)
546
547 # Override descriptor with query string kwargs
548 if kwargs:
549 BaseTopic._update_input_with_kwargs(indata, kwargs)
550 try:
tierno65ca36d2019-02-12 19:27:52 +0100551 indata = self._validate_input_edit(indata, force=session["force"])
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100552
553 if not content:
554 content = self.show(session, _id)
tierno65ca36d2019-02-12 19:27:52 +0100555 self.check_conflict_on_edit(session, content, indata, _id=_id)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100556 self.format_on_edit(content, indata)
557
558 if "password" in content:
559 self.auth.change_password(content["name"], content["password"])
560 else:
Eduardo Sousaa16a4fa2019-05-23 01:41:18 +0100561 user = self.show(session, _id)
562 original_mapping = user["project_role_mappings"]
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100563 edit_mapping = content["project_role_mappings"]
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100564
565 mappings_to_remove = [mapping for mapping in original_mapping
566 if mapping not in edit_mapping]
567
568 mappings_to_add = [mapping for mapping in edit_mapping
569 if mapping not in original_mapping]
570
571 for mapping in mappings_to_remove:
572 self.auth.remove_role_from_user(
573 user["name"],
Eduardo Sousa88d58a42019-05-30 13:18:36 +0100574 mapping["project"],
575 mapping["role"]
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100576 )
577
578 for mapping in mappings_to_add:
579 self.auth.assign_role_to_user(
580 user["name"],
Eduardo Sousa88d58a42019-05-30 13:18:36 +0100581 mapping["project"],
582 mapping["role"]
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100583 )
584
585 return content["_id"]
586 except ValidationError as e:
587 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
588
589 def list(self, session, filter_q=None):
590 """
591 Get a list of the topic that matches a filter
tierno65ca36d2019-02-12 19:27:52 +0100592 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100593 :param filter_q: filter of data to be applied
594 :return: The list, it can be empty if no one match the filter.
595 """
Eduardo Sousa2d5a5152019-05-20 15:41:54 +0100596 if not filter_q:
597 filter_q = {}
598
Eduardo Sousaa16a4fa2019-05-23 01:41:18 +0100599 users = [self.format_on_show(user) for user in self.auth.get_user_list(filter_q)]
600
601 return users
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100602
tierno65ca36d2019-02-12 19:27:52 +0100603 def delete(self, session, _id, dry_run=False):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100604 """
605 Delete item by its internal _id
606
tierno65ca36d2019-02-12 19:27:52 +0100607 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100608 :param _id: server internal id
609 :param force: indicates if deletion must be forced in case of conflict
610 :param dry_run: make checking but do not delete
611 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
612 """
tiernob4844ab2019-05-23 08:42:12 +0000613 self.check_conflict_on_del(session, _id, None)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100614 if not dry_run:
615 v = self.auth.delete_user(_id)
616 return v
617 return None
618
619
620class ProjectTopicAuth(ProjectTopic):
tierno65ca36d2019-02-12 19:27:52 +0100621 # topic = "projects"
622 # topic_msg = "projects"
623 # schema_new = project_new_schema
624 # schema_edit = project_edit_schema
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100625
626 def __init__(self, db, fs, msg, auth):
627 ProjectTopic.__init__(self, db, fs, msg)
628 self.auth = auth
629
tierno65ca36d2019-02-12 19:27:52 +0100630 def check_conflict_on_new(self, session, indata):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100631 """
632 Check that the data to be inserted is valid
633
tierno65ca36d2019-02-12 19:27:52 +0100634 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100635 :param indata: data to be inserted
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100636 :return: None or raises EngineException
637 """
638 project = indata.get("name")
639 project_list = list(map(lambda x: x["name"], self.auth.get_project_list()))
640
641 if project in project_list:
642 raise EngineException("project '{}' exists".format(project), HTTPStatus.CONFLICT)
643
tiernob4844ab2019-05-23 08:42:12 +0000644 def check_conflict_on_del(self, session, _id, db_content):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100645 """
646 Check if deletion can be done because of dependencies if it is not force. To override
647
tierno65ca36d2019-02-12 19:27:52 +0100648 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100649 :param _id: internal _id
tiernob4844ab2019-05-23 08:42:12 +0000650 :param db_content: The database content of this item _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100651 :return: None if ok or raises EngineException with the conflict
652 """
653 projects = self.auth.get_project_list()
654 current_project = [project for project in projects
655 if project["name"] == session["project_id"]][0]
656
657 if _id == current_project["_id"]:
658 raise EngineException("You cannot delete your own project", http_code=HTTPStatus.CONFLICT)
659
tierno65ca36d2019-02-12 19:27:52 +0100660 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100661 """
662 Creates a new entry into the authentication backend.
663
664 NOTE: Overrides BaseTopic functionality because it doesn't require access to database.
665
666 :param rollback: list to append created items at database in case a rollback may to be done
tierno65ca36d2019-02-12 19:27:52 +0100667 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100668 :param indata: data to be inserted
669 :param kwargs: used to override the indata descriptor
670 :param headers: http request headers
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100671 :return: _id: identity of the inserted data.
672 """
673 try:
674 content = BaseTopic._remove_envelop(indata)
675
676 # Override descriptor with query string kwargs
677 BaseTopic._update_input_with_kwargs(content, kwargs)
tierno65ca36d2019-02-12 19:27:52 +0100678 content = self._validate_input_new(content, session["force"])
679 self.check_conflict_on_new(session, content)
680 self.format_on_new(content, project_id=session["project_id"], make_public=session["public"])
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100681 _id = self.auth.create_project(content["name"])
682 rollback.append({"topic": self.topic, "_id": _id})
683 # self._send_msg("create", content)
684 return _id
685 except ValidationError as e:
686 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
687
688 def show(self, session, _id):
689 """
690 Get complete information on an topic
691
tierno65ca36d2019-02-12 19:27:52 +0100692 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100693 :param _id: server internal id
694 :return: dictionary, raise exception if not found.
695 """
696 projects = [project for project in self.auth.get_project_list() if project["_id"] == _id]
697
698 if len(projects) == 1:
699 return projects[0]
700 elif len(projects) > 1:
701 raise EngineException("Too many projects found", HTTPStatus.CONFLICT)
702 else:
703 raise EngineException("Project not found", HTTPStatus.NOT_FOUND)
704
705 def list(self, session, filter_q=None):
706 """
707 Get a list of the topic that matches a filter
708
tierno65ca36d2019-02-12 19:27:52 +0100709 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100710 :param filter_q: filter of data to be applied
711 :return: The list, it can be empty if no one match the filter.
712 """
Eduardo Sousafa54cd92019-05-20 15:58:41 +0100713 if not filter_q:
714 filter_q = {}
715
716 return self.auth.get_project_list(filter_q)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100717
tierno65ca36d2019-02-12 19:27:52 +0100718 def delete(self, session, _id, dry_run=False):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100719 """
720 Delete item by its internal _id
721
tierno65ca36d2019-02-12 19:27:52 +0100722 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100723 :param _id: server internal id
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100724 :param dry_run: make checking but do not delete
725 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
726 """
tiernob4844ab2019-05-23 08:42:12 +0000727 self.check_conflict_on_del(session, _id, None)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100728 if not dry_run:
729 v = self.auth.delete_project(_id)
730 return v
731 return None
732
733
734class RoleTopicAuth(BaseTopic):
735 topic = "roles_operations"
736 topic_msg = "roles"
737 schema_new = roles_new_schema
738 schema_edit = roles_edit_schema
tierno65ca36d2019-02-12 19:27:52 +0100739 multiproject = False
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100740
741 def __init__(self, db, fs, msg, auth, ops):
742 BaseTopic.__init__(self, db, fs, msg)
743 self.auth = auth
744 self.operations = ops
745
746 @staticmethod
747 def validate_role_definition(operations, role_definitions):
748 """
749 Validates the role definition against the operations defined in
750 the resources to operations files.
751
752 :param operations: operations list
753 :param role_definitions: role definition to test
754 :return: None if ok, raises ValidationError exception on error
755 """
Eduardo Sousa867a2ee2019-05-29 09:53:36 +0100756 ignore_fields = ["_id", "_admin", "name"]
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100757 for role_def in role_definitions.keys():
Eduardo Sousa37de0912019-05-23 02:17:22 +0100758 if role_def in ignore_fields:
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100759 continue
Eduardo Sousa37de0912019-05-23 02:17:22 +0100760 if role_def == ".":
761 if isinstance(role_definitions[role_def], bool):
762 continue
763 else:
764 raise ValidationError("Operation authorization \".\" should be True/False.")
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100765 if role_def[-1] == ".":
766 raise ValidationError("Operation cannot end with \".\"")
767
delacruzramoc061f562019-04-05 11:00:02 +0200768 role_def_matches = [op for op in operations if op.startswith(role_def)]
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100769
770 if len(role_def_matches) == 0:
771 raise ValidationError("No matching operation found.")
772
Eduardo Sousa37de0912019-05-23 02:17:22 +0100773 if not isinstance(role_definitions[role_def], bool):
774 raise ValidationError("Operation authorization {} should be True/False.".format(role_def))
775
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100776 def _validate_input_new(self, input, force=False):
777 """
778 Validates input user content for a new entry.
779
780 :param input: user input content for the new topic
781 :param force: may be used for being more tolerant
782 :return: The same input content, or a changed version of it.
783 """
784 if self.schema_new:
785 validate_input(input, self.schema_new)
Eduardo Sousa37de0912019-05-23 02:17:22 +0100786 self.validate_role_definition(self.operations, input)
787
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100788 return input
789
790 def _validate_input_edit(self, input, force=False):
791 """
792 Validates input user content for updating an entry.
793
794 :param input: user input content for the new topic
795 :param force: may be used for being more tolerant
796 :return: The same input content, or a changed version of it.
797 """
798 if self.schema_edit:
799 validate_input(input, self.schema_edit)
Eduardo Sousa37de0912019-05-23 02:17:22 +0100800 self.validate_role_definition(self.operations, input)
801
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100802 return input
803
tierno65ca36d2019-02-12 19:27:52 +0100804 def check_conflict_on_new(self, session, indata):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100805 """
806 Check that the data to be inserted is valid
807
tierno65ca36d2019-02-12 19:27:52 +0100808 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100809 :param indata: data to be inserted
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100810 :return: None or raises EngineException
811 """
812 role = indata.get("name")
813 role_list = list(map(lambda x: x["name"], self.auth.get_role_list()))
814
815 if role in role_list:
816 raise EngineException("role '{}' exists".format(role), HTTPStatus.CONFLICT)
817
tierno65ca36d2019-02-12 19:27:52 +0100818 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100819 """
820 Check that the data to be edited/uploaded is valid
821
tierno65ca36d2019-02-12 19:27:52 +0100822 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100823 :param final_content: data once modified
824 :param edit_content: incremental data that contains the modifications to apply
825 :param _id: internal _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100826 :return: None or raises EngineException
827 """
828 roles = self.auth.get_role_list()
829 system_admin_role = [role for role in roles
830 if roles["name"] == "system_admin"][0]
831
832 if _id == system_admin_role["_id"]:
833 raise EngineException("You cannot edit system_admin role", http_code=HTTPStatus.FORBIDDEN)
834
tiernob4844ab2019-05-23 08:42:12 +0000835 def check_conflict_on_del(self, session, _id, db_content):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100836 """
837 Check if deletion can be done because of dependencies if it is not force. To override
838
tierno65ca36d2019-02-12 19:27:52 +0100839 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100840 :param _id: internal _id
tiernob4844ab2019-05-23 08:42:12 +0000841 :param db_content: The database content of this item _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100842 :return: None if ok or raises EngineException with the conflict
843 """
844 roles = self.auth.get_role_list()
845 system_admin_role = [role for role in roles
846 if roles["name"] == "system_admin"][0]
847
848 if _id == system_admin_role["_id"]:
849 raise EngineException("You cannot delete system_admin role", http_code=HTTPStatus.FORBIDDEN)
850
851 @staticmethod
852 def format_on_new(content, project_id=None, make_public=False):
853 """
854 Modifies content descriptor to include _admin
855
856 :param content: descriptor to be modified
857 :param project_id: if included, it add project read/write permissions
858 :param make_public: if included it is generated as public for reading.
859 :return: None, but content is modified
860 """
861 now = time()
862 if "_admin" not in content:
863 content["_admin"] = {}
864 if not content["_admin"].get("created"):
865 content["_admin"]["created"] = now
866 content["_admin"]["modified"] = now
Eduardo Sousa871f8882019-05-29 14:43:05 +0100867
868 if "." in content.keys():
869 content["root"] = content["."]
870 del content["."]
871
872 if "root" not in content.keys():
873 content["root"] = False
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100874
Eduardo Sousa37de0912019-05-23 02:17:22 +0100875 ignore_fields = ["_id", "_admin", "name"]
Eduardo Sousa568ca902019-05-29 11:03:57 +0100876 content_keys = content.keys()
877 for role_def in content_keys:
Eduardo Sousa37de0912019-05-23 02:17:22 +0100878 if role_def in ignore_fields:
879 continue
Eduardo Sousa568ca902019-05-29 11:03:57 +0100880 content[role_def.replace(".", ":")] = content[role_def]
Eduardo Sousa37de0912019-05-23 02:17:22 +0100881 del content[role_def]
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100882
883 @staticmethod
884 def format_on_edit(final_content, edit_content):
885 """
886 Modifies final_content descriptor to include the modified date.
887
888 :param final_content: final descriptor generated
889 :param edit_content: alterations to be include
890 :return: None, but final_content is modified
891 """
892 final_content["_admin"]["modified"] = time()
893
894 ignore_fields = ["_id", "name", "_admin"]
895 delete_keys = [key for key in final_content.keys() if key not in ignore_fields]
896
897 for key in delete_keys:
898 del final_content[key]
899
900 # Saving the role definition
Eduardo Sousa37de0912019-05-23 02:17:22 +0100901 for role_def, value in edit_content.items():
902 final_content[role_def.replace(".", ":")] = value
903
Eduardo Sousa871f8882019-05-29 14:43:05 +0100904 if ":" in final_content.keys():
905 final_content["root"] = final_content[":"]
906 del final_content[":"]
907
908 if "root" not in final_content.keys():
909 final_content["root"] = False
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100910
911 @staticmethod
912 def format_on_show(content):
913 """
914 Modifies the content of the role information to separate the role
915 metadata from the role definition. Eases the reading process of the
916 role definition.
917
918 :param definition: role definition to be processed
919 """
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100920 content_keys = list(content.keys())
Eduardo Sousa37de0912019-05-23 02:17:22 +0100921
Eduardo Sousab1d73122019-05-29 11:09:16 +0100922 content["_id"] = str(content["_id"])
923
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100924 for key in content_keys:
Eduardo Sousa37de0912019-05-23 02:17:22 +0100925 if ":" in key:
926 content[key.replace(":", ".")] = content[key]
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100927 del content[key]
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100928
929 def show(self, session, _id):
930 """
931 Get complete information on an topic
932
tierno65ca36d2019-02-12 19:27:52 +0100933 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100934 :param _id: server internal id
935 :return: dictionary, raise exception if not found.
936 """
Eduardo Sousa867a2ee2019-05-29 09:53:36 +0100937 filter_db = self._get_project_filter(session)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100938 filter_db["_id"] = _id
939
940 role = self.db.get_one(self.topic, filter_db)
941 new_role = dict(role)
942 self.format_on_show(new_role)
943
944 return new_role
945
946 def list(self, session, filter_q=None):
947 """
948 Get a list of the topic that matches a filter
949
tierno65ca36d2019-02-12 19:27:52 +0100950 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100951 :param filter_q: filter of data to be applied
952 :return: The list, it can be empty if no one match the filter.
953 """
954 if not filter_q:
955 filter_q = {}
956
Eduardo Sousa867a2ee2019-05-29 09:53:36 +0100957 if "root" in filter_q:
958 filter_q[":"] = filter_q["root"]
959 del filter_q["root"]
960
961 if len(filter_q) > 0:
962 keys = [key for key in filter_q.keys() if "." in key]
963
964 for key in keys:
965 filter_q[key.replace(".", ":")] = filter_q[key]
966 del filter_q[key]
967
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100968 roles = self.db.get_list(self.topic, filter_q)
969 new_roles = []
970
971 for role in roles:
972 new_role = dict(role)
973 self.format_on_show(new_role)
974 new_roles.append(new_role)
975
976 return new_roles
977
tierno65ca36d2019-02-12 19:27:52 +0100978 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100979 """
980 Creates a new entry into database.
981
982 :param rollback: list to append created items at database in case a rollback may to be done
tierno65ca36d2019-02-12 19:27:52 +0100983 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100984 :param indata: data to be inserted
985 :param kwargs: used to override the indata descriptor
986 :param headers: http request headers
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100987 :return: _id: identity of the inserted data.
988 """
989 try:
990 content = BaseTopic._remove_envelop(indata)
991
992 # Override descriptor with query string kwargs
993 BaseTopic._update_input_with_kwargs(content, kwargs)
tierno65ca36d2019-02-12 19:27:52 +0100994 content = self._validate_input_new(content, session["force"])
995 self.check_conflict_on_new(session, content)
996 self.format_on_new(content, project_id=session["project_id"], make_public=session["public"])
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100997 role_name = content["name"]
998 role = self.auth.create_role(role_name)
999 content["_id"] = role["_id"]
1000 _id = self.db.create(self.topic, content)
1001 rollback.append({"topic": self.topic, "_id": _id})
1002 # self._send_msg("create", content)
1003 return _id
1004 except ValidationError as e:
1005 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1006
tierno65ca36d2019-02-12 19:27:52 +01001007 def delete(self, session, _id, dry_run=False):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001008 """
1009 Delete item by its internal _id
1010
tierno65ca36d2019-02-12 19:27:52 +01001011 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001012 :param _id: server internal id
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001013 :param dry_run: make checking but do not delete
1014 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
1015 """
tiernob4844ab2019-05-23 08:42:12 +00001016 self.check_conflict_on_del(session, _id, None)
1017 filter_q = self._get_project_filter(session)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001018 filter_q["_id"] = _id
1019 if not dry_run:
1020 self.auth.delete_role(_id)
1021 v = self.db.del_one(self.topic, filter_q)
1022 return v
1023 return None
1024
tierno65ca36d2019-02-12 19:27:52 +01001025 def edit(self, session, _id, indata=None, kwargs=None, content=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001026 """
1027 Updates a role entry.
1028
tierno65ca36d2019-02-12 19:27:52 +01001029 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001030 :param _id:
1031 :param indata: data to be inserted
1032 :param kwargs: used to override the indata descriptor
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001033 :param content:
1034 :return: _id: identity of the inserted data.
1035 """
1036 indata = self._remove_envelop(indata)
1037
1038 # Override descriptor with query string kwargs
1039 if kwargs:
tiernob4844ab2019-05-23 08:42:12 +00001040 self._update_input_with_kwargs(indata, kwargs)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001041 try:
tierno65ca36d2019-02-12 19:27:52 +01001042 indata = self._validate_input_edit(indata, force=session["force"])
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001043
1044 if not content:
1045 content = self.show(session, _id)
tierno65ca36d2019-02-12 19:27:52 +01001046 self.check_conflict_on_edit(session, content, indata, _id=_id)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001047 self.format_on_edit(content, indata)
1048 self.db.replace(self.topic, _id, content)
1049 return id
1050 except ValidationError as e:
1051 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)