blob: e887afb3bb310762c5b5c74b7177236b0f352cac [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
tierno23acf402019-08-28 13:36:34 +000021from osm_nbi.validation import user_new_schema, user_edit_schema, project_new_schema, project_edit_schema, \
22 vim_account_new_schema, vim_account_edit_schema, sdn_new_schema, sdn_edit_schema, \
23 wim_account_new_schema, wim_account_edit_schema, roles_new_schema, roles_edit_schema, \
delacruzramofe598fe2019-10-23 18:25:11 +020024 k8scluster_new_schema, k8scluster_edit_schema, k8srepo_new_schema, k8srepo_edit_schema, \
tierno23acf402019-08-28 13:36:34 +000025 validate_input, ValidationError, is_valid_uuid # To check that User/Project Names don't look like UUIDs
26from osm_nbi.base_topic import BaseTopic, EngineException
27from osm_nbi.authconn import AuthconnNotFoundException, AuthconnConflictException
delacruzramo01b15d32019-07-02 14:37:47 +020028from osm_common.dbbase import deep_update_rfc7396
tiernob24258a2018-10-04 18:39:49 +020029
30__author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
31
32
33class UserTopic(BaseTopic):
34 topic = "users"
35 topic_msg = "users"
36 schema_new = user_new_schema
37 schema_edit = user_edit_schema
tierno65ca36d2019-02-12 19:27:52 +010038 multiproject = False
tiernob24258a2018-10-04 18:39:49 +020039
delacruzramo32bab472019-09-13 12:24:22 +020040 def __init__(self, db, fs, msg, auth):
41 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +020042
43 @staticmethod
tierno65ca36d2019-02-12 19:27:52 +010044 def _get_project_filter(session):
tiernob24258a2018-10-04 18:39:49 +020045 """
46 Generates a filter dictionary for querying database users.
47 Current policy is admin can show all, non admin, only its own user.
tierno65ca36d2019-02-12 19:27:52 +010048 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +020049 :return:
50 """
51 if session["admin"]: # allows all
52 return {}
53 else:
54 return {"username": session["username"]}
55
tierno65ca36d2019-02-12 19:27:52 +010056 def check_conflict_on_new(self, session, indata):
tiernob24258a2018-10-04 18:39:49 +020057 # check username not exists
58 if self.db.get_one(self.topic, {"username": indata.get("username")}, fail_on_empty=False, fail_on_more=False):
59 raise EngineException("username '{}' exists".format(indata["username"]), HTTPStatus.CONFLICT)
60 # check projects
tierno65ca36d2019-02-12 19:27:52 +010061 if not session["force"]:
delacruzramoceb8baf2019-06-21 14:25:38 +020062 for p in indata.get("projects") or []:
delacruzramoc061f562019-04-05 11:00:02 +020063 # To allow project addressing by Name as well as ID
64 if not self.db.get_one("projects", {BaseTopic.id_field("projects", p): p}, fail_on_empty=False,
65 fail_on_more=False):
66 raise EngineException("project '{}' does not exist".format(p), HTTPStatus.CONFLICT)
tiernob24258a2018-10-04 18:39:49 +020067
tiernob4844ab2019-05-23 08:42:12 +000068 def check_conflict_on_del(self, session, _id, db_content):
69 """
70 Check if deletion can be done because of dependencies if it is not force. To override
71 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
72 :param _id: internal _id
73 :param db_content: The database content of this item _id
74 :return: None if ok or raises EngineException with the conflict
75 """
tiernob24258a2018-10-04 18:39:49 +020076 if _id == session["username"]:
77 raise EngineException("You cannot delete your own user", http_code=HTTPStatus.CONFLICT)
78
79 @staticmethod
80 def format_on_new(content, project_id=None, make_public=False):
81 BaseTopic.format_on_new(content, make_public=False)
delacruzramoc061f562019-04-05 11:00:02 +020082 # Removed so that the UUID is kept, to allow User Name modification
83 # content["_id"] = content["username"]
tiernob24258a2018-10-04 18:39:49 +020084 salt = uuid4().hex
85 content["_admin"]["salt"] = salt
86 if content.get("password"):
87 content["password"] = sha256(content["password"].encode('utf-8') + salt.encode('utf-8')).hexdigest()
Eduardo Sousa339ed782019-05-28 14:25:00 +010088 if content.get("project_role_mappings"):
delacruzramo01b15d32019-07-02 14:37:47 +020089 projects = [mapping["project"] for mapping in content["project_role_mappings"]]
Eduardo Sousa339ed782019-05-28 14:25:00 +010090
91 if content.get("projects"):
92 content["projects"] += projects
93 else:
94 content["projects"] = projects
tiernob24258a2018-10-04 18:39:49 +020095
96 @staticmethod
97 def format_on_edit(final_content, edit_content):
98 BaseTopic.format_on_edit(final_content, edit_content)
99 if edit_content.get("password"):
100 salt = uuid4().hex
101 final_content["_admin"]["salt"] = salt
102 final_content["password"] = sha256(edit_content["password"].encode('utf-8') +
103 salt.encode('utf-8')).hexdigest()
tiernobdebce92019-07-01 15:36:49 +0000104 return None
tiernob24258a2018-10-04 18:39:49 +0200105
tierno65ca36d2019-02-12 19:27:52 +0100106 def edit(self, session, _id, indata=None, kwargs=None, content=None):
tiernob24258a2018-10-04 18:39:49 +0200107 if not session["admin"]:
108 raise EngineException("needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED)
delacruzramoc061f562019-04-05 11:00:02 +0200109 # Names that look like UUIDs are not allowed
110 name = (indata if indata else kwargs).get("username")
111 if is_valid_uuid(name):
112 raise EngineException("Usernames that look like UUIDs are not allowed",
113 http_code=HTTPStatus.UNPROCESSABLE_ENTITY)
tierno65ca36d2019-02-12 19:27:52 +0100114 return BaseTopic.edit(self, session, _id, indata=indata, kwargs=kwargs, content=content)
tiernob24258a2018-10-04 18:39:49 +0200115
tierno65ca36d2019-02-12 19:27:52 +0100116 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +0200117 if not session["admin"]:
118 raise EngineException("needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED)
delacruzramoc061f562019-04-05 11:00:02 +0200119 # Names that look like UUIDs are not allowed
120 name = indata["username"] if indata else kwargs["username"]
121 if is_valid_uuid(name):
122 raise EngineException("Usernames that look like UUIDs are not allowed",
123 http_code=HTTPStatus.UNPROCESSABLE_ENTITY)
tierno65ca36d2019-02-12 19:27:52 +0100124 return BaseTopic.new(self, rollback, session, indata=indata, kwargs=kwargs, headers=headers)
tiernob24258a2018-10-04 18:39:49 +0200125
126
127class ProjectTopic(BaseTopic):
128 topic = "projects"
129 topic_msg = "projects"
130 schema_new = project_new_schema
131 schema_edit = project_edit_schema
tierno65ca36d2019-02-12 19:27:52 +0100132 multiproject = False
tiernob24258a2018-10-04 18:39:49 +0200133
delacruzramo32bab472019-09-13 12:24:22 +0200134 def __init__(self, db, fs, msg, auth):
135 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +0200136
tierno65ca36d2019-02-12 19:27:52 +0100137 @staticmethod
138 def _get_project_filter(session):
139 """
140 Generates a filter dictionary for querying database users.
141 Current policy is admin can show all, non admin, only its own user.
142 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
143 :return:
144 """
145 if session["admin"]: # allows all
146 return {}
147 else:
148 return {"_id.cont": session["project_id"]}
149
150 def check_conflict_on_new(self, session, indata):
tiernob24258a2018-10-04 18:39:49 +0200151 if not indata.get("name"):
152 raise EngineException("missing 'name'")
153 # check name not exists
154 if self.db.get_one(self.topic, {"name": indata.get("name")}, fail_on_empty=False, fail_on_more=False):
155 raise EngineException("name '{}' exists".format(indata["name"]), HTTPStatus.CONFLICT)
156
157 @staticmethod
158 def format_on_new(content, project_id=None, make_public=False):
159 BaseTopic.format_on_new(content, None)
delacruzramoc061f562019-04-05 11:00:02 +0200160 # Removed so that the UUID is kept, to allow Project Name modification
161 # content["_id"] = content["name"]
tiernob24258a2018-10-04 18:39:49 +0200162
tiernob4844ab2019-05-23 08:42:12 +0000163 def check_conflict_on_del(self, session, _id, db_content):
164 """
165 Check if deletion can be done because of dependencies if it is not force. To override
166 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
167 :param _id: internal _id
168 :param db_content: The database content of this item _id
169 :return: None if ok or raises EngineException with the conflict
170 """
tierno65ca36d2019-02-12 19:27:52 +0100171 if _id in session["project_id"]:
tiernob24258a2018-10-04 18:39:49 +0200172 raise EngineException("You cannot delete your own project", http_code=HTTPStatus.CONFLICT)
tierno65ca36d2019-02-12 19:27:52 +0100173 if session["force"]:
tiernob24258a2018-10-04 18:39:49 +0200174 return
175 _filter = {"projects": _id}
176 if self.db.get_list("users", _filter):
177 raise EngineException("There is some USER that contains this project", http_code=HTTPStatus.CONFLICT)
178
tierno65ca36d2019-02-12 19:27:52 +0100179 def edit(self, session, _id, indata=None, kwargs=None, content=None):
tiernob24258a2018-10-04 18:39:49 +0200180 if not session["admin"]:
181 raise EngineException("needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED)
delacruzramoc061f562019-04-05 11:00:02 +0200182 # Names that look like UUIDs are not allowed
183 name = (indata if indata else kwargs).get("name")
184 if is_valid_uuid(name):
185 raise EngineException("Project names that look like UUIDs are not allowed",
186 http_code=HTTPStatus.UNPROCESSABLE_ENTITY)
tierno65ca36d2019-02-12 19:27:52 +0100187 return BaseTopic.edit(self, session, _id, indata=indata, kwargs=kwargs, content=content)
tiernob24258a2018-10-04 18:39:49 +0200188
tierno65ca36d2019-02-12 19:27:52 +0100189 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +0200190 if not session["admin"]:
191 raise EngineException("needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED)
delacruzramoc061f562019-04-05 11:00:02 +0200192 # Names that look like UUIDs are not allowed
193 name = indata["name"] if indata else kwargs["name"]
194 if is_valid_uuid(name):
195 raise EngineException("Project names that look like UUIDs are not allowed",
196 http_code=HTTPStatus.UNPROCESSABLE_ENTITY)
tierno65ca36d2019-02-12 19:27:52 +0100197 return BaseTopic.new(self, rollback, session, indata=indata, kwargs=kwargs, headers=headers)
tiernob24258a2018-10-04 18:39:49 +0200198
199
tiernobdebce92019-07-01 15:36:49 +0000200class CommonVimWimSdn(BaseTopic):
201 """Common class for VIM, WIM SDN just to unify methods that are equal to all of them"""
tierno468aa242019-08-01 16:35:04 +0000202 config_to_encrypt = {} # what keys at config must be encrypted because contains passwords
tiernobdebce92019-07-01 15:36:49 +0000203 password_to_encrypt = "" # key that contains a password
tiernob24258a2018-10-04 18:39:49 +0200204
tiernobdebce92019-07-01 15:36:49 +0000205 @staticmethod
206 def _create_operation(op_type, params=None):
207 """
208 Creates a dictionary with the information to an operation, similar to ns-lcm-op
209 :param op_type: can be create, edit, delete
210 :param params: operation input parameters
211 :return: new dictionary with
212 """
213 now = time()
214 return {
215 "lcmOperationType": op_type,
216 "operationState": "PROCESSING",
217 "startTime": now,
218 "statusEnteredTime": now,
219 "detailed-status": "",
220 "operationParams": params,
221 }
tiernob24258a2018-10-04 18:39:49 +0200222
tierno65ca36d2019-02-12 19:27:52 +0100223 def check_conflict_on_new(self, session, indata):
tiernobdebce92019-07-01 15:36:49 +0000224 """
225 Check that the data to be inserted is valid. It is checked that name is unique
226 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
227 :param indata: data to be inserted
228 :return: None or raises EngineException
229 """
tiernob24258a2018-10-04 18:39:49 +0200230 self.check_unique_name(session, indata["name"], _id=None)
231
tierno65ca36d2019-02-12 19:27:52 +0100232 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
tiernobdebce92019-07-01 15:36:49 +0000233 """
234 Check that the data to be edited/uploaded is valid. It is checked that name is unique
235 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
236 :param final_content: data once modified. This method may change it.
237 :param edit_content: incremental data that contains the modifications to apply
238 :param _id: internal _id
239 :return: None or raises EngineException
240 """
tierno65ca36d2019-02-12 19:27:52 +0100241 if not session["force"] and edit_content.get("name"):
tiernob24258a2018-10-04 18:39:49 +0200242 self.check_unique_name(session, edit_content["name"], _id=_id)
243
tiernobdebce92019-07-01 15:36:49 +0000244 def format_on_edit(self, final_content, edit_content):
245 """
246 Modifies final_content inserting admin information upon edition
247 :param final_content: final content to be stored at database
248 :param edit_content: user requested update content
249 :return: operation id
250 """
delacruzramofe598fe2019-10-23 18:25:11 +0200251 super().format_on_edit(final_content, edit_content)
tiernobdebce92019-07-01 15:36:49 +0000252
tierno92c1c7d2018-11-12 15:22:37 +0100253 # encrypt passwords
254 schema_version = final_content.get("schema_version")
255 if schema_version:
tiernobdebce92019-07-01 15:36:49 +0000256 if edit_content.get(self.password_to_encrypt):
257 final_content[self.password_to_encrypt] = self.db.encrypt(edit_content[self.password_to_encrypt],
258 schema_version=schema_version,
259 salt=final_content["_id"])
tierno468aa242019-08-01 16:35:04 +0000260 config_to_encrypt_keys = self.config_to_encrypt.get(schema_version) or self.config_to_encrypt.get("default")
261 if edit_content.get("config") and config_to_encrypt_keys:
262
263 for p in config_to_encrypt_keys:
tierno92c1c7d2018-11-12 15:22:37 +0100264 if edit_content["config"].get(p):
265 final_content["config"][p] = self.db.encrypt(edit_content["config"][p],
tiernobdebce92019-07-01 15:36:49 +0000266 schema_version=schema_version,
267 salt=final_content["_id"])
268
269 # create edit operation
270 final_content["_admin"]["operations"].append(self._create_operation("edit"))
271 return "{}:{}".format(final_content["_id"], len(final_content["_admin"]["operations"]) - 1)
tierno92c1c7d2018-11-12 15:22:37 +0100272
273 def format_on_new(self, content, project_id=None, make_public=False):
tiernobdebce92019-07-01 15:36:49 +0000274 """
275 Modifies content descriptor to include _admin and insert create operation
276 :param content: descriptor to be modified
277 :param project_id: if included, it add project read/write permissions. Can be None or a list
278 :param make_public: if included it is generated as public for reading.
279 :return: op_id: operation id on asynchronous operation, None otherwise. In addition content is modified
280 """
281 super().format_on_new(content, project_id=project_id, make_public=make_public)
tierno468aa242019-08-01 16:35:04 +0000282 content["schema_version"] = schema_version = "1.11"
tierno92c1c7d2018-11-12 15:22:37 +0100283
284 # encrypt passwords
tiernobdebce92019-07-01 15:36:49 +0000285 if content.get(self.password_to_encrypt):
286 content[self.password_to_encrypt] = self.db.encrypt(content[self.password_to_encrypt],
287 schema_version=schema_version,
288 salt=content["_id"])
tierno468aa242019-08-01 16:35:04 +0000289 config_to_encrypt_keys = self.config_to_encrypt.get(schema_version) or self.config_to_encrypt.get("default")
290 if content.get("config") and config_to_encrypt_keys:
291 for p in config_to_encrypt_keys:
tierno92c1c7d2018-11-12 15:22:37 +0100292 if content["config"].get(p):
tiernobdebce92019-07-01 15:36:49 +0000293 content["config"][p] = self.db.encrypt(content["config"][p],
294 schema_version=schema_version,
tierno92c1c7d2018-11-12 15:22:37 +0100295 salt=content["_id"])
296
tiernob24258a2018-10-04 18:39:49 +0200297 content["_admin"]["operationalState"] = "PROCESSING"
298
tiernobdebce92019-07-01 15:36:49 +0000299 # create operation
300 content["_admin"]["operations"] = [self._create_operation("create")]
301 content["_admin"]["current_operation"] = None
302
303 return "{}:0".format(content["_id"])
304
tierno65ca36d2019-02-12 19:27:52 +0100305 def delete(self, session, _id, dry_run=False):
tiernob24258a2018-10-04 18:39:49 +0200306 """
307 Delete item by its internal _id
tierno65ca36d2019-02-12 19:27:52 +0100308 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +0200309 :param _id: server internal id
tiernob24258a2018-10-04 18:39:49 +0200310 :param dry_run: make checking but do not delete
tiernobdebce92019-07-01 15:36:49 +0000311 :return: operation id if it is ordered to delete. None otherwise
tiernob24258a2018-10-04 18:39:49 +0200312 """
tiernobdebce92019-07-01 15:36:49 +0000313
314 filter_q = self._get_project_filter(session)
315 filter_q["_id"] = _id
316 db_content = self.db.get_one(self.topic, filter_q)
317
318 self.check_conflict_on_del(session, _id, db_content)
319 if dry_run:
320 return None
321
322 # remove reference from project_read. If not last delete
323 if session["project_id"]:
324 for project_id in session["project_id"]:
325 if project_id in db_content["_admin"]["projects_read"]:
326 db_content["_admin"]["projects_read"].remove(project_id)
327 if project_id in db_content["_admin"]["projects_write"]:
328 db_content["_admin"]["projects_write"].remove(project_id)
329 else:
330 db_content["_admin"]["projects_read"].clear()
331 db_content["_admin"]["projects_write"].clear()
332
333 update_dict = {"_admin.projects_read": db_content["_admin"]["projects_read"],
334 "_admin.projects_write": db_content["_admin"]["projects_write"]
335 }
336
337 # check if there are projects referencing it (apart from ANY that means public)....
338 if db_content["_admin"]["projects_read"] and (len(db_content["_admin"]["projects_read"]) > 1 or
339 db_content["_admin"]["projects_read"][0] != "ANY"):
340 self.db.set_one(self.topic, filter_q, update_dict=update_dict) # remove references but not delete
341 return None
342
343 # It must be deleted
344 if session["force"]:
345 self.db.del_one(self.topic, {"_id": _id})
346 op_id = None
347 self._send_msg("deleted", {"_id": _id, "op_id": op_id})
348 else:
349 update_dict["_admin.to_delete"] = True
350 self.db.set_one(self.topic, {"_id": _id},
351 update_dict=update_dict,
352 push={"_admin.operations": self._create_operation("delete")}
353 )
354 # the number of operations is the operation_id. db_content does not contains the new operation inserted,
355 # so the -1 is not needed
356 op_id = "{}:{}".format(db_content["_id"], len(db_content["_admin"]["operations"]))
357 self._send_msg("delete", {"_id": _id, "op_id": op_id})
358 return op_id
tiernob24258a2018-10-04 18:39:49 +0200359
360
tiernobdebce92019-07-01 15:36:49 +0000361class VimAccountTopic(CommonVimWimSdn):
362 topic = "vim_accounts"
363 topic_msg = "vim_account"
364 schema_new = vim_account_new_schema
365 schema_edit = vim_account_edit_schema
366 multiproject = True
367 password_to_encrypt = "vim_password"
tierno468aa242019-08-01 16:35:04 +0000368 config_to_encrypt = {"1.1": ("admin_password", "nsx_password", "vcenter_password"),
369 "default": ("admin_password", "nsx_password", "vcenter_password", "vrops_password")}
tiernobdebce92019-07-01 15:36:49 +0000370
371
372class WimAccountTopic(CommonVimWimSdn):
tierno55ba2e62018-12-11 17:22:22 +0000373 topic = "wim_accounts"
374 topic_msg = "wim_account"
375 schema_new = wim_account_new_schema
376 schema_edit = wim_account_edit_schema
tierno65ca36d2019-02-12 19:27:52 +0100377 multiproject = True
tiernobdebce92019-07-01 15:36:49 +0000378 password_to_encrypt = "wim_password"
tierno468aa242019-08-01 16:35:04 +0000379 config_to_encrypt = {}
tierno55ba2e62018-12-11 17:22:22 +0000380
381
tiernobdebce92019-07-01 15:36:49 +0000382class SdnTopic(CommonVimWimSdn):
tiernob24258a2018-10-04 18:39:49 +0200383 topic = "sdns"
384 topic_msg = "sdn"
385 schema_new = sdn_new_schema
386 schema_edit = sdn_edit_schema
tierno65ca36d2019-02-12 19:27:52 +0100387 multiproject = True
tiernobdebce92019-07-01 15:36:49 +0000388 password_to_encrypt = "password"
tierno468aa242019-08-01 16:35:04 +0000389 config_to_encrypt = {}
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100390
391
delacruzramofe598fe2019-10-23 18:25:11 +0200392class K8sClusterTopic(CommonVimWimSdn):
393 topic = "k8sclusters"
394 topic_msg = "k8scluster"
395 schema_new = k8scluster_new_schema
396 schema_edit = k8scluster_edit_schema
397 multiproject = True
398 password_to_encrypt = None
399 config_to_encrypt = {}
400
401 def format_on_new(self, content, project_id=None, make_public=False):
402 oid = super().format_on_new(content, project_id, make_public)
403 self.db.encrypt_decrypt_fields(content["credentials"], 'encrypt', ['password', 'secret'],
404 schema_version=content["schema_version"], salt=content["_id"])
405 return oid
406
407 def format_on_edit(self, final_content, edit_content):
408 if final_content.get("schema_version") and edit_content.get("credentials"):
409 self.db.encrypt_decrypt_fields(edit_content["credentials"], 'encrypt', ['password', 'secret'],
410 schema_version=final_content["schema_version"], salt=final_content["_id"])
411 deep_update_rfc7396(final_content["credentials"], edit_content["credentials"])
412 oid = super().format_on_edit(final_content, edit_content)
413 return oid
414
415
416class K8sRepoTopic(CommonVimWimSdn):
417 topic = "k8srepos"
418 topic_msg = "k8srepo"
419 schema_new = k8srepo_new_schema
420 schema_edit = k8srepo_edit_schema
421 multiproject = True
422 password_to_encrypt = None
423 config_to_encrypt = {}
424
425
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100426class UserTopicAuth(UserTopic):
tierno65ca36d2019-02-12 19:27:52 +0100427 # topic = "users"
428 # topic_msg = "users"
Eduardo Sousaa16a4fa2019-05-23 01:41:18 +0100429 schema_new = user_new_schema
430 schema_edit = user_edit_schema
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100431
432 def __init__(self, db, fs, msg, auth):
delacruzramo32bab472019-09-13 12:24:22 +0200433 UserTopic.__init__(self, db, fs, msg, auth)
434 # self.auth = auth
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100435
tierno65ca36d2019-02-12 19:27:52 +0100436 def check_conflict_on_new(self, session, indata):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100437 """
438 Check that the data to be inserted is valid
439
tierno65ca36d2019-02-12 19:27:52 +0100440 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100441 :param indata: data to be inserted
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100442 :return: None or raises EngineException
443 """
444 username = indata.get("username")
tiernocf042d32019-06-13 09:06:40 +0000445 if is_valid_uuid(username):
delacruzramoceb8baf2019-06-21 14:25:38 +0200446 raise EngineException("username '{}' cannot have a uuid format".format(username),
tiernocf042d32019-06-13 09:06:40 +0000447 HTTPStatus.UNPROCESSABLE_ENTITY)
448
449 # Check that username is not used, regardless keystone already checks this
450 if self.auth.get_user_list(filter_q={"name": username}):
451 raise EngineException("username '{}' is already used".format(username), HTTPStatus.CONFLICT)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100452
Eduardo Sousa339ed782019-05-28 14:25:00 +0100453 if "projects" in indata.keys():
tierno701018c2019-06-25 11:13:14 +0000454 # convert to new format project_role_mappings
delacruzramo01b15d32019-07-02 14:37:47 +0200455 role = self.auth.get_role_list({"name": "project_admin"})
456 if not role:
457 role = self.auth.get_role_list()
458 if not role:
459 raise AuthconnNotFoundException("Can't find default role for user '{}'".format(username))
460 rid = role[0]["_id"]
tierno701018c2019-06-25 11:13:14 +0000461 if not indata.get("project_role_mappings"):
462 indata["project_role_mappings"] = []
463 for project in indata["projects"]:
delacruzramo01b15d32019-07-02 14:37:47 +0200464 pid = self.auth.get_project(project)["_id"]
465 prm = {"project": pid, "role": rid}
466 if prm not in indata["project_role_mappings"]:
467 indata["project_role_mappings"].append(prm)
tierno701018c2019-06-25 11:13:14 +0000468 # raise EngineException("Format invalid: the keyword 'projects' is not allowed for keystone authentication",
469 # HTTPStatus.BAD_REQUEST)
Eduardo Sousa339ed782019-05-28 14:25:00 +0100470
tierno65ca36d2019-02-12 19:27:52 +0100471 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100472 """
473 Check that the data to be edited/uploaded is valid
474
tierno65ca36d2019-02-12 19:27:52 +0100475 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100476 :param final_content: data once modified
477 :param edit_content: incremental data that contains the modifications to apply
478 :param _id: internal _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100479 :return: None or raises EngineException
480 """
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100481
tiernocf042d32019-06-13 09:06:40 +0000482 if "username" in edit_content:
483 username = edit_content.get("username")
484 if is_valid_uuid(username):
delacruzramoceb8baf2019-06-21 14:25:38 +0200485 raise EngineException("username '{}' cannot have an uuid format".format(username),
tiernocf042d32019-06-13 09:06:40 +0000486 HTTPStatus.UNPROCESSABLE_ENTITY)
487
488 # Check that username is not used, regardless keystone already checks this
489 if self.auth.get_user_list(filter_q={"name": username}):
490 raise EngineException("username '{}' is already used".format(username), HTTPStatus.CONFLICT)
491
492 if final_content["username"] == "admin":
493 for mapping in edit_content.get("remove_project_role_mappings", ()):
494 if mapping["project"] == "admin" and mapping.get("role") in (None, "system_admin"):
495 # TODO make this also available for project id and role id
496 raise EngineException("You cannot remove system_admin role from admin user",
497 http_code=HTTPStatus.FORBIDDEN)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100498
tiernob4844ab2019-05-23 08:42:12 +0000499 def check_conflict_on_del(self, session, _id, db_content):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100500 """
501 Check if deletion can be done because of dependencies if it is not force. To override
tierno65ca36d2019-02-12 19:27:52 +0100502 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100503 :param _id: internal _id
tiernob4844ab2019-05-23 08:42:12 +0000504 :param db_content: The database content of this item _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100505 :return: None if ok or raises EngineException with the conflict
506 """
tiernocf042d32019-06-13 09:06:40 +0000507 if db_content["username"] == session["username"]:
508 raise EngineException("You cannot delete your own login user ", http_code=HTTPStatus.CONFLICT)
delacruzramo01b15d32019-07-02 14:37:47 +0200509 # TODO: Check that user is not logged in ? How? (Would require listing current tokens)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100510
Eduardo Sousaa16a4fa2019-05-23 01:41:18 +0100511 @staticmethod
512 def format_on_show(content):
513 """
Eduardo Sousa44603902019-06-04 08:10:32 +0100514 Modifies the content of the role information to separate the role
Eduardo Sousaa16a4fa2019-05-23 01:41:18 +0100515 metadata from the role definition.
516 """
517 project_role_mappings = []
518
delacruzramo01b15d32019-07-02 14:37:47 +0200519 if "projects" in content:
520 for project in content["projects"]:
521 for role in project["roles"]:
522 project_role_mappings.append({"project": project["_id"],
523 "project_name": project["name"],
524 "role": role["_id"],
525 "role_name": role["name"]})
526 del content["projects"]
Eduardo Sousaa16a4fa2019-05-23 01:41:18 +0100527 content["project_role_mappings"] = project_role_mappings
528
Eduardo Sousa0b1d61b2019-05-30 19:55:52 +0100529 return content
530
tierno65ca36d2019-02-12 19:27:52 +0100531 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100532 """
533 Creates a new entry into the authentication backend.
534
535 NOTE: Overrides BaseTopic functionality because it doesn't require access to database.
536
537 :param rollback: list to append created items at database in case a rollback may to be done
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 indata: data to be inserted
540 :param kwargs: used to override the indata descriptor
541 :param headers: http request headers
delacruzramo01b15d32019-07-02 14:37:47 +0200542 :return: _id: identity of the inserted data, operation _id (None)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100543 """
544 try:
545 content = BaseTopic._remove_envelop(indata)
546
547 # Override descriptor with query string kwargs
548 BaseTopic._update_input_with_kwargs(content, kwargs)
tierno65ca36d2019-02-12 19:27:52 +0100549 content = self._validate_input_new(content, session["force"])
550 self.check_conflict_on_new(session, content)
tiernocf042d32019-06-13 09:06:40 +0000551 # self.format_on_new(content, session["project_id"], make_public=session["public"])
delacruzramo01b15d32019-07-02 14:37:47 +0200552 now = time()
553 content["_admin"] = {"created": now, "modified": now}
554 prms = []
555 for prm in content.get("project_role_mappings", []):
556 proj = self.auth.get_project(prm["project"], not session["force"])
557 role = self.auth.get_role(prm["role"], not session["force"])
558 pid = proj["_id"] if proj else None
559 rid = role["_id"] if role else None
560 prl = {"project": pid, "role": rid}
561 if prl not in prms:
562 prms.append(prl)
563 content["project_role_mappings"] = prms
564 # _id = self.auth.create_user(content["username"], content["password"])["_id"]
565 _id = self.auth.create_user(content)["_id"]
Eduardo Sousa44603902019-06-04 08:10:32 +0100566
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100567 rollback.append({"topic": self.topic, "_id": _id})
tiernocf042d32019-06-13 09:06:40 +0000568 # del content["password"]
tierno15a1f682019-10-16 09:00:13 +0000569 # self._send_msg("created", content)
delacruzramo01b15d32019-07-02 14:37:47 +0200570 return _id, None
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100571 except ValidationError as e:
572 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
573
574 def show(self, session, _id):
575 """
576 Get complete information on an topic
577
tierno65ca36d2019-02-12 19:27:52 +0100578 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100579 :param _id: server internal id
580 :return: dictionary, raise exception if not found.
581 """
tiernocf042d32019-06-13 09:06:40 +0000582 # Allow _id to be a name or uuid
583 filter_q = {self.id_field(self.topic, _id): _id}
delacruzramo029405d2019-09-26 10:52:56 +0200584 # users = self.auth.get_user_list(filter_q)
585 users = self.list(session, filter_q) # To allow default filtering (Bug 853)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100586 if len(users) == 1:
tierno1546f2a2019-08-20 15:38:11 +0000587 return users[0]
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100588 elif len(users) > 1:
589 raise EngineException("Too many users found", HTTPStatus.CONFLICT)
590 else:
591 raise EngineException("User not found", HTTPStatus.NOT_FOUND)
592
tierno65ca36d2019-02-12 19:27:52 +0100593 def edit(self, session, _id, indata=None, kwargs=None, content=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100594 """
595 Updates an user entry.
596
tierno65ca36d2019-02-12 19:27:52 +0100597 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100598 :param _id:
599 :param indata: data to be inserted
600 :param kwargs: used to override the indata descriptor
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100601 :param content:
602 :return: _id: identity of the inserted data.
603 """
604 indata = self._remove_envelop(indata)
605
606 # Override descriptor with query string kwargs
607 if kwargs:
608 BaseTopic._update_input_with_kwargs(indata, kwargs)
609 try:
tierno65ca36d2019-02-12 19:27:52 +0100610 indata = self._validate_input_edit(indata, force=session["force"])
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100611
612 if not content:
613 content = self.show(session, _id)
tierno65ca36d2019-02-12 19:27:52 +0100614 self.check_conflict_on_edit(session, content, indata, _id=_id)
tiernocf042d32019-06-13 09:06:40 +0000615 # self.format_on_edit(content, indata)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100616
delacruzramo01b15d32019-07-02 14:37:47 +0200617 if not ("password" in indata or "username" in indata or indata.get("remove_project_role_mappings") or
618 indata.get("add_project_role_mappings") or indata.get("project_role_mappings") or
619 indata.get("projects") or indata.get("add_projects")):
tiernocf042d32019-06-13 09:06:40 +0000620 return _id
delacruzramo01b15d32019-07-02 14:37:47 +0200621 if indata.get("project_role_mappings") \
622 and (indata.get("remove_project_role_mappings") or indata.get("add_project_role_mappings")):
tiernocf042d32019-06-13 09:06:40 +0000623 raise EngineException("Option 'project_role_mappings' is incompatible with 'add_project_role_mappings"
624 "' or 'remove_project_role_mappings'", http_code=HTTPStatus.BAD_REQUEST)
Eduardo Sousa44603902019-06-04 08:10:32 +0100625
delacruzramo01b15d32019-07-02 14:37:47 +0200626 if indata.get("projects") or indata.get("add_projects"):
627 role = self.auth.get_role_list({"name": "project_admin"})
628 if not role:
629 role = self.auth.get_role_list()
630 if not role:
631 raise AuthconnNotFoundException("Can't find a default role for user '{}'"
632 .format(content["username"]))
633 rid = role[0]["_id"]
634 if "add_project_role_mappings" not in indata:
635 indata["add_project_role_mappings"] = []
tierno1546f2a2019-08-20 15:38:11 +0000636 if "remove_project_role_mappings" not in indata:
637 indata["remove_project_role_mappings"] = []
638 if isinstance(indata.get("projects"), dict):
639 # backward compatible
640 for k, v in indata["projects"].items():
641 if k.startswith("$") and v is None:
642 indata["remove_project_role_mappings"].append({"project": k[1:]})
643 elif k.startswith("$+"):
644 indata["add_project_role_mappings"].append({"project": v, "role": rid})
645 del indata["projects"]
delacruzramo01b15d32019-07-02 14:37:47 +0200646 for proj in indata.get("projects", []) + indata.get("add_projects", []):
647 indata["add_project_role_mappings"].append({"project": proj, "role": rid})
648
649 # user = self.show(session, _id) # Already in 'content'
650 original_mapping = content["project_role_mappings"]
Eduardo Sousa44603902019-06-04 08:10:32 +0100651
tiernocf042d32019-06-13 09:06:40 +0000652 mappings_to_add = []
653 mappings_to_remove = []
Eduardo Sousa44603902019-06-04 08:10:32 +0100654
tiernocf042d32019-06-13 09:06:40 +0000655 # remove
656 for to_remove in indata.get("remove_project_role_mappings", ()):
657 for mapping in original_mapping:
658 if to_remove["project"] in (mapping["project"], mapping["project_name"]):
659 if not to_remove.get("role") or to_remove["role"] in (mapping["role"], mapping["role_name"]):
660 mappings_to_remove.append(mapping)
Eduardo Sousa44603902019-06-04 08:10:32 +0100661
tiernocf042d32019-06-13 09:06:40 +0000662 # add
663 for to_add in indata.get("add_project_role_mappings", ()):
664 for mapping in original_mapping:
665 if to_add["project"] in (mapping["project"], mapping["project_name"]) and \
666 to_add["role"] in (mapping["role"], mapping["role_name"]):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100667
tiernocf042d32019-06-13 09:06:40 +0000668 if mapping in mappings_to_remove: # do not remove
669 mappings_to_remove.remove(mapping)
670 break # do not add, it is already at user
671 else:
delacruzramo01b15d32019-07-02 14:37:47 +0200672 pid = self.auth.get_project(to_add["project"])["_id"]
673 rid = self.auth.get_role(to_add["role"])["_id"]
674 mappings_to_add.append({"project": pid, "role": rid})
tiernocf042d32019-06-13 09:06:40 +0000675
676 # set
677 if indata.get("project_role_mappings"):
678 for to_set in indata["project_role_mappings"]:
679 for mapping in original_mapping:
680 if to_set["project"] in (mapping["project"], mapping["project_name"]) and \
681 to_set["role"] in (mapping["role"], mapping["role_name"]):
tiernocf042d32019-06-13 09:06:40 +0000682 if mapping in mappings_to_remove: # do not remove
683 mappings_to_remove.remove(mapping)
684 break # do not add, it is already at user
685 else:
delacruzramo01b15d32019-07-02 14:37:47 +0200686 pid = self.auth.get_project(to_set["project"])["_id"]
687 rid = self.auth.get_role(to_set["role"])["_id"]
688 mappings_to_add.append({"project": pid, "role": rid})
tiernocf042d32019-06-13 09:06:40 +0000689 for mapping in original_mapping:
690 for to_set in indata["project_role_mappings"]:
691 if to_set["project"] in (mapping["project"], mapping["project_name"]) and \
692 to_set["role"] in (mapping["role"], mapping["role_name"]):
693 break
694 else:
695 # delete
696 if mapping not in mappings_to_remove: # do not remove
697 mappings_to_remove.append(mapping)
698
delacruzramo01b15d32019-07-02 14:37:47 +0200699 self.auth.update_user({"_id": _id, "username": indata.get("username"), "password": indata.get("password"),
700 "add_project_role_mappings": mappings_to_add,
701 "remove_project_role_mappings": mappings_to_remove
702 })
tiernocf042d32019-06-13 09:06:40 +0000703
delacruzramo01b15d32019-07-02 14:37:47 +0200704 # return _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100705 except ValidationError as e:
706 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
707
708 def list(self, session, filter_q=None):
709 """
710 Get a list of the topic that matches a filter
tierno65ca36d2019-02-12 19:27:52 +0100711 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100712 :param filter_q: filter of data to be applied
713 :return: The list, it can be empty if no one match the filter.
714 """
delacruzramo029405d2019-09-26 10:52:56 +0200715 user_list = self.auth.get_user_list(filter_q)
716 if not session["allow_show_user_project_role"]:
717 # Bug 853 - Default filtering
718 user_list = [usr for usr in user_list if usr["username"] == session["username"]]
719 return user_list
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100720
tierno65ca36d2019-02-12 19:27:52 +0100721 def delete(self, session, _id, dry_run=False):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100722 """
723 Delete item by its internal _id
724
tierno65ca36d2019-02-12 19:27:52 +0100725 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100726 :param _id: server internal id
727 :param force: indicates if deletion must be forced in case of conflict
728 :param dry_run: make checking but do not delete
729 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
730 """
tiernocf042d32019-06-13 09:06:40 +0000731 # Allow _id to be a name or uuid
delacruzramo01b15d32019-07-02 14:37:47 +0200732 user = self.auth.get_user(_id)
733 uid = user["_id"]
734 self.check_conflict_on_del(session, uid, user)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100735 if not dry_run:
delacruzramo01b15d32019-07-02 14:37:47 +0200736 v = self.auth.delete_user(uid)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100737 return v
738 return None
739
740
741class ProjectTopicAuth(ProjectTopic):
tierno65ca36d2019-02-12 19:27:52 +0100742 # topic = "projects"
743 # topic_msg = "projects"
Eduardo Sousa44603902019-06-04 08:10:32 +0100744 schema_new = project_new_schema
745 schema_edit = project_edit_schema
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100746
747 def __init__(self, db, fs, msg, auth):
delacruzramo32bab472019-09-13 12:24:22 +0200748 ProjectTopic.__init__(self, db, fs, msg, auth)
749 # self.auth = auth
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100750
tierno65ca36d2019-02-12 19:27:52 +0100751 def check_conflict_on_new(self, session, indata):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100752 """
753 Check that the data to be inserted is valid
754
tierno65ca36d2019-02-12 19:27:52 +0100755 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100756 :param indata: data to be inserted
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100757 :return: None or raises EngineException
758 """
tiernocf042d32019-06-13 09:06:40 +0000759 project_name = indata.get("name")
760 if is_valid_uuid(project_name):
delacruzramoceb8baf2019-06-21 14:25:38 +0200761 raise EngineException("project name '{}' cannot have an uuid format".format(project_name),
tiernocf042d32019-06-13 09:06:40 +0000762 HTTPStatus.UNPROCESSABLE_ENTITY)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100763
tiernocf042d32019-06-13 09:06:40 +0000764 project_list = self.auth.get_project_list(filter_q={"name": project_name})
765
766 if project_list:
767 raise EngineException("project '{}' exists".format(project_name), HTTPStatus.CONFLICT)
768
769 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
770 """
771 Check that the data to be edited/uploaded is valid
772
773 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
774 :param final_content: data once modified
775 :param edit_content: incremental data that contains the modifications to apply
776 :param _id: internal _id
777 :return: None or raises EngineException
778 """
779
780 project_name = edit_content.get("name")
delacruzramo01b15d32019-07-02 14:37:47 +0200781 if project_name != final_content["name"]: # It is a true renaming
tiernocf042d32019-06-13 09:06:40 +0000782 if is_valid_uuid(project_name):
delacruzramo01b15d32019-07-02 14:37:47 +0200783 raise EngineException("project name '{}' cannot have an uuid format".format(project_name),
tiernocf042d32019-06-13 09:06:40 +0000784 HTTPStatus.UNPROCESSABLE_ENTITY)
785
delacruzramo01b15d32019-07-02 14:37:47 +0200786 if final_content["name"] == "admin":
787 raise EngineException("You cannot rename project 'admin'", http_code=HTTPStatus.CONFLICT)
788
tiernocf042d32019-06-13 09:06:40 +0000789 # Check that project name is not used, regardless keystone already checks this
delacruzramo32bab472019-09-13 12:24:22 +0200790 if project_name and self.auth.get_project_list(filter_q={"name": project_name}):
tiernocf042d32019-06-13 09:06:40 +0000791 raise EngineException("project '{}' is already used".format(project_name), HTTPStatus.CONFLICT)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100792
tiernob4844ab2019-05-23 08:42:12 +0000793 def check_conflict_on_del(self, session, _id, db_content):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100794 """
795 Check if deletion can be done because of dependencies if it is not force. To override
796
tierno65ca36d2019-02-12 19:27:52 +0100797 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100798 :param _id: internal _id
tiernob4844ab2019-05-23 08:42:12 +0000799 :param db_content: The database content of this item _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100800 :return: None if ok or raises EngineException with the conflict
801 """
delacruzramo01b15d32019-07-02 14:37:47 +0200802
803 def check_rw_projects(topic, title, id_field):
804 for desc in self.db.get_list(topic):
805 if _id in desc["_admin"]["projects_read"] + desc["_admin"]["projects_write"]:
806 raise EngineException("Project '{}' ({}) is being used by {} '{}'"
807 .format(db_content["name"], _id, title, desc[id_field]), HTTPStatus.CONFLICT)
808
809 if _id in session["project_id"]:
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100810 raise EngineException("You cannot delete your own project", http_code=HTTPStatus.CONFLICT)
811
delacruzramo01b15d32019-07-02 14:37:47 +0200812 if db_content["name"] == "admin":
813 raise EngineException("You cannot delete project 'admin'", http_code=HTTPStatus.CONFLICT)
814
815 # If any user is using this project, raise CONFLICT exception
816 if not session["force"]:
817 for user in self.auth.get_user_list():
tierno1546f2a2019-08-20 15:38:11 +0000818 for prm in user.get("project_role_mappings"):
819 if prm["project"] == _id:
820 raise EngineException("Project '{}' ({}) is being used by user '{}'"
821 .format(db_content["name"], _id, user["username"]), HTTPStatus.CONFLICT)
delacruzramo01b15d32019-07-02 14:37:47 +0200822
823 # If any VNFD, NSD, NST, PDU, etc. is using this project, raise CONFLICT exception
824 if not session["force"]:
825 check_rw_projects("vnfds", "VNF Descriptor", "id")
826 check_rw_projects("nsds", "NS Descriptor", "id")
827 check_rw_projects("nsts", "NS Template", "id")
828 check_rw_projects("pdus", "PDU Descriptor", "name")
829
tierno65ca36d2019-02-12 19:27:52 +0100830 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100831 """
832 Creates a new entry into the authentication backend.
833
834 NOTE: Overrides BaseTopic functionality because it doesn't require access to database.
835
836 :param rollback: list to append created items at database in case a rollback may to be done
tierno65ca36d2019-02-12 19:27:52 +0100837 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100838 :param indata: data to be inserted
839 :param kwargs: used to override the indata descriptor
840 :param headers: http request headers
delacruzramo01b15d32019-07-02 14:37:47 +0200841 :return: _id: identity of the inserted data, operation _id (None)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100842 """
843 try:
844 content = BaseTopic._remove_envelop(indata)
845
846 # Override descriptor with query string kwargs
847 BaseTopic._update_input_with_kwargs(content, kwargs)
tierno65ca36d2019-02-12 19:27:52 +0100848 content = self._validate_input_new(content, session["force"])
849 self.check_conflict_on_new(session, content)
850 self.format_on_new(content, project_id=session["project_id"], make_public=session["public"])
delacruzramo01b15d32019-07-02 14:37:47 +0200851 _id = self.auth.create_project(content)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100852 rollback.append({"topic": self.topic, "_id": _id})
tierno15a1f682019-10-16 09:00:13 +0000853 # self._send_msg("created", content)
delacruzramo01b15d32019-07-02 14:37:47 +0200854 return _id, None
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100855 except ValidationError as e:
856 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
857
858 def show(self, session, _id):
859 """
860 Get complete information on an topic
861
tierno65ca36d2019-02-12 19:27:52 +0100862 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100863 :param _id: server internal id
864 :return: dictionary, raise exception if not found.
865 """
tiernocf042d32019-06-13 09:06:40 +0000866 # Allow _id to be a name or uuid
867 filter_q = {self.id_field(self.topic, _id): _id}
delacruzramo029405d2019-09-26 10:52:56 +0200868 # projects = self.auth.get_project_list(filter_q=filter_q)
869 projects = self.list(session, filter_q) # To allow default filtering (Bug 853)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100870 if len(projects) == 1:
871 return projects[0]
872 elif len(projects) > 1:
873 raise EngineException("Too many projects found", HTTPStatus.CONFLICT)
874 else:
875 raise EngineException("Project not found", HTTPStatus.NOT_FOUND)
876
877 def list(self, session, filter_q=None):
878 """
879 Get a list of the topic that matches a filter
880
tierno65ca36d2019-02-12 19:27:52 +0100881 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100882 :param filter_q: filter of data to be applied
883 :return: The list, it can be empty if no one match the filter.
884 """
delacruzramo029405d2019-09-26 10:52:56 +0200885 project_list = self.auth.get_project_list(filter_q)
886 if not session["allow_show_user_project_role"]:
887 # Bug 853 - Default filtering
888 user = self.auth.get_user(session["username"])
889 projects = [prm["project"] for prm in user["project_role_mappings"]]
890 project_list = [proj for proj in project_list if proj["_id"] in projects]
891 return project_list
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100892
tierno65ca36d2019-02-12 19:27:52 +0100893 def delete(self, session, _id, dry_run=False):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100894 """
895 Delete item by its internal _id
896
tierno65ca36d2019-02-12 19:27:52 +0100897 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100898 :param _id: server internal id
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100899 :param dry_run: make checking but do not delete
900 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
901 """
tiernocf042d32019-06-13 09:06:40 +0000902 # Allow _id to be a name or uuid
delacruzramo01b15d32019-07-02 14:37:47 +0200903 proj = self.auth.get_project(_id)
904 pid = proj["_id"]
905 self.check_conflict_on_del(session, pid, proj)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100906 if not dry_run:
delacruzramo01b15d32019-07-02 14:37:47 +0200907 v = self.auth.delete_project(pid)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100908 return v
909 return None
910
tierno4015b472019-06-10 13:57:29 +0000911 def edit(self, session, _id, indata=None, kwargs=None, content=None):
912 """
913 Updates a project entry.
914
915 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
916 :param _id:
917 :param indata: data to be inserted
918 :param kwargs: used to override the indata descriptor
919 :param content:
920 :return: _id: identity of the inserted data.
921 """
922 indata = self._remove_envelop(indata)
923
924 # Override descriptor with query string kwargs
925 if kwargs:
926 BaseTopic._update_input_with_kwargs(indata, kwargs)
927 try:
928 indata = self._validate_input_edit(indata, force=session["force"])
929
930 if not content:
931 content = self.show(session, _id)
932 self.check_conflict_on_edit(session, content, indata, _id=_id)
delacruzramo01b15d32019-07-02 14:37:47 +0200933 self.format_on_edit(content, indata)
tierno4015b472019-06-10 13:57:29 +0000934
delacruzramo32bab472019-09-13 12:24:22 +0200935 deep_update_rfc7396(content, indata)
delacruzramo01b15d32019-07-02 14:37:47 +0200936 self.auth.update_project(content["_id"], content)
tierno4015b472019-06-10 13:57:29 +0000937 except ValidationError as e:
938 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
939
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100940
941class RoleTopicAuth(BaseTopic):
delacruzramoceb8baf2019-06-21 14:25:38 +0200942 topic = "roles"
943 topic_msg = None # "roles"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100944 schema_new = roles_new_schema
945 schema_edit = roles_edit_schema
tierno65ca36d2019-02-12 19:27:52 +0100946 multiproject = False
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100947
948 def __init__(self, db, fs, msg, auth, ops):
delacruzramo32bab472019-09-13 12:24:22 +0200949 BaseTopic.__init__(self, db, fs, msg, auth)
950 # self.auth = auth
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100951 self.operations = ops
delacruzramo01b15d32019-07-02 14:37:47 +0200952 # self.topic = "roles_operations" if isinstance(auth, AuthconnKeystone) else "roles"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100953
954 @staticmethod
955 def validate_role_definition(operations, role_definitions):
956 """
957 Validates the role definition against the operations defined in
958 the resources to operations files.
959
960 :param operations: operations list
961 :param role_definitions: role definition to test
962 :return: None if ok, raises ValidationError exception on error
963 """
tierno1f029d82019-06-13 22:37:04 +0000964 if not role_definitions.get("permissions"):
965 return
966 ignore_fields = ["admin", "default"]
967 for role_def in role_definitions["permissions"].keys():
Eduardo Sousa37de0912019-05-23 02:17:22 +0100968 if role_def in ignore_fields:
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100969 continue
Eduardo Sousac7689372019-06-04 16:01:46 +0100970 if role_def[-1] == ":":
tierno1f029d82019-06-13 22:37:04 +0000971 raise ValidationError("Operation cannot end with ':'")
Eduardo Sousac5a18892019-06-06 14:51:23 +0100972
delacruzramoc061f562019-04-05 11:00:02 +0200973 role_def_matches = [op for op in operations if op.startswith(role_def)]
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100974
975 if len(role_def_matches) == 0:
tierno1f029d82019-06-13 22:37:04 +0000976 raise ValidationError("Invalid permission '{}'".format(role_def))
Eduardo Sousa37de0912019-05-23 02:17:22 +0100977
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100978 def _validate_input_new(self, input, force=False):
979 """
980 Validates input user content for a new entry.
981
982 :param input: user input content for the new topic
983 :param force: may be used for being more tolerant
984 :return: The same input content, or a changed version of it.
985 """
986 if self.schema_new:
987 validate_input(input, self.schema_new)
Eduardo Sousa37de0912019-05-23 02:17:22 +0100988 self.validate_role_definition(self.operations, input)
Eduardo Sousac4650362019-06-04 13:24:22 +0100989
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100990 return input
991
992 def _validate_input_edit(self, input, force=False):
993 """
994 Validates input user content for updating an entry.
995
996 :param input: user input content for the new topic
997 :param force: may be used for being more tolerant
998 :return: The same input content, or a changed version of it.
999 """
1000 if self.schema_edit:
1001 validate_input(input, self.schema_edit)
Eduardo Sousa37de0912019-05-23 02:17:22 +01001002 self.validate_role_definition(self.operations, input)
Eduardo Sousac4650362019-06-04 13:24:22 +01001003
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001004 return input
1005
tierno65ca36d2019-02-12 19:27:52 +01001006 def check_conflict_on_new(self, session, indata):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001007 """
1008 Check that the data to be inserted is valid
1009
tierno65ca36d2019-02-12 19:27:52 +01001010 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001011 :param indata: data to be inserted
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001012 :return: None or raises EngineException
1013 """
tierno1f029d82019-06-13 22:37:04 +00001014 # check name not exists
delacruzramo01b15d32019-07-02 14:37:47 +02001015 name = indata["name"]
1016 # if self.db.get_one(self.topic, {"name": indata.get("name")}, fail_on_empty=False, fail_on_more=False):
1017 if self.auth.get_role_list({"name": name}):
1018 raise EngineException("role name '{}' exists".format(name), HTTPStatus.CONFLICT)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001019
tierno65ca36d2019-02-12 19:27:52 +01001020 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001021 """
1022 Check that the data to be edited/uploaded is valid
1023
tierno65ca36d2019-02-12 19:27:52 +01001024 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001025 :param final_content: data once modified
1026 :param edit_content: incremental data that contains the modifications to apply
1027 :param _id: internal _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001028 :return: None or raises EngineException
1029 """
tierno1f029d82019-06-13 22:37:04 +00001030 if "default" not in final_content["permissions"]:
1031 final_content["permissions"]["default"] = False
1032 if "admin" not in final_content["permissions"]:
1033 final_content["permissions"]["admin"] = False
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001034
tierno1f029d82019-06-13 22:37:04 +00001035 # check name not exists
1036 if "name" in edit_content:
1037 role_name = edit_content["name"]
delacruzramo01b15d32019-07-02 14:37:47 +02001038 # if self.db.get_one(self.topic, {"name":role_name,"_id.ne":_id}, fail_on_empty=False, fail_on_more=False):
1039 roles = self.auth.get_role_list({"name": role_name})
1040 if roles and roles[0][BaseTopic.id_field("roles", _id)] != _id:
tierno1f029d82019-06-13 22:37:04 +00001041 raise EngineException("role name '{}' exists".format(role_name), HTTPStatus.CONFLICT)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001042
tiernob4844ab2019-05-23 08:42:12 +00001043 def check_conflict_on_del(self, session, _id, db_content):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001044 """
1045 Check if deletion can be done because of dependencies if it is not force. To override
1046
tierno65ca36d2019-02-12 19:27:52 +01001047 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001048 :param _id: internal _id
tiernob4844ab2019-05-23 08:42:12 +00001049 :param db_content: The database content of this item _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001050 :return: None if ok or raises EngineException with the conflict
1051 """
delacruzramo01b15d32019-07-02 14:37:47 +02001052 role = self.auth.get_role(_id)
1053 if role["name"] in ["system_admin", "project_admin"]:
1054 raise EngineException("You cannot delete role '{}'".format(role["name"]), http_code=HTTPStatus.FORBIDDEN)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001055
delacruzramo01b15d32019-07-02 14:37:47 +02001056 # If any user is using this role, raise CONFLICT exception
1057 for user in self.auth.get_user_list():
tierno1546f2a2019-08-20 15:38:11 +00001058 for prm in user.get("project_role_mappings"):
1059 if prm["role"] == _id:
1060 raise EngineException("Role '{}' ({}) is being used by user '{}'"
1061 .format(role["name"], _id, user["username"]), HTTPStatus.CONFLICT)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001062
1063 @staticmethod
delacruzramo01b15d32019-07-02 14:37:47 +02001064 def format_on_new(content, project_id=None, make_public=False): # TO BE REMOVED ?
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001065 """
1066 Modifies content descriptor to include _admin
1067
1068 :param content: descriptor to be modified
1069 :param project_id: if included, it add project read/write permissions
1070 :param make_public: if included it is generated as public for reading.
1071 :return: None, but content is modified
1072 """
1073 now = time()
1074 if "_admin" not in content:
1075 content["_admin"] = {}
1076 if not content["_admin"].get("created"):
1077 content["_admin"]["created"] = now
1078 content["_admin"]["modified"] = now
Eduardo Sousac4650362019-06-04 13:24:22 +01001079
tierno1f029d82019-06-13 22:37:04 +00001080 if "permissions" not in content:
1081 content["permissions"] = {}
Eduardo Sousac4650362019-06-04 13:24:22 +01001082
tierno1f029d82019-06-13 22:37:04 +00001083 if "default" not in content["permissions"]:
1084 content["permissions"]["default"] = False
1085 if "admin" not in content["permissions"]:
1086 content["permissions"]["admin"] = False
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001087
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001088 @staticmethod
1089 def format_on_edit(final_content, edit_content):
1090 """
1091 Modifies final_content descriptor to include the modified date.
1092
1093 :param final_content: final descriptor generated
1094 :param edit_content: alterations to be include
1095 :return: None, but final_content is modified
1096 """
delacruzramo01b15d32019-07-02 14:37:47 +02001097 if "_admin" in final_content:
1098 final_content["_admin"]["modified"] = time()
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001099
tierno1f029d82019-06-13 22:37:04 +00001100 if "permissions" not in final_content:
1101 final_content["permissions"] = {}
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001102
tierno1f029d82019-06-13 22:37:04 +00001103 if "default" not in final_content["permissions"]:
1104 final_content["permissions"]["default"] = False
1105 if "admin" not in final_content["permissions"]:
1106 final_content["permissions"]["admin"] = False
tiernobdebce92019-07-01 15:36:49 +00001107 return None
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001108
delacruzramo01b15d32019-07-02 14:37:47 +02001109 def show(self, session, _id):
1110 """
1111 Get complete information on an topic
Eduardo Sousac4650362019-06-04 13:24:22 +01001112
delacruzramo01b15d32019-07-02 14:37:47 +02001113 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1114 :param _id: server internal id
1115 :return: dictionary, raise exception if not found.
1116 """
1117 filter_q = {BaseTopic.id_field(self.topic, _id): _id}
delacruzramo029405d2019-09-26 10:52:56 +02001118 # roles = self.auth.get_role_list(filter_q)
1119 roles = self.list(session, filter_q) # To allow default filtering (Bug 853)
delacruzramo01b15d32019-07-02 14:37:47 +02001120 if not roles:
1121 raise AuthconnNotFoundException("Not found any role with filter {}".format(filter_q))
1122 elif len(roles) > 1:
1123 raise AuthconnConflictException("Found more than one role with filter {}".format(filter_q))
1124 return roles[0]
1125
1126 def list(self, session, filter_q=None):
1127 """
1128 Get a list of the topic that matches a filter
1129
1130 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1131 :param filter_q: filter of data to be applied
1132 :return: The list, it can be empty if no one match the filter.
1133 """
delacruzramo029405d2019-09-26 10:52:56 +02001134 role_list = self.auth.get_role_list(filter_q)
1135 if not session["allow_show_user_project_role"]:
1136 # Bug 853 - Default filtering
1137 user = self.auth.get_user(session["username"])
1138 roles = [prm["role"] for prm in user["project_role_mappings"]]
1139 role_list = [role for role in role_list if role["_id"] in roles]
1140 return role_list
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001141
tierno65ca36d2019-02-12 19:27:52 +01001142 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001143 """
1144 Creates a new entry into database.
1145
1146 :param rollback: list to append created items at database in case a rollback may to be done
tierno65ca36d2019-02-12 19:27:52 +01001147 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001148 :param indata: data to be inserted
1149 :param kwargs: used to override the indata descriptor
1150 :param headers: http request headers
delacruzramo01b15d32019-07-02 14:37:47 +02001151 :return: _id: identity of the inserted data, operation _id (None)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001152 """
1153 try:
tierno1f029d82019-06-13 22:37:04 +00001154 content = self._remove_envelop(indata)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001155
1156 # Override descriptor with query string kwargs
tierno1f029d82019-06-13 22:37:04 +00001157 self._update_input_with_kwargs(content, kwargs)
tierno65ca36d2019-02-12 19:27:52 +01001158 content = self._validate_input_new(content, session["force"])
1159 self.check_conflict_on_new(session, content)
1160 self.format_on_new(content, project_id=session["project_id"], make_public=session["public"])
delacruzramo01b15d32019-07-02 14:37:47 +02001161 # role_name = content["name"]
1162 rid = self.auth.create_role(content)
1163 content["_id"] = rid
1164 # _id = self.db.create(self.topic, content)
1165 rollback.append({"topic": self.topic, "_id": rid})
tierno15a1f682019-10-16 09:00:13 +00001166 # self._send_msg("created", content)
delacruzramo01b15d32019-07-02 14:37:47 +02001167 return rid, None
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001168 except ValidationError as e:
1169 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1170
tierno65ca36d2019-02-12 19:27:52 +01001171 def delete(self, session, _id, dry_run=False):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001172 """
1173 Delete item by its internal _id
1174
tierno65ca36d2019-02-12 19:27:52 +01001175 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001176 :param _id: server internal id
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001177 :param dry_run: make checking but do not delete
1178 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
1179 """
delacruzramo01b15d32019-07-02 14:37:47 +02001180 filter_q = {BaseTopic.id_field(self.topic, _id): _id}
1181 roles = self.auth.get_role_list(filter_q)
1182 if not roles:
1183 raise AuthconnNotFoundException("Not found any role with filter {}".format(filter_q))
1184 elif len(roles) > 1:
1185 raise AuthconnConflictException("Found more than one role with filter {}".format(filter_q))
1186 rid = roles[0]["_id"]
1187 self.check_conflict_on_del(session, rid, None)
delacruzramoceb8baf2019-06-21 14:25:38 +02001188 # filter_q = {"_id": _id}
delacruzramo01b15d32019-07-02 14:37:47 +02001189 # filter_q = {BaseTopic.id_field(self.topic, _id): _id} # To allow role addressing by name
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001190 if not dry_run:
delacruzramo01b15d32019-07-02 14:37:47 +02001191 v = self.auth.delete_role(rid)
1192 # v = self.db.del_one(self.topic, filter_q)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001193 return v
1194 return None
1195
tierno65ca36d2019-02-12 19:27:52 +01001196 def edit(self, session, _id, indata=None, kwargs=None, content=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001197 """
1198 Updates a role entry.
1199
tierno65ca36d2019-02-12 19:27:52 +01001200 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001201 :param _id:
1202 :param indata: data to be inserted
1203 :param kwargs: used to override the indata descriptor
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001204 :param content:
1205 :return: _id: identity of the inserted data.
1206 """
delacruzramo01b15d32019-07-02 14:37:47 +02001207 if kwargs:
1208 self._update_input_with_kwargs(indata, kwargs)
1209 try:
1210 indata = self._validate_input_edit(indata, force=session["force"])
1211 if not content:
1212 content = self.show(session, _id)
1213 deep_update_rfc7396(content, indata)
1214 self.check_conflict_on_edit(session, content, indata, _id=_id)
1215 self.format_on_edit(content, indata)
1216 self.auth.update_role(content)
1217 except ValidationError as e:
1218 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)