blob: 670629eb68f844ed507240b82a65271fe5fd9e93 [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
tiernobee3bad2019-12-05 12:26:01 +0000305 def delete(self, session, _id, dry_run=False, not_send_msg=None):
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
tiernobee3bad2019-12-05 12:26:01 +0000311 :param not_send_msg: To not send message (False) or store content (list) instead
tiernobdebce92019-07-01 15:36:49 +0000312 :return: operation id if it is ordered to delete. None otherwise
tiernob24258a2018-10-04 18:39:49 +0200313 """
tiernobdebce92019-07-01 15:36:49 +0000314
315 filter_q = self._get_project_filter(session)
316 filter_q["_id"] = _id
317 db_content = self.db.get_one(self.topic, filter_q)
318
319 self.check_conflict_on_del(session, _id, db_content)
320 if dry_run:
321 return None
322
323 # remove reference from project_read. If not last delete
324 if session["project_id"]:
325 for project_id in session["project_id"]:
326 if project_id in db_content["_admin"]["projects_read"]:
327 db_content["_admin"]["projects_read"].remove(project_id)
328 if project_id in db_content["_admin"]["projects_write"]:
329 db_content["_admin"]["projects_write"].remove(project_id)
330 else:
331 db_content["_admin"]["projects_read"].clear()
332 db_content["_admin"]["projects_write"].clear()
333
334 update_dict = {"_admin.projects_read": db_content["_admin"]["projects_read"],
335 "_admin.projects_write": db_content["_admin"]["projects_write"]
336 }
337
338 # check if there are projects referencing it (apart from ANY that means public)....
339 if db_content["_admin"]["projects_read"] and (len(db_content["_admin"]["projects_read"]) > 1 or
340 db_content["_admin"]["projects_read"][0] != "ANY"):
341 self.db.set_one(self.topic, filter_q, update_dict=update_dict) # remove references but not delete
342 return None
343
344 # It must be deleted
345 if session["force"]:
346 self.db.del_one(self.topic, {"_id": _id})
347 op_id = None
tiernobee3bad2019-12-05 12:26:01 +0000348 self._send_msg("deleted", {"_id": _id, "op_id": op_id}, not_send_msg=not_send_msg)
tiernobdebce92019-07-01 15:36:49 +0000349 else:
350 update_dict["_admin.to_delete"] = True
351 self.db.set_one(self.topic, {"_id": _id},
352 update_dict=update_dict,
353 push={"_admin.operations": self._create_operation("delete")}
354 )
355 # the number of operations is the operation_id. db_content does not contains the new operation inserted,
356 # so the -1 is not needed
357 op_id = "{}:{}".format(db_content["_id"], len(db_content["_admin"]["operations"]))
tiernobee3bad2019-12-05 12:26:01 +0000358 self._send_msg("delete", {"_id": _id, "op_id": op_id}, not_send_msg=not_send_msg)
tiernobdebce92019-07-01 15:36:49 +0000359 return op_id
tiernob24258a2018-10-04 18:39:49 +0200360
361
tiernobdebce92019-07-01 15:36:49 +0000362class VimAccountTopic(CommonVimWimSdn):
363 topic = "vim_accounts"
364 topic_msg = "vim_account"
365 schema_new = vim_account_new_schema
366 schema_edit = vim_account_edit_schema
367 multiproject = True
368 password_to_encrypt = "vim_password"
tierno468aa242019-08-01 16:35:04 +0000369 config_to_encrypt = {"1.1": ("admin_password", "nsx_password", "vcenter_password"),
370 "default": ("admin_password", "nsx_password", "vcenter_password", "vrops_password")}
tiernobdebce92019-07-01 15:36:49 +0000371
delacruzramo35c998b2019-11-21 11:09:16 +0100372 def check_conflict_on_del(self, session, _id, db_content):
373 """
374 Check if deletion can be done because of dependencies if it is not force. To override
375 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
376 :param _id: internal _id
377 :param db_content: The database content of this item _id
378 :return: None if ok or raises EngineException with the conflict
379 """
380 if session["force"]:
381 return
382 # check if used by VNF
383 if self.db.get_list("vnfrs", {"vim-account-id": _id}):
384 raise EngineException("There is at least one VNF using this VIM account", http_code=HTTPStatus.CONFLICT)
385 super().check_conflict_on_del(session, _id, db_content)
386
tiernobdebce92019-07-01 15:36:49 +0000387
388class WimAccountTopic(CommonVimWimSdn):
tierno55ba2e62018-12-11 17:22:22 +0000389 topic = "wim_accounts"
390 topic_msg = "wim_account"
391 schema_new = wim_account_new_schema
392 schema_edit = wim_account_edit_schema
tierno65ca36d2019-02-12 19:27:52 +0100393 multiproject = True
tiernobdebce92019-07-01 15:36:49 +0000394 password_to_encrypt = "wim_password"
tierno468aa242019-08-01 16:35:04 +0000395 config_to_encrypt = {}
tierno55ba2e62018-12-11 17:22:22 +0000396
397
tiernobdebce92019-07-01 15:36:49 +0000398class SdnTopic(CommonVimWimSdn):
tiernob24258a2018-10-04 18:39:49 +0200399 topic = "sdns"
400 topic_msg = "sdn"
401 schema_new = sdn_new_schema
402 schema_edit = sdn_edit_schema
tierno65ca36d2019-02-12 19:27:52 +0100403 multiproject = True
tiernobdebce92019-07-01 15:36:49 +0000404 password_to_encrypt = "password"
tierno468aa242019-08-01 16:35:04 +0000405 config_to_encrypt = {}
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100406
407
delacruzramofe598fe2019-10-23 18:25:11 +0200408class K8sClusterTopic(CommonVimWimSdn):
409 topic = "k8sclusters"
410 topic_msg = "k8scluster"
411 schema_new = k8scluster_new_schema
412 schema_edit = k8scluster_edit_schema
413 multiproject = True
414 password_to_encrypt = None
415 config_to_encrypt = {}
416
417 def format_on_new(self, content, project_id=None, make_public=False):
418 oid = super().format_on_new(content, project_id, make_public)
419 self.db.encrypt_decrypt_fields(content["credentials"], 'encrypt', ['password', 'secret'],
420 schema_version=content["schema_version"], salt=content["_id"])
421 return oid
422
423 def format_on_edit(self, final_content, edit_content):
424 if final_content.get("schema_version") and edit_content.get("credentials"):
425 self.db.encrypt_decrypt_fields(edit_content["credentials"], 'encrypt', ['password', 'secret'],
426 schema_version=final_content["schema_version"], salt=final_content["_id"])
427 deep_update_rfc7396(final_content["credentials"], edit_content["credentials"])
428 oid = super().format_on_edit(final_content, edit_content)
429 return oid
430
431
432class K8sRepoTopic(CommonVimWimSdn):
433 topic = "k8srepos"
434 topic_msg = "k8srepo"
435 schema_new = k8srepo_new_schema
436 schema_edit = k8srepo_edit_schema
437 multiproject = True
438 password_to_encrypt = None
439 config_to_encrypt = {}
440
441
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100442class UserTopicAuth(UserTopic):
tierno65ca36d2019-02-12 19:27:52 +0100443 # topic = "users"
444 # topic_msg = "users"
Eduardo Sousaa16a4fa2019-05-23 01:41:18 +0100445 schema_new = user_new_schema
446 schema_edit = user_edit_schema
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100447
448 def __init__(self, db, fs, msg, auth):
delacruzramo32bab472019-09-13 12:24:22 +0200449 UserTopic.__init__(self, db, fs, msg, auth)
450 # self.auth = auth
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100451
tierno65ca36d2019-02-12 19:27:52 +0100452 def check_conflict_on_new(self, session, indata):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100453 """
454 Check that the data to be inserted is valid
455
tierno65ca36d2019-02-12 19:27:52 +0100456 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100457 :param indata: data to be inserted
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100458 :return: None or raises EngineException
459 """
460 username = indata.get("username")
tiernocf042d32019-06-13 09:06:40 +0000461 if is_valid_uuid(username):
delacruzramoceb8baf2019-06-21 14:25:38 +0200462 raise EngineException("username '{}' cannot have a uuid format".format(username),
tiernocf042d32019-06-13 09:06:40 +0000463 HTTPStatus.UNPROCESSABLE_ENTITY)
464
465 # Check that username is not used, regardless keystone already checks this
466 if self.auth.get_user_list(filter_q={"name": username}):
467 raise EngineException("username '{}' is already used".format(username), HTTPStatus.CONFLICT)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100468
Eduardo Sousa339ed782019-05-28 14:25:00 +0100469 if "projects" in indata.keys():
tierno701018c2019-06-25 11:13:14 +0000470 # convert to new format project_role_mappings
delacruzramo01b15d32019-07-02 14:37:47 +0200471 role = self.auth.get_role_list({"name": "project_admin"})
472 if not role:
473 role = self.auth.get_role_list()
474 if not role:
475 raise AuthconnNotFoundException("Can't find default role for user '{}'".format(username))
476 rid = role[0]["_id"]
tierno701018c2019-06-25 11:13:14 +0000477 if not indata.get("project_role_mappings"):
478 indata["project_role_mappings"] = []
479 for project in indata["projects"]:
delacruzramo01b15d32019-07-02 14:37:47 +0200480 pid = self.auth.get_project(project)["_id"]
481 prm = {"project": pid, "role": rid}
482 if prm not in indata["project_role_mappings"]:
483 indata["project_role_mappings"].append(prm)
tierno701018c2019-06-25 11:13:14 +0000484 # raise EngineException("Format invalid: the keyword 'projects' is not allowed for keystone authentication",
485 # HTTPStatus.BAD_REQUEST)
Eduardo Sousa339ed782019-05-28 14:25:00 +0100486
tierno65ca36d2019-02-12 19:27:52 +0100487 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100488 """
489 Check that the data to be edited/uploaded is valid
490
tierno65ca36d2019-02-12 19:27:52 +0100491 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100492 :param final_content: data once modified
493 :param edit_content: incremental data that contains the modifications to apply
494 :param _id: internal _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100495 :return: None or raises EngineException
496 """
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100497
tiernocf042d32019-06-13 09:06:40 +0000498 if "username" in edit_content:
499 username = edit_content.get("username")
500 if is_valid_uuid(username):
delacruzramoceb8baf2019-06-21 14:25:38 +0200501 raise EngineException("username '{}' cannot have an uuid format".format(username),
tiernocf042d32019-06-13 09:06:40 +0000502 HTTPStatus.UNPROCESSABLE_ENTITY)
503
504 # Check that username is not used, regardless keystone already checks this
505 if self.auth.get_user_list(filter_q={"name": username}):
506 raise EngineException("username '{}' is already used".format(username), HTTPStatus.CONFLICT)
507
508 if final_content["username"] == "admin":
509 for mapping in edit_content.get("remove_project_role_mappings", ()):
510 if mapping["project"] == "admin" and mapping.get("role") in (None, "system_admin"):
511 # TODO make this also available for project id and role id
512 raise EngineException("You cannot remove system_admin role from admin user",
513 http_code=HTTPStatus.FORBIDDEN)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100514
tiernob4844ab2019-05-23 08:42:12 +0000515 def check_conflict_on_del(self, session, _id, db_content):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100516 """
517 Check if deletion can be done because of dependencies if it is not force. To override
tierno65ca36d2019-02-12 19:27:52 +0100518 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100519 :param _id: internal _id
tiernob4844ab2019-05-23 08:42:12 +0000520 :param db_content: The database content of this item _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100521 :return: None if ok or raises EngineException with the conflict
522 """
tiernocf042d32019-06-13 09:06:40 +0000523 if db_content["username"] == session["username"]:
524 raise EngineException("You cannot delete your own login user ", http_code=HTTPStatus.CONFLICT)
delacruzramo01b15d32019-07-02 14:37:47 +0200525 # TODO: Check that user is not logged in ? How? (Would require listing current tokens)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100526
Eduardo Sousaa16a4fa2019-05-23 01:41:18 +0100527 @staticmethod
528 def format_on_show(content):
529 """
Eduardo Sousa44603902019-06-04 08:10:32 +0100530 Modifies the content of the role information to separate the role
Eduardo Sousaa16a4fa2019-05-23 01:41:18 +0100531 metadata from the role definition.
532 """
533 project_role_mappings = []
534
delacruzramo01b15d32019-07-02 14:37:47 +0200535 if "projects" in content:
536 for project in content["projects"]:
537 for role in project["roles"]:
538 project_role_mappings.append({"project": project["_id"],
539 "project_name": project["name"],
540 "role": role["_id"],
541 "role_name": role["name"]})
542 del content["projects"]
Eduardo Sousaa16a4fa2019-05-23 01:41:18 +0100543 content["project_role_mappings"] = project_role_mappings
544
Eduardo Sousa0b1d61b2019-05-30 19:55:52 +0100545 return content
546
tierno65ca36d2019-02-12 19:27:52 +0100547 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100548 """
549 Creates a new entry into the authentication backend.
550
551 NOTE: Overrides BaseTopic functionality because it doesn't require access to database.
552
553 :param rollback: list to append created items at database in case a rollback may to be done
tierno65ca36d2019-02-12 19:27:52 +0100554 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100555 :param indata: data to be inserted
556 :param kwargs: used to override the indata descriptor
557 :param headers: http request headers
delacruzramo01b15d32019-07-02 14:37:47 +0200558 :return: _id: identity of the inserted data, operation _id (None)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100559 """
560 try:
561 content = BaseTopic._remove_envelop(indata)
562
563 # Override descriptor with query string kwargs
564 BaseTopic._update_input_with_kwargs(content, kwargs)
tierno65ca36d2019-02-12 19:27:52 +0100565 content = self._validate_input_new(content, session["force"])
566 self.check_conflict_on_new(session, content)
tiernocf042d32019-06-13 09:06:40 +0000567 # self.format_on_new(content, session["project_id"], make_public=session["public"])
delacruzramo01b15d32019-07-02 14:37:47 +0200568 now = time()
569 content["_admin"] = {"created": now, "modified": now}
570 prms = []
571 for prm in content.get("project_role_mappings", []):
572 proj = self.auth.get_project(prm["project"], not session["force"])
573 role = self.auth.get_role(prm["role"], not session["force"])
574 pid = proj["_id"] if proj else None
575 rid = role["_id"] if role else None
576 prl = {"project": pid, "role": rid}
577 if prl not in prms:
578 prms.append(prl)
579 content["project_role_mappings"] = prms
580 # _id = self.auth.create_user(content["username"], content["password"])["_id"]
581 _id = self.auth.create_user(content)["_id"]
Eduardo Sousa44603902019-06-04 08:10:32 +0100582
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100583 rollback.append({"topic": self.topic, "_id": _id})
tiernocf042d32019-06-13 09:06:40 +0000584 # del content["password"]
tiernobee3bad2019-12-05 12:26:01 +0000585 # self._send_msg("created", content, not_send_msg=not_send_msg)
delacruzramo01b15d32019-07-02 14:37:47 +0200586 return _id, None
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100587 except ValidationError as e:
588 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
589
590 def show(self, session, _id):
591 """
592 Get complete information on an topic
593
tierno65ca36d2019-02-12 19:27:52 +0100594 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100595 :param _id: server internal id
596 :return: dictionary, raise exception if not found.
597 """
tiernocf042d32019-06-13 09:06:40 +0000598 # Allow _id to be a name or uuid
599 filter_q = {self.id_field(self.topic, _id): _id}
delacruzramo029405d2019-09-26 10:52:56 +0200600 # users = self.auth.get_user_list(filter_q)
601 users = self.list(session, filter_q) # To allow default filtering (Bug 853)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100602 if len(users) == 1:
tierno1546f2a2019-08-20 15:38:11 +0000603 return users[0]
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100604 elif len(users) > 1:
605 raise EngineException("Too many users found", HTTPStatus.CONFLICT)
606 else:
607 raise EngineException("User not found", HTTPStatus.NOT_FOUND)
608
tierno65ca36d2019-02-12 19:27:52 +0100609 def edit(self, session, _id, indata=None, kwargs=None, content=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100610 """
611 Updates an user entry.
612
tierno65ca36d2019-02-12 19:27:52 +0100613 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100614 :param _id:
615 :param indata: data to be inserted
616 :param kwargs: used to override the indata descriptor
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100617 :param content:
618 :return: _id: identity of the inserted data.
619 """
620 indata = self._remove_envelop(indata)
621
622 # Override descriptor with query string kwargs
623 if kwargs:
624 BaseTopic._update_input_with_kwargs(indata, kwargs)
625 try:
tierno65ca36d2019-02-12 19:27:52 +0100626 indata = self._validate_input_edit(indata, force=session["force"])
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100627
628 if not content:
629 content = self.show(session, _id)
tierno65ca36d2019-02-12 19:27:52 +0100630 self.check_conflict_on_edit(session, content, indata, _id=_id)
tiernocf042d32019-06-13 09:06:40 +0000631 # self.format_on_edit(content, indata)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100632
delacruzramo01b15d32019-07-02 14:37:47 +0200633 if not ("password" in indata or "username" in indata or indata.get("remove_project_role_mappings") or
634 indata.get("add_project_role_mappings") or indata.get("project_role_mappings") or
635 indata.get("projects") or indata.get("add_projects")):
tiernocf042d32019-06-13 09:06:40 +0000636 return _id
delacruzramo01b15d32019-07-02 14:37:47 +0200637 if indata.get("project_role_mappings") \
638 and (indata.get("remove_project_role_mappings") or indata.get("add_project_role_mappings")):
tiernocf042d32019-06-13 09:06:40 +0000639 raise EngineException("Option 'project_role_mappings' is incompatible with 'add_project_role_mappings"
640 "' or 'remove_project_role_mappings'", http_code=HTTPStatus.BAD_REQUEST)
Eduardo Sousa44603902019-06-04 08:10:32 +0100641
delacruzramo01b15d32019-07-02 14:37:47 +0200642 if indata.get("projects") or indata.get("add_projects"):
643 role = self.auth.get_role_list({"name": "project_admin"})
644 if not role:
645 role = self.auth.get_role_list()
646 if not role:
647 raise AuthconnNotFoundException("Can't find a default role for user '{}'"
648 .format(content["username"]))
649 rid = role[0]["_id"]
650 if "add_project_role_mappings" not in indata:
651 indata["add_project_role_mappings"] = []
tierno1546f2a2019-08-20 15:38:11 +0000652 if "remove_project_role_mappings" not in indata:
653 indata["remove_project_role_mappings"] = []
654 if isinstance(indata.get("projects"), dict):
655 # backward compatible
656 for k, v in indata["projects"].items():
657 if k.startswith("$") and v is None:
658 indata["remove_project_role_mappings"].append({"project": k[1:]})
659 elif k.startswith("$+"):
660 indata["add_project_role_mappings"].append({"project": v, "role": rid})
661 del indata["projects"]
delacruzramo01b15d32019-07-02 14:37:47 +0200662 for proj in indata.get("projects", []) + indata.get("add_projects", []):
663 indata["add_project_role_mappings"].append({"project": proj, "role": rid})
664
665 # user = self.show(session, _id) # Already in 'content'
666 original_mapping = content["project_role_mappings"]
Eduardo Sousa44603902019-06-04 08:10:32 +0100667
tiernocf042d32019-06-13 09:06:40 +0000668 mappings_to_add = []
669 mappings_to_remove = []
Eduardo Sousa44603902019-06-04 08:10:32 +0100670
tiernocf042d32019-06-13 09:06:40 +0000671 # remove
672 for to_remove in indata.get("remove_project_role_mappings", ()):
673 for mapping in original_mapping:
674 if to_remove["project"] in (mapping["project"], mapping["project_name"]):
675 if not to_remove.get("role") or to_remove["role"] in (mapping["role"], mapping["role_name"]):
676 mappings_to_remove.append(mapping)
Eduardo Sousa44603902019-06-04 08:10:32 +0100677
tiernocf042d32019-06-13 09:06:40 +0000678 # add
679 for to_add in indata.get("add_project_role_mappings", ()):
680 for mapping in original_mapping:
681 if to_add["project"] in (mapping["project"], mapping["project_name"]) and \
682 to_add["role"] in (mapping["role"], mapping["role_name"]):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100683
tiernocf042d32019-06-13 09:06:40 +0000684 if mapping in mappings_to_remove: # do not remove
685 mappings_to_remove.remove(mapping)
686 break # do not add, it is already at user
687 else:
delacruzramo01b15d32019-07-02 14:37:47 +0200688 pid = self.auth.get_project(to_add["project"])["_id"]
689 rid = self.auth.get_role(to_add["role"])["_id"]
690 mappings_to_add.append({"project": pid, "role": rid})
tiernocf042d32019-06-13 09:06:40 +0000691
692 # set
693 if indata.get("project_role_mappings"):
694 for to_set in indata["project_role_mappings"]:
695 for mapping in original_mapping:
696 if to_set["project"] in (mapping["project"], mapping["project_name"]) and \
697 to_set["role"] in (mapping["role"], mapping["role_name"]):
tiernocf042d32019-06-13 09:06:40 +0000698 if mapping in mappings_to_remove: # do not remove
699 mappings_to_remove.remove(mapping)
700 break # do not add, it is already at user
701 else:
delacruzramo01b15d32019-07-02 14:37:47 +0200702 pid = self.auth.get_project(to_set["project"])["_id"]
703 rid = self.auth.get_role(to_set["role"])["_id"]
704 mappings_to_add.append({"project": pid, "role": rid})
tiernocf042d32019-06-13 09:06:40 +0000705 for mapping in original_mapping:
706 for to_set in indata["project_role_mappings"]:
707 if to_set["project"] in (mapping["project"], mapping["project_name"]) and \
708 to_set["role"] in (mapping["role"], mapping["role_name"]):
709 break
710 else:
711 # delete
712 if mapping not in mappings_to_remove: # do not remove
713 mappings_to_remove.append(mapping)
714
delacruzramo01b15d32019-07-02 14:37:47 +0200715 self.auth.update_user({"_id": _id, "username": indata.get("username"), "password": indata.get("password"),
716 "add_project_role_mappings": mappings_to_add,
717 "remove_project_role_mappings": mappings_to_remove
718 })
tiernocf042d32019-06-13 09:06:40 +0000719
delacruzramo01b15d32019-07-02 14:37:47 +0200720 # return _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100721 except ValidationError as e:
722 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
723
724 def list(self, session, filter_q=None):
725 """
726 Get a list of the topic that matches a filter
tierno65ca36d2019-02-12 19:27:52 +0100727 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100728 :param filter_q: filter of data to be applied
729 :return: The list, it can be empty if no one match the filter.
730 """
delacruzramo029405d2019-09-26 10:52:56 +0200731 user_list = self.auth.get_user_list(filter_q)
732 if not session["allow_show_user_project_role"]:
733 # Bug 853 - Default filtering
734 user_list = [usr for usr in user_list if usr["username"] == session["username"]]
735 return user_list
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100736
tiernobee3bad2019-12-05 12:26:01 +0000737 def delete(self, session, _id, dry_run=False, not_send_msg=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100738 """
739 Delete item by its internal _id
740
tierno65ca36d2019-02-12 19:27:52 +0100741 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100742 :param _id: server internal id
743 :param force: indicates if deletion must be forced in case of conflict
744 :param dry_run: make checking but do not delete
tiernobee3bad2019-12-05 12:26:01 +0000745 :param not_send_msg: To not send message (False) or store content (list) instead
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100746 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
747 """
tiernocf042d32019-06-13 09:06:40 +0000748 # Allow _id to be a name or uuid
delacruzramo01b15d32019-07-02 14:37:47 +0200749 user = self.auth.get_user(_id)
750 uid = user["_id"]
751 self.check_conflict_on_del(session, uid, user)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100752 if not dry_run:
delacruzramo01b15d32019-07-02 14:37:47 +0200753 v = self.auth.delete_user(uid)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100754 return v
755 return None
756
757
758class ProjectTopicAuth(ProjectTopic):
tierno65ca36d2019-02-12 19:27:52 +0100759 # topic = "projects"
760 # topic_msg = "projects"
Eduardo Sousa44603902019-06-04 08:10:32 +0100761 schema_new = project_new_schema
762 schema_edit = project_edit_schema
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100763
764 def __init__(self, db, fs, msg, auth):
delacruzramo32bab472019-09-13 12:24:22 +0200765 ProjectTopic.__init__(self, db, fs, msg, auth)
766 # self.auth = auth
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100767
tierno65ca36d2019-02-12 19:27:52 +0100768 def check_conflict_on_new(self, session, indata):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100769 """
770 Check that the data to be inserted is valid
771
tierno65ca36d2019-02-12 19:27:52 +0100772 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100773 :param indata: data to be inserted
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100774 :return: None or raises EngineException
775 """
tiernocf042d32019-06-13 09:06:40 +0000776 project_name = indata.get("name")
777 if is_valid_uuid(project_name):
delacruzramoceb8baf2019-06-21 14:25:38 +0200778 raise EngineException("project name '{}' cannot have an uuid format".format(project_name),
tiernocf042d32019-06-13 09:06:40 +0000779 HTTPStatus.UNPROCESSABLE_ENTITY)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100780
tiernocf042d32019-06-13 09:06:40 +0000781 project_list = self.auth.get_project_list(filter_q={"name": project_name})
782
783 if project_list:
784 raise EngineException("project '{}' exists".format(project_name), HTTPStatus.CONFLICT)
785
786 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
787 """
788 Check that the data to be edited/uploaded is valid
789
790 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
791 :param final_content: data once modified
792 :param edit_content: incremental data that contains the modifications to apply
793 :param _id: internal _id
794 :return: None or raises EngineException
795 """
796
797 project_name = edit_content.get("name")
delacruzramo01b15d32019-07-02 14:37:47 +0200798 if project_name != final_content["name"]: # It is a true renaming
tiernocf042d32019-06-13 09:06:40 +0000799 if is_valid_uuid(project_name):
delacruzramo79e40f42019-10-10 16:36:40 +0200800 raise EngineException("project name '{}' cannot have an uuid format".format(project_name),
tiernocf042d32019-06-13 09:06:40 +0000801 HTTPStatus.UNPROCESSABLE_ENTITY)
802
delacruzramo01b15d32019-07-02 14:37:47 +0200803 if final_content["name"] == "admin":
804 raise EngineException("You cannot rename project 'admin'", http_code=HTTPStatus.CONFLICT)
805
tiernocf042d32019-06-13 09:06:40 +0000806 # Check that project name is not used, regardless keystone already checks this
delacruzramo32bab472019-09-13 12:24:22 +0200807 if project_name and self.auth.get_project_list(filter_q={"name": project_name}):
tiernocf042d32019-06-13 09:06:40 +0000808 raise EngineException("project '{}' is already used".format(project_name), HTTPStatus.CONFLICT)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100809
tiernob4844ab2019-05-23 08:42:12 +0000810 def check_conflict_on_del(self, session, _id, db_content):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100811 """
812 Check if deletion can be done because of dependencies if it is not force. To override
813
tierno65ca36d2019-02-12 19:27:52 +0100814 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100815 :param _id: internal _id
tiernob4844ab2019-05-23 08:42:12 +0000816 :param db_content: The database content of this item _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100817 :return: None if ok or raises EngineException with the conflict
818 """
delacruzramo01b15d32019-07-02 14:37:47 +0200819
820 def check_rw_projects(topic, title, id_field):
821 for desc in self.db.get_list(topic):
822 if _id in desc["_admin"]["projects_read"] + desc["_admin"]["projects_write"]:
823 raise EngineException("Project '{}' ({}) is being used by {} '{}'"
824 .format(db_content["name"], _id, title, desc[id_field]), HTTPStatus.CONFLICT)
825
826 if _id in session["project_id"]:
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100827 raise EngineException("You cannot delete your own project", http_code=HTTPStatus.CONFLICT)
828
delacruzramo01b15d32019-07-02 14:37:47 +0200829 if db_content["name"] == "admin":
830 raise EngineException("You cannot delete project 'admin'", http_code=HTTPStatus.CONFLICT)
831
832 # If any user is using this project, raise CONFLICT exception
833 if not session["force"]:
834 for user in self.auth.get_user_list():
tierno1546f2a2019-08-20 15:38:11 +0000835 for prm in user.get("project_role_mappings"):
836 if prm["project"] == _id:
837 raise EngineException("Project '{}' ({}) is being used by user '{}'"
838 .format(db_content["name"], _id, user["username"]), HTTPStatus.CONFLICT)
delacruzramo01b15d32019-07-02 14:37:47 +0200839
840 # If any VNFD, NSD, NST, PDU, etc. is using this project, raise CONFLICT exception
841 if not session["force"]:
842 check_rw_projects("vnfds", "VNF Descriptor", "id")
843 check_rw_projects("nsds", "NS Descriptor", "id")
844 check_rw_projects("nsts", "NS Template", "id")
845 check_rw_projects("pdus", "PDU Descriptor", "name")
846
tierno65ca36d2019-02-12 19:27:52 +0100847 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100848 """
849 Creates a new entry into the authentication backend.
850
851 NOTE: Overrides BaseTopic functionality because it doesn't require access to database.
852
853 :param rollback: list to append created items at database in case a rollback may to be done
tierno65ca36d2019-02-12 19:27:52 +0100854 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100855 :param indata: data to be inserted
856 :param kwargs: used to override the indata descriptor
857 :param headers: http request headers
delacruzramo01b15d32019-07-02 14:37:47 +0200858 :return: _id: identity of the inserted data, operation _id (None)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100859 """
860 try:
861 content = BaseTopic._remove_envelop(indata)
862
863 # Override descriptor with query string kwargs
864 BaseTopic._update_input_with_kwargs(content, kwargs)
tierno65ca36d2019-02-12 19:27:52 +0100865 content = self._validate_input_new(content, session["force"])
866 self.check_conflict_on_new(session, content)
867 self.format_on_new(content, project_id=session["project_id"], make_public=session["public"])
delacruzramo01b15d32019-07-02 14:37:47 +0200868 _id = self.auth.create_project(content)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100869 rollback.append({"topic": self.topic, "_id": _id})
tiernobee3bad2019-12-05 12:26:01 +0000870 # self._send_msg("created", content, not_send_msg=not_send_msg)
delacruzramo01b15d32019-07-02 14:37:47 +0200871 return _id, None
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100872 except ValidationError as e:
873 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
874
875 def show(self, session, _id):
876 """
877 Get complete information on an topic
878
tierno65ca36d2019-02-12 19:27:52 +0100879 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100880 :param _id: server internal id
881 :return: dictionary, raise exception if not found.
882 """
tiernocf042d32019-06-13 09:06:40 +0000883 # Allow _id to be a name or uuid
884 filter_q = {self.id_field(self.topic, _id): _id}
delacruzramo029405d2019-09-26 10:52:56 +0200885 # projects = self.auth.get_project_list(filter_q=filter_q)
886 projects = self.list(session, filter_q) # To allow default filtering (Bug 853)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100887 if len(projects) == 1:
888 return projects[0]
889 elif len(projects) > 1:
890 raise EngineException("Too many projects found", HTTPStatus.CONFLICT)
891 else:
892 raise EngineException("Project not found", HTTPStatus.NOT_FOUND)
893
894 def list(self, session, filter_q=None):
895 """
896 Get a list of the topic that matches a filter
897
tierno65ca36d2019-02-12 19:27:52 +0100898 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100899 :param filter_q: filter of data to be applied
900 :return: The list, it can be empty if no one match the filter.
901 """
delacruzramo029405d2019-09-26 10:52:56 +0200902 project_list = self.auth.get_project_list(filter_q)
903 if not session["allow_show_user_project_role"]:
904 # Bug 853 - Default filtering
905 user = self.auth.get_user(session["username"])
906 projects = [prm["project"] for prm in user["project_role_mappings"]]
907 project_list = [proj for proj in project_list if proj["_id"] in projects]
908 return project_list
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100909
tiernobee3bad2019-12-05 12:26:01 +0000910 def delete(self, session, _id, dry_run=False, not_send_msg=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100911 """
912 Delete item by its internal _id
913
tierno65ca36d2019-02-12 19:27:52 +0100914 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100915 :param _id: server internal id
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100916 :param dry_run: make checking but do not delete
tiernobee3bad2019-12-05 12:26:01 +0000917 :param not_send_msg: To not send message (False) or store content (list) instead
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100918 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
919 """
tiernocf042d32019-06-13 09:06:40 +0000920 # Allow _id to be a name or uuid
delacruzramo01b15d32019-07-02 14:37:47 +0200921 proj = self.auth.get_project(_id)
922 pid = proj["_id"]
923 self.check_conflict_on_del(session, pid, proj)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100924 if not dry_run:
delacruzramo01b15d32019-07-02 14:37:47 +0200925 v = self.auth.delete_project(pid)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100926 return v
927 return None
928
tierno4015b472019-06-10 13:57:29 +0000929 def edit(self, session, _id, indata=None, kwargs=None, content=None):
930 """
931 Updates a project entry.
932
933 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
934 :param _id:
935 :param indata: data to be inserted
936 :param kwargs: used to override the indata descriptor
937 :param content:
938 :return: _id: identity of the inserted data.
939 """
940 indata = self._remove_envelop(indata)
941
942 # Override descriptor with query string kwargs
943 if kwargs:
944 BaseTopic._update_input_with_kwargs(indata, kwargs)
945 try:
946 indata = self._validate_input_edit(indata, force=session["force"])
947
948 if not content:
949 content = self.show(session, _id)
950 self.check_conflict_on_edit(session, content, indata, _id=_id)
delacruzramo01b15d32019-07-02 14:37:47 +0200951 self.format_on_edit(content, indata)
tierno4015b472019-06-10 13:57:29 +0000952
delacruzramo32bab472019-09-13 12:24:22 +0200953 deep_update_rfc7396(content, indata)
delacruzramo01b15d32019-07-02 14:37:47 +0200954 self.auth.update_project(content["_id"], content)
tierno4015b472019-06-10 13:57:29 +0000955 except ValidationError as e:
956 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
957
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100958
959class RoleTopicAuth(BaseTopic):
delacruzramoceb8baf2019-06-21 14:25:38 +0200960 topic = "roles"
961 topic_msg = None # "roles"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100962 schema_new = roles_new_schema
963 schema_edit = roles_edit_schema
tierno65ca36d2019-02-12 19:27:52 +0100964 multiproject = False
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100965
966 def __init__(self, db, fs, msg, auth, ops):
delacruzramo32bab472019-09-13 12:24:22 +0200967 BaseTopic.__init__(self, db, fs, msg, auth)
968 # self.auth = auth
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100969 self.operations = ops
delacruzramo01b15d32019-07-02 14:37:47 +0200970 # self.topic = "roles_operations" if isinstance(auth, AuthconnKeystone) else "roles"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100971
972 @staticmethod
973 def validate_role_definition(operations, role_definitions):
974 """
975 Validates the role definition against the operations defined in
976 the resources to operations files.
977
978 :param operations: operations list
979 :param role_definitions: role definition to test
980 :return: None if ok, raises ValidationError exception on error
981 """
tierno1f029d82019-06-13 22:37:04 +0000982 if not role_definitions.get("permissions"):
983 return
984 ignore_fields = ["admin", "default"]
985 for role_def in role_definitions["permissions"].keys():
Eduardo Sousa37de0912019-05-23 02:17:22 +0100986 if role_def in ignore_fields:
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100987 continue
Eduardo Sousac7689372019-06-04 16:01:46 +0100988 if role_def[-1] == ":":
tierno1f029d82019-06-13 22:37:04 +0000989 raise ValidationError("Operation cannot end with ':'")
Eduardo Sousac5a18892019-06-06 14:51:23 +0100990
delacruzramoc061f562019-04-05 11:00:02 +0200991 role_def_matches = [op for op in operations if op.startswith(role_def)]
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100992
993 if len(role_def_matches) == 0:
tierno1f029d82019-06-13 22:37:04 +0000994 raise ValidationError("Invalid permission '{}'".format(role_def))
Eduardo Sousa37de0912019-05-23 02:17:22 +0100995
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100996 def _validate_input_new(self, input, force=False):
997 """
998 Validates input user content for a new entry.
999
1000 :param input: user input content for the new topic
1001 :param force: may be used for being more tolerant
1002 :return: The same input content, or a changed version of it.
1003 """
1004 if self.schema_new:
1005 validate_input(input, self.schema_new)
Eduardo Sousa37de0912019-05-23 02:17:22 +01001006 self.validate_role_definition(self.operations, input)
Eduardo Sousac4650362019-06-04 13:24:22 +01001007
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001008 return input
1009
1010 def _validate_input_edit(self, input, force=False):
1011 """
1012 Validates input user content for updating an entry.
1013
1014 :param input: user input content for the new topic
1015 :param force: may be used for being more tolerant
1016 :return: The same input content, or a changed version of it.
1017 """
1018 if self.schema_edit:
1019 validate_input(input, self.schema_edit)
Eduardo Sousa37de0912019-05-23 02:17:22 +01001020 self.validate_role_definition(self.operations, input)
Eduardo Sousac4650362019-06-04 13:24:22 +01001021
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001022 return input
1023
tierno65ca36d2019-02-12 19:27:52 +01001024 def check_conflict_on_new(self, session, indata):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001025 """
1026 Check that the data to be inserted is valid
1027
tierno65ca36d2019-02-12 19:27:52 +01001028 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001029 :param indata: data to be inserted
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001030 :return: None or raises EngineException
1031 """
delacruzramo79e40f42019-10-10 16:36:40 +02001032 # check name is not uuid
1033 role_name = indata.get("name")
1034 if is_valid_uuid(role_name):
1035 raise EngineException("role name '{}' cannot have an uuid format".format(role_name),
1036 HTTPStatus.UNPROCESSABLE_ENTITY)
tierno1f029d82019-06-13 22:37:04 +00001037 # check name not exists
delacruzramo01b15d32019-07-02 14:37:47 +02001038 name = indata["name"]
1039 # if self.db.get_one(self.topic, {"name": indata.get("name")}, fail_on_empty=False, fail_on_more=False):
1040 if self.auth.get_role_list({"name": name}):
1041 raise EngineException("role name '{}' exists".format(name), HTTPStatus.CONFLICT)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001042
tierno65ca36d2019-02-12 19:27:52 +01001043 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001044 """
1045 Check that the data to be edited/uploaded is valid
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 final_content: data once modified
1049 :param edit_content: incremental data that contains the modifications to apply
1050 :param _id: internal _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001051 :return: None or raises EngineException
1052 """
tierno1f029d82019-06-13 22:37:04 +00001053 if "default" not in final_content["permissions"]:
1054 final_content["permissions"]["default"] = False
1055 if "admin" not in final_content["permissions"]:
1056 final_content["permissions"]["admin"] = False
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001057
delacruzramo79e40f42019-10-10 16:36:40 +02001058 # check name is not uuid
1059 role_name = edit_content.get("name")
1060 if is_valid_uuid(role_name):
1061 raise EngineException("role name '{}' cannot have an uuid format".format(role_name),
1062 HTTPStatus.UNPROCESSABLE_ENTITY)
1063
1064 # Check renaming of admin roles
1065 role = self.auth.get_role(_id)
1066 if role["name"] in ["system_admin", "project_admin"]:
1067 raise EngineException("You cannot rename role '{}'".format(role["name"]), http_code=HTTPStatus.FORBIDDEN)
1068
tierno1f029d82019-06-13 22:37:04 +00001069 # check name not exists
1070 if "name" in edit_content:
1071 role_name = edit_content["name"]
delacruzramo01b15d32019-07-02 14:37:47 +02001072 # if self.db.get_one(self.topic, {"name":role_name,"_id.ne":_id}, fail_on_empty=False, fail_on_more=False):
1073 roles = self.auth.get_role_list({"name": role_name})
1074 if roles and roles[0][BaseTopic.id_field("roles", _id)] != _id:
tierno1f029d82019-06-13 22:37:04 +00001075 raise EngineException("role name '{}' exists".format(role_name), HTTPStatus.CONFLICT)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001076
tiernob4844ab2019-05-23 08:42:12 +00001077 def check_conflict_on_del(self, session, _id, db_content):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001078 """
1079 Check if deletion can be done because of dependencies if it is not force. To override
1080
tierno65ca36d2019-02-12 19:27:52 +01001081 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001082 :param _id: internal _id
tiernob4844ab2019-05-23 08:42:12 +00001083 :param db_content: The database content of this item _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001084 :return: None if ok or raises EngineException with the conflict
1085 """
delacruzramo01b15d32019-07-02 14:37:47 +02001086 role = self.auth.get_role(_id)
1087 if role["name"] in ["system_admin", "project_admin"]:
1088 raise EngineException("You cannot delete role '{}'".format(role["name"]), http_code=HTTPStatus.FORBIDDEN)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001089
delacruzramo01b15d32019-07-02 14:37:47 +02001090 # If any user is using this role, raise CONFLICT exception
1091 for user in self.auth.get_user_list():
tierno1546f2a2019-08-20 15:38:11 +00001092 for prm in user.get("project_role_mappings"):
1093 if prm["role"] == _id:
1094 raise EngineException("Role '{}' ({}) is being used by user '{}'"
1095 .format(role["name"], _id, user["username"]), HTTPStatus.CONFLICT)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001096
1097 @staticmethod
delacruzramo01b15d32019-07-02 14:37:47 +02001098 def format_on_new(content, project_id=None, make_public=False): # TO BE REMOVED ?
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001099 """
1100 Modifies content descriptor to include _admin
1101
1102 :param content: descriptor to be modified
1103 :param project_id: if included, it add project read/write permissions
1104 :param make_public: if included it is generated as public for reading.
1105 :return: None, but content is modified
1106 """
1107 now = time()
1108 if "_admin" not in content:
1109 content["_admin"] = {}
1110 if not content["_admin"].get("created"):
1111 content["_admin"]["created"] = now
1112 content["_admin"]["modified"] = now
Eduardo Sousac4650362019-06-04 13:24:22 +01001113
tierno1f029d82019-06-13 22:37:04 +00001114 if "permissions" not in content:
1115 content["permissions"] = {}
Eduardo Sousac4650362019-06-04 13:24:22 +01001116
tierno1f029d82019-06-13 22:37:04 +00001117 if "default" not in content["permissions"]:
1118 content["permissions"]["default"] = False
1119 if "admin" not in content["permissions"]:
1120 content["permissions"]["admin"] = False
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001121
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001122 @staticmethod
1123 def format_on_edit(final_content, edit_content):
1124 """
1125 Modifies final_content descriptor to include the modified date.
1126
1127 :param final_content: final descriptor generated
1128 :param edit_content: alterations to be include
1129 :return: None, but final_content is modified
1130 """
delacruzramo01b15d32019-07-02 14:37:47 +02001131 if "_admin" in final_content:
1132 final_content["_admin"]["modified"] = time()
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001133
tierno1f029d82019-06-13 22:37:04 +00001134 if "permissions" not in final_content:
1135 final_content["permissions"] = {}
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001136
tierno1f029d82019-06-13 22:37:04 +00001137 if "default" not in final_content["permissions"]:
1138 final_content["permissions"]["default"] = False
1139 if "admin" not in final_content["permissions"]:
1140 final_content["permissions"]["admin"] = False
tiernobdebce92019-07-01 15:36:49 +00001141 return None
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001142
delacruzramo01b15d32019-07-02 14:37:47 +02001143 def show(self, session, _id):
1144 """
1145 Get complete information on an topic
Eduardo Sousac4650362019-06-04 13:24:22 +01001146
delacruzramo01b15d32019-07-02 14:37:47 +02001147 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1148 :param _id: server internal id
1149 :return: dictionary, raise exception if not found.
1150 """
1151 filter_q = {BaseTopic.id_field(self.topic, _id): _id}
delacruzramo029405d2019-09-26 10:52:56 +02001152 # roles = self.auth.get_role_list(filter_q)
1153 roles = self.list(session, filter_q) # To allow default filtering (Bug 853)
delacruzramo01b15d32019-07-02 14:37:47 +02001154 if not roles:
1155 raise AuthconnNotFoundException("Not found any role with filter {}".format(filter_q))
1156 elif len(roles) > 1:
1157 raise AuthconnConflictException("Found more than one role with filter {}".format(filter_q))
1158 return roles[0]
1159
1160 def list(self, session, filter_q=None):
1161 """
1162 Get a list of the topic that matches a filter
1163
1164 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1165 :param filter_q: filter of data to be applied
1166 :return: The list, it can be empty if no one match the filter.
1167 """
delacruzramo029405d2019-09-26 10:52:56 +02001168 role_list = self.auth.get_role_list(filter_q)
1169 if not session["allow_show_user_project_role"]:
1170 # Bug 853 - Default filtering
1171 user = self.auth.get_user(session["username"])
1172 roles = [prm["role"] for prm in user["project_role_mappings"]]
1173 role_list = [role for role in role_list if role["_id"] in roles]
1174 return role_list
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001175
tierno65ca36d2019-02-12 19:27:52 +01001176 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001177 """
1178 Creates a new entry into database.
1179
1180 :param rollback: list to append created items at database in case a rollback may to be done
tierno65ca36d2019-02-12 19:27:52 +01001181 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001182 :param indata: data to be inserted
1183 :param kwargs: used to override the indata descriptor
1184 :param headers: http request headers
delacruzramo01b15d32019-07-02 14:37:47 +02001185 :return: _id: identity of the inserted data, operation _id (None)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001186 """
1187 try:
tierno1f029d82019-06-13 22:37:04 +00001188 content = self._remove_envelop(indata)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001189
1190 # Override descriptor with query string kwargs
tierno1f029d82019-06-13 22:37:04 +00001191 self._update_input_with_kwargs(content, kwargs)
tierno65ca36d2019-02-12 19:27:52 +01001192 content = self._validate_input_new(content, session["force"])
1193 self.check_conflict_on_new(session, content)
1194 self.format_on_new(content, project_id=session["project_id"], make_public=session["public"])
delacruzramo01b15d32019-07-02 14:37:47 +02001195 # role_name = content["name"]
1196 rid = self.auth.create_role(content)
1197 content["_id"] = rid
1198 # _id = self.db.create(self.topic, content)
1199 rollback.append({"topic": self.topic, "_id": rid})
tiernobee3bad2019-12-05 12:26:01 +00001200 # self._send_msg("created", content, not_send_msg=not_send_msg)
delacruzramo01b15d32019-07-02 14:37:47 +02001201 return rid, None
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001202 except ValidationError as e:
1203 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1204
tiernobee3bad2019-12-05 12:26:01 +00001205 def delete(self, session, _id, dry_run=False, not_send_msg=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001206 """
1207 Delete item by its internal _id
1208
tierno65ca36d2019-02-12 19:27:52 +01001209 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001210 :param _id: server internal id
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001211 :param dry_run: make checking but do not delete
tiernobee3bad2019-12-05 12:26:01 +00001212 :param not_send_msg: To not send message (False) or store content (list) instead
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001213 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
1214 """
delacruzramo01b15d32019-07-02 14:37:47 +02001215 filter_q = {BaseTopic.id_field(self.topic, _id): _id}
1216 roles = self.auth.get_role_list(filter_q)
1217 if not roles:
1218 raise AuthconnNotFoundException("Not found any role with filter {}".format(filter_q))
1219 elif len(roles) > 1:
1220 raise AuthconnConflictException("Found more than one role with filter {}".format(filter_q))
1221 rid = roles[0]["_id"]
1222 self.check_conflict_on_del(session, rid, None)
delacruzramoceb8baf2019-06-21 14:25:38 +02001223 # filter_q = {"_id": _id}
delacruzramo01b15d32019-07-02 14:37:47 +02001224 # filter_q = {BaseTopic.id_field(self.topic, _id): _id} # To allow role addressing by name
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001225 if not dry_run:
delacruzramo01b15d32019-07-02 14:37:47 +02001226 v = self.auth.delete_role(rid)
1227 # v = self.db.del_one(self.topic, filter_q)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001228 return v
1229 return None
1230
tierno65ca36d2019-02-12 19:27:52 +01001231 def edit(self, session, _id, indata=None, kwargs=None, content=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001232 """
1233 Updates a role entry.
1234
tierno65ca36d2019-02-12 19:27:52 +01001235 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001236 :param _id:
1237 :param indata: data to be inserted
1238 :param kwargs: used to override the indata descriptor
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001239 :param content:
1240 :return: _id: identity of the inserted data.
1241 """
delacruzramo01b15d32019-07-02 14:37:47 +02001242 if kwargs:
1243 self._update_input_with_kwargs(indata, kwargs)
1244 try:
1245 indata = self._validate_input_edit(indata, force=session["force"])
1246 if not content:
1247 content = self.show(session, _id)
1248 deep_update_rfc7396(content, indata)
1249 self.check_conflict_on_edit(session, content, indata, _id=_id)
1250 self.format_on_edit(content, indata)
1251 self.auth.update_role(content)
1252 except ValidationError as e:
1253 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)