blob: 788ae3e26537b3e1ae6ff818fc36586a4fb5b4fe [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
garciadeblas4568a372021-03-24 09:19:48 +010021from osm_nbi.validation import (
22 user_new_schema,
23 user_edit_schema,
24 project_new_schema,
25 project_edit_schema,
26 vim_account_new_schema,
27 vim_account_edit_schema,
28 sdn_new_schema,
29 sdn_edit_schema,
30 wim_account_new_schema,
31 wim_account_edit_schema,
32 roles_new_schema,
33 roles_edit_schema,
34 k8scluster_new_schema,
35 k8scluster_edit_schema,
36 k8srepo_new_schema,
37 k8srepo_edit_schema,
38 vca_new_schema,
39 vca_edit_schema,
40 osmrepo_new_schema,
41 osmrepo_edit_schema,
42 validate_input,
43 ValidationError,
44 is_valid_uuid,
45) # To check that User/Project Names don't look like UUIDs
tierno23acf402019-08-28 13:36:34 +000046from osm_nbi.base_topic import BaseTopic, EngineException
47from osm_nbi.authconn import AuthconnNotFoundException, AuthconnConflictException
delacruzramo01b15d32019-07-02 14:37:47 +020048from osm_common.dbbase import deep_update_rfc7396
agarwalat53471982020-10-08 13:06:14 +000049import copy
tiernob24258a2018-10-04 18:39:49 +020050
51__author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
52
53
54class UserTopic(BaseTopic):
55 topic = "users"
56 topic_msg = "users"
57 schema_new = user_new_schema
58 schema_edit = user_edit_schema
tierno65ca36d2019-02-12 19:27:52 +010059 multiproject = False
tiernob24258a2018-10-04 18:39:49 +020060
delacruzramo32bab472019-09-13 12:24:22 +020061 def __init__(self, db, fs, msg, auth):
62 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +020063
64 @staticmethod
tierno65ca36d2019-02-12 19:27:52 +010065 def _get_project_filter(session):
tiernob24258a2018-10-04 18:39:49 +020066 """
67 Generates a filter dictionary for querying database users.
68 Current policy is admin can show all, non admin, only its own user.
tierno65ca36d2019-02-12 19:27:52 +010069 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +020070 :return:
71 """
72 if session["admin"]: # allows all
73 return {}
74 else:
75 return {"username": session["username"]}
76
tierno65ca36d2019-02-12 19:27:52 +010077 def check_conflict_on_new(self, session, indata):
tiernob24258a2018-10-04 18:39:49 +020078 # check username not exists
garciadeblas4568a372021-03-24 09:19:48 +010079 if self.db.get_one(
80 self.topic,
81 {"username": indata.get("username")},
82 fail_on_empty=False,
83 fail_on_more=False,
84 ):
85 raise EngineException(
86 "username '{}' exists".format(indata["username"]), HTTPStatus.CONFLICT
87 )
tiernob24258a2018-10-04 18:39:49 +020088 # check projects
tierno65ca36d2019-02-12 19:27:52 +010089 if not session["force"]:
delacruzramoceb8baf2019-06-21 14:25:38 +020090 for p in indata.get("projects") or []:
delacruzramoc061f562019-04-05 11:00:02 +020091 # To allow project addressing by Name as well as ID
garciadeblas4568a372021-03-24 09:19:48 +010092 if not self.db.get_one(
93 "projects",
94 {BaseTopic.id_field("projects", p): p},
95 fail_on_empty=False,
96 fail_on_more=False,
97 ):
98 raise EngineException(
99 "project '{}' does not exist".format(p), HTTPStatus.CONFLICT
100 )
tiernob24258a2018-10-04 18:39:49 +0200101
tiernob4844ab2019-05-23 08:42:12 +0000102 def check_conflict_on_del(self, session, _id, db_content):
103 """
104 Check if deletion can be done because of dependencies if it is not force. To override
105 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
106 :param _id: internal _id
107 :param db_content: The database content of this item _id
108 :return: None if ok or raises EngineException with the conflict
109 """
tiernob24258a2018-10-04 18:39:49 +0200110 if _id == session["username"]:
garciadeblas4568a372021-03-24 09:19:48 +0100111 raise EngineException(
112 "You cannot delete your own user", http_code=HTTPStatus.CONFLICT
113 )
tiernob24258a2018-10-04 18:39:49 +0200114
115 @staticmethod
116 def format_on_new(content, project_id=None, make_public=False):
117 BaseTopic.format_on_new(content, make_public=False)
delacruzramoc061f562019-04-05 11:00:02 +0200118 # Removed so that the UUID is kept, to allow User Name modification
119 # content["_id"] = content["username"]
tiernob24258a2018-10-04 18:39:49 +0200120 salt = uuid4().hex
121 content["_admin"]["salt"] = salt
122 if content.get("password"):
garciadeblas4568a372021-03-24 09:19:48 +0100123 content["password"] = sha256(
124 content["password"].encode("utf-8") + salt.encode("utf-8")
125 ).hexdigest()
Eduardo Sousa339ed782019-05-28 14:25:00 +0100126 if content.get("project_role_mappings"):
garciadeblas4568a372021-03-24 09:19:48 +0100127 projects = [
128 mapping["project"] for mapping in content["project_role_mappings"]
129 ]
Eduardo Sousa339ed782019-05-28 14:25:00 +0100130
131 if content.get("projects"):
132 content["projects"] += projects
133 else:
134 content["projects"] = projects
tiernob24258a2018-10-04 18:39:49 +0200135
136 @staticmethod
137 def format_on_edit(final_content, edit_content):
138 BaseTopic.format_on_edit(final_content, edit_content)
139 if edit_content.get("password"):
140 salt = uuid4().hex
141 final_content["_admin"]["salt"] = salt
garciadeblas4568a372021-03-24 09:19:48 +0100142 final_content["password"] = sha256(
143 edit_content["password"].encode("utf-8") + salt.encode("utf-8")
144 ).hexdigest()
tiernobdebce92019-07-01 15:36:49 +0000145 return None
tiernob24258a2018-10-04 18:39:49 +0200146
tierno65ca36d2019-02-12 19:27:52 +0100147 def edit(self, session, _id, indata=None, kwargs=None, content=None):
tiernob24258a2018-10-04 18:39:49 +0200148 if not session["admin"]:
garciadeblas4568a372021-03-24 09:19:48 +0100149 raise EngineException(
150 "needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED
151 )
delacruzramoc061f562019-04-05 11:00:02 +0200152 # Names that look like UUIDs are not allowed
153 name = (indata if indata else kwargs).get("username")
154 if is_valid_uuid(name):
garciadeblas4568a372021-03-24 09:19:48 +0100155 raise EngineException(
156 "Usernames that look like UUIDs are not allowed",
157 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
158 )
159 return BaseTopic.edit(
160 self, session, _id, indata=indata, kwargs=kwargs, content=content
161 )
tiernob24258a2018-10-04 18:39:49 +0200162
tierno65ca36d2019-02-12 19:27:52 +0100163 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +0200164 if not session["admin"]:
garciadeblas4568a372021-03-24 09:19:48 +0100165 raise EngineException(
166 "needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED
167 )
delacruzramoc061f562019-04-05 11:00:02 +0200168 # Names that look like UUIDs are not allowed
169 name = indata["username"] if indata else kwargs["username"]
170 if is_valid_uuid(name):
garciadeblas4568a372021-03-24 09:19:48 +0100171 raise EngineException(
172 "Usernames that look like UUIDs are not allowed",
173 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
174 )
175 return BaseTopic.new(
176 self, rollback, session, indata=indata, kwargs=kwargs, headers=headers
177 )
tiernob24258a2018-10-04 18:39:49 +0200178
179
180class ProjectTopic(BaseTopic):
181 topic = "projects"
182 topic_msg = "projects"
183 schema_new = project_new_schema
184 schema_edit = project_edit_schema
tierno65ca36d2019-02-12 19:27:52 +0100185 multiproject = False
tiernob24258a2018-10-04 18:39:49 +0200186
delacruzramo32bab472019-09-13 12:24:22 +0200187 def __init__(self, db, fs, msg, auth):
188 BaseTopic.__init__(self, db, fs, msg, auth)
tiernob24258a2018-10-04 18:39:49 +0200189
tierno65ca36d2019-02-12 19:27:52 +0100190 @staticmethod
191 def _get_project_filter(session):
192 """
193 Generates a filter dictionary for querying database users.
194 Current policy is admin can show all, non admin, only its own user.
195 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
196 :return:
197 """
198 if session["admin"]: # allows all
199 return {}
200 else:
201 return {"_id.cont": session["project_id"]}
202
203 def check_conflict_on_new(self, session, indata):
tiernob24258a2018-10-04 18:39:49 +0200204 if not indata.get("name"):
205 raise EngineException("missing 'name'")
206 # check name not exists
garciadeblas4568a372021-03-24 09:19:48 +0100207 if self.db.get_one(
208 self.topic,
209 {"name": indata.get("name")},
210 fail_on_empty=False,
211 fail_on_more=False,
212 ):
213 raise EngineException(
214 "name '{}' exists".format(indata["name"]), HTTPStatus.CONFLICT
215 )
tiernob24258a2018-10-04 18:39:49 +0200216
217 @staticmethod
218 def format_on_new(content, project_id=None, make_public=False):
219 BaseTopic.format_on_new(content, None)
delacruzramoc061f562019-04-05 11:00:02 +0200220 # Removed so that the UUID is kept, to allow Project Name modification
221 # content["_id"] = content["name"]
tiernob24258a2018-10-04 18:39:49 +0200222
tiernob4844ab2019-05-23 08:42:12 +0000223 def check_conflict_on_del(self, session, _id, db_content):
224 """
225 Check if deletion can be done because of dependencies if it is not force. To override
226 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
227 :param _id: internal _id
228 :param db_content: The database content of this item _id
229 :return: None if ok or raises EngineException with the conflict
230 """
tierno65ca36d2019-02-12 19:27:52 +0100231 if _id in session["project_id"]:
garciadeblas4568a372021-03-24 09:19:48 +0100232 raise EngineException(
233 "You cannot delete your own project", http_code=HTTPStatus.CONFLICT
234 )
tierno65ca36d2019-02-12 19:27:52 +0100235 if session["force"]:
tiernob24258a2018-10-04 18:39:49 +0200236 return
237 _filter = {"projects": _id}
238 if self.db.get_list("users", _filter):
garciadeblas4568a372021-03-24 09:19:48 +0100239 raise EngineException(
240 "There is some USER that contains this project",
241 http_code=HTTPStatus.CONFLICT,
242 )
tiernob24258a2018-10-04 18:39:49 +0200243
tierno65ca36d2019-02-12 19:27:52 +0100244 def edit(self, session, _id, indata=None, kwargs=None, content=None):
tiernob24258a2018-10-04 18:39:49 +0200245 if not session["admin"]:
garciadeblas4568a372021-03-24 09:19:48 +0100246 raise EngineException(
247 "needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED
248 )
delacruzramoc061f562019-04-05 11:00:02 +0200249 # Names that look like UUIDs are not allowed
250 name = (indata if indata else kwargs).get("name")
251 if is_valid_uuid(name):
garciadeblas4568a372021-03-24 09:19:48 +0100252 raise EngineException(
253 "Project names that look like UUIDs are not allowed",
254 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
255 )
256 return BaseTopic.edit(
257 self, session, _id, indata=indata, kwargs=kwargs, content=content
258 )
tiernob24258a2018-10-04 18:39:49 +0200259
tierno65ca36d2019-02-12 19:27:52 +0100260 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
tiernob24258a2018-10-04 18:39:49 +0200261 if not session["admin"]:
garciadeblas4568a372021-03-24 09:19:48 +0100262 raise EngineException(
263 "needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED
264 )
delacruzramoc061f562019-04-05 11:00:02 +0200265 # Names that look like UUIDs are not allowed
266 name = indata["name"] if indata else kwargs["name"]
267 if is_valid_uuid(name):
garciadeblas4568a372021-03-24 09:19:48 +0100268 raise EngineException(
269 "Project names that look like UUIDs are not allowed",
270 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
271 )
272 return BaseTopic.new(
273 self, rollback, session, indata=indata, kwargs=kwargs, headers=headers
274 )
tiernob24258a2018-10-04 18:39:49 +0200275
276
tiernobdebce92019-07-01 15:36:49 +0000277class CommonVimWimSdn(BaseTopic):
278 """Common class for VIM, WIM SDN just to unify methods that are equal to all of them"""
garciadeblas4568a372021-03-24 09:19:48 +0100279
280 config_to_encrypt = (
281 {}
282 ) # what keys at config must be encrypted because contains passwords
283 password_to_encrypt = "" # key that contains a password
tiernob24258a2018-10-04 18:39:49 +0200284
tiernobdebce92019-07-01 15:36:49 +0000285 @staticmethod
286 def _create_operation(op_type, params=None):
287 """
288 Creates a dictionary with the information to an operation, similar to ns-lcm-op
289 :param op_type: can be create, edit, delete
290 :param params: operation input parameters
291 :return: new dictionary with
292 """
293 now = time()
294 return {
295 "lcmOperationType": op_type,
296 "operationState": "PROCESSING",
297 "startTime": now,
298 "statusEnteredTime": now,
299 "detailed-status": "",
300 "operationParams": params,
301 }
tiernob24258a2018-10-04 18:39:49 +0200302
tierno65ca36d2019-02-12 19:27:52 +0100303 def check_conflict_on_new(self, session, indata):
tiernobdebce92019-07-01 15:36:49 +0000304 """
305 Check that the data to be inserted is valid. It is checked that name is unique
306 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
307 :param indata: data to be inserted
308 :return: None or raises EngineException
309 """
tiernob24258a2018-10-04 18:39:49 +0200310 self.check_unique_name(session, indata["name"], _id=None)
311
tierno65ca36d2019-02-12 19:27:52 +0100312 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
tiernobdebce92019-07-01 15:36:49 +0000313 """
314 Check that the data to be edited/uploaded is valid. It is checked that name is unique
315 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
316 :param final_content: data once modified. This method may change it.
317 :param edit_content: incremental data that contains the modifications to apply
318 :param _id: internal _id
319 :return: None or raises EngineException
320 """
tierno65ca36d2019-02-12 19:27:52 +0100321 if not session["force"] and edit_content.get("name"):
tiernob24258a2018-10-04 18:39:49 +0200322 self.check_unique_name(session, edit_content["name"], _id=_id)
323
bravofb995ea22021-02-10 10:57:52 -0300324 return final_content
325
tiernobdebce92019-07-01 15:36:49 +0000326 def format_on_edit(self, final_content, edit_content):
327 """
328 Modifies final_content inserting admin information upon edition
329 :param final_content: final content to be stored at database
330 :param edit_content: user requested update content
331 :return: operation id
332 """
delacruzramofe598fe2019-10-23 18:25:11 +0200333 super().format_on_edit(final_content, edit_content)
tiernobdebce92019-07-01 15:36:49 +0000334
tierno92c1c7d2018-11-12 15:22:37 +0100335 # encrypt passwords
336 schema_version = final_content.get("schema_version")
337 if schema_version:
tiernobdebce92019-07-01 15:36:49 +0000338 if edit_content.get(self.password_to_encrypt):
garciadeblas4568a372021-03-24 09:19:48 +0100339 final_content[self.password_to_encrypt] = self.db.encrypt(
340 edit_content[self.password_to_encrypt],
341 schema_version=schema_version,
342 salt=final_content["_id"],
343 )
344 config_to_encrypt_keys = self.config_to_encrypt.get(
345 schema_version
346 ) or self.config_to_encrypt.get("default")
tierno468aa242019-08-01 16:35:04 +0000347 if edit_content.get("config") and config_to_encrypt_keys:
tierno468aa242019-08-01 16:35:04 +0000348 for p in config_to_encrypt_keys:
tierno92c1c7d2018-11-12 15:22:37 +0100349 if edit_content["config"].get(p):
garciadeblas4568a372021-03-24 09:19:48 +0100350 final_content["config"][p] = self.db.encrypt(
351 edit_content["config"][p],
352 schema_version=schema_version,
353 salt=final_content["_id"],
354 )
yshah93909d22024-08-12 09:13:28 +0000355 if edit_content.get("config", {}).get("credentials"):
356 cloud_credentials = edit_content["config"]["credentials"]
357 if cloud_credentials.get("clientSecret"):
358 edit_content["config"]["credentials"][
359 "clientSecret"
360 ] = self.db.encrypt(
361 edit_content["config"]["credentials"]["clientSecret"],
362 schema_version=schema_version,
363 salt=edit_content["_id"],
364 )
365 elif cloud_credentials.get("SecretAccessKey"):
366 edit_content["config"]["credentials"][
367 "SecretAccessKey"
368 ] = self.db.encrypt(
369 edit_content["config"]["credentials"]["SecretAccessKey"],
370 schema_version=schema_version,
371 salt=edit_content["_id"],
372 )
tiernobdebce92019-07-01 15:36:49 +0000373
374 # create edit operation
375 final_content["_admin"]["operations"].append(self._create_operation("edit"))
garciadeblas4568a372021-03-24 09:19:48 +0100376 return "{}:{}".format(
377 final_content["_id"], len(final_content["_admin"]["operations"]) - 1
378 )
tierno92c1c7d2018-11-12 15:22:37 +0100379
380 def format_on_new(self, content, project_id=None, make_public=False):
tiernobdebce92019-07-01 15:36:49 +0000381 """
382 Modifies content descriptor to include _admin and insert create operation
383 :param content: descriptor to be modified
384 :param project_id: if included, it add project read/write permissions. Can be None or a list
385 :param make_public: if included it is generated as public for reading.
386 :return: op_id: operation id on asynchronous operation, None otherwise. In addition content is modified
387 """
388 super().format_on_new(content, project_id=project_id, make_public=make_public)
tierno468aa242019-08-01 16:35:04 +0000389 content["schema_version"] = schema_version = "1.11"
tierno92c1c7d2018-11-12 15:22:37 +0100390
391 # encrypt passwords
tiernobdebce92019-07-01 15:36:49 +0000392 if content.get(self.password_to_encrypt):
garciadeblas4568a372021-03-24 09:19:48 +0100393 content[self.password_to_encrypt] = self.db.encrypt(
394 content[self.password_to_encrypt],
395 schema_version=schema_version,
396 salt=content["_id"],
397 )
398 config_to_encrypt_keys = self.config_to_encrypt.get(
399 schema_version
400 ) or self.config_to_encrypt.get("default")
tierno468aa242019-08-01 16:35:04 +0000401 if content.get("config") and config_to_encrypt_keys:
402 for p in config_to_encrypt_keys:
tierno92c1c7d2018-11-12 15:22:37 +0100403 if content["config"].get(p):
garciadeblas4568a372021-03-24 09:19:48 +0100404 content["config"][p] = self.db.encrypt(
405 content["config"][p],
406 schema_version=schema_version,
407 salt=content["_id"],
408 )
yshah93909d22024-08-12 09:13:28 +0000409 if content.get("config", {}).get("credentials"):
410 cloud_credentials = content["config"]["credentials"]
411 if cloud_credentials.get("clientSecret"):
412 content["config"]["credentials"]["clientSecret"] = self.db.encrypt(
413 content["config"]["credentials"]["clientSecret"],
414 schema_version=schema_version,
415 salt=content["_id"],
416 )
417 elif cloud_credentials.get("SecretAccessKey"):
418 content["config"]["credentials"]["SecretAccessKey"] = self.db.encrypt(
419 content["config"]["credentials"]["SecretAccessKey"],
420 schema_version=schema_version,
421 salt=content["_id"],
422 )
tierno92c1c7d2018-11-12 15:22:37 +0100423
tiernob24258a2018-10-04 18:39:49 +0200424 content["_admin"]["operationalState"] = "PROCESSING"
425
tiernobdebce92019-07-01 15:36:49 +0000426 # create operation
427 content["_admin"]["operations"] = [self._create_operation("create")]
428 content["_admin"]["current_operation"] = None
vijay.rd1eaf982021-05-14 11:54:59 +0000429 # create Resource in Openstack based VIM
430 if content.get("vim_type"):
431 if content["vim_type"] == "openstack":
432 compute = {
garciadeblasf2af4a12023-01-24 16:56:54 +0100433 "ram": {"total": None, "used": None},
434 "vcpus": {"total": None, "used": None},
435 "instances": {"total": None, "used": None},
vijay.rd1eaf982021-05-14 11:54:59 +0000436 }
437 storage = {
garciadeblasf2af4a12023-01-24 16:56:54 +0100438 "volumes": {"total": None, "used": None},
439 "snapshots": {"total": None, "used": None},
440 "storage": {"total": None, "used": None},
vijay.rd1eaf982021-05-14 11:54:59 +0000441 }
442 network = {
garciadeblasf2af4a12023-01-24 16:56:54 +0100443 "networks": {"total": None, "used": None},
444 "subnets": {"total": None, "used": None},
445 "floating_ips": {"total": None, "used": None},
vijay.rd1eaf982021-05-14 11:54:59 +0000446 }
garciadeblasf2af4a12023-01-24 16:56:54 +0100447 content["resources"] = {
448 "compute": compute,
449 "storage": storage,
450 "network": network,
451 }
vijay.rd1eaf982021-05-14 11:54:59 +0000452
tiernobdebce92019-07-01 15:36:49 +0000453 return "{}:0".format(content["_id"])
454
tiernobee3bad2019-12-05 12:26:01 +0000455 def delete(self, session, _id, dry_run=False, not_send_msg=None):
tiernob24258a2018-10-04 18:39:49 +0200456 """
457 Delete item by its internal _id
tierno65ca36d2019-02-12 19:27:52 +0100458 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +0200459 :param _id: server internal id
tiernob24258a2018-10-04 18:39:49 +0200460 :param dry_run: make checking but do not delete
tiernobee3bad2019-12-05 12:26:01 +0000461 :param not_send_msg: To not send message (False) or store content (list) instead
tiernobdebce92019-07-01 15:36:49 +0000462 :return: operation id if it is ordered to delete. None otherwise
tiernob24258a2018-10-04 18:39:49 +0200463 """
tiernobdebce92019-07-01 15:36:49 +0000464
465 filter_q = self._get_project_filter(session)
466 filter_q["_id"] = _id
467 db_content = self.db.get_one(self.topic, filter_q)
468
469 self.check_conflict_on_del(session, _id, db_content)
470 if dry_run:
471 return None
472
tiernof5f2e3f2020-03-23 14:42:10 +0000473 # remove reference from project_read if there are more projects referencing it. If it last one,
474 # do not remove reference, but order via kafka to delete it
selvi.ja5e05112023-04-28 11:00:21 +0000475 if session["project_id"]:
garciadeblas4568a372021-03-24 09:19:48 +0100476 other_projects_referencing = next(
477 (
478 p
479 for p in db_content["_admin"]["projects_read"]
480 if p not in session["project_id"] and p != "ANY"
481 ),
482 None,
483 )
tiernobdebce92019-07-01 15:36:49 +0000484
tiernof5f2e3f2020-03-23 14:42:10 +0000485 # check if there are projects referencing it (apart from ANY, that means, public)....
486 if other_projects_referencing:
487 # remove references but not delete
garciadeblas4568a372021-03-24 09:19:48 +0100488 update_dict_pull = {
489 "_admin.projects_read": session["project_id"],
490 "_admin.projects_write": session["project_id"],
491 }
492 self.db.set_one(
493 self.topic, filter_q, update_dict=None, pull_list=update_dict_pull
494 )
tiernof5f2e3f2020-03-23 14:42:10 +0000495 return None
496 else:
garciadeblas4568a372021-03-24 09:19:48 +0100497 can_write = next(
498 (
499 p
500 for p in db_content["_admin"]["projects_write"]
501 if p == "ANY" or p in session["project_id"]
502 ),
503 None,
504 )
tiernof5f2e3f2020-03-23 14:42:10 +0000505 if not can_write:
garciadeblas4568a372021-03-24 09:19:48 +0100506 raise EngineException(
507 "You have not write permission to delete it",
508 http_code=HTTPStatus.UNAUTHORIZED,
509 )
tiernobdebce92019-07-01 15:36:49 +0000510
511 # It must be deleted
512 if session["force"]:
513 self.db.del_one(self.topic, {"_id": _id})
514 op_id = None
garciadeblas4568a372021-03-24 09:19:48 +0100515 self._send_msg(
516 "deleted", {"_id": _id, "op_id": op_id}, not_send_msg=not_send_msg
517 )
tiernobdebce92019-07-01 15:36:49 +0000518 else:
tiernof5f2e3f2020-03-23 14:42:10 +0000519 update_dict = {"_admin.to_delete": True}
garciadeblas4568a372021-03-24 09:19:48 +0100520 self.db.set_one(
521 self.topic,
522 {"_id": _id},
523 update_dict=update_dict,
524 push={"_admin.operations": self._create_operation("delete")},
525 )
tiernobdebce92019-07-01 15:36:49 +0000526 # the number of operations is the operation_id. db_content does not contains the new operation inserted,
527 # so the -1 is not needed
garciadeblas4568a372021-03-24 09:19:48 +0100528 op_id = "{}:{}".format(
529 db_content["_id"], len(db_content["_admin"]["operations"])
530 )
531 self._send_msg(
532 "delete", {"_id": _id, "op_id": op_id}, not_send_msg=not_send_msg
533 )
tiernobdebce92019-07-01 15:36:49 +0000534 return op_id
tiernob24258a2018-10-04 18:39:49 +0200535
536
tiernobdebce92019-07-01 15:36:49 +0000537class VimAccountTopic(CommonVimWimSdn):
538 topic = "vim_accounts"
539 topic_msg = "vim_account"
540 schema_new = vim_account_new_schema
541 schema_edit = vim_account_edit_schema
542 multiproject = True
543 password_to_encrypt = "vim_password"
garciadeblas4568a372021-03-24 09:19:48 +0100544 config_to_encrypt = {
545 "1.1": ("admin_password", "nsx_password", "vcenter_password"),
546 "default": (
547 "admin_password",
548 "nsx_password",
549 "vcenter_password",
550 "vrops_password",
551 ),
552 }
tiernobdebce92019-07-01 15:36:49 +0000553
delacruzramo35c998b2019-11-21 11:09:16 +0100554 def check_conflict_on_del(self, session, _id, db_content):
555 """
556 Check if deletion can be done because of dependencies if it is not force. To override
557 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
558 :param _id: internal _id
559 :param db_content: The database content of this item _id
560 :return: None if ok or raises EngineException with the conflict
561 """
562 if session["force"]:
563 return
564 # check if used by VNF
565 if self.db.get_list("vnfrs", {"vim-account-id": _id}):
garciadeblas4568a372021-03-24 09:19:48 +0100566 raise EngineException(
567 "There is at least one VNF using this VIM account",
568 http_code=HTTPStatus.CONFLICT,
569 )
delacruzramo35c998b2019-11-21 11:09:16 +0100570 super().check_conflict_on_del(session, _id, db_content)
571
tiernobdebce92019-07-01 15:36:49 +0000572
573class WimAccountTopic(CommonVimWimSdn):
tierno55ba2e62018-12-11 17:22:22 +0000574 topic = "wim_accounts"
575 topic_msg = "wim_account"
576 schema_new = wim_account_new_schema
577 schema_edit = wim_account_edit_schema
tierno65ca36d2019-02-12 19:27:52 +0100578 multiproject = True
gifrerenom44f5ec12022-03-07 16:57:25 +0000579 password_to_encrypt = "password"
tierno468aa242019-08-01 16:35:04 +0000580 config_to_encrypt = {}
tierno55ba2e62018-12-11 17:22:22 +0000581
582
tiernobdebce92019-07-01 15:36:49 +0000583class SdnTopic(CommonVimWimSdn):
tiernob24258a2018-10-04 18:39:49 +0200584 topic = "sdns"
585 topic_msg = "sdn"
tierno6b02b052020-06-02 10:07:41 +0000586 quota_name = "sdn_controllers"
tiernob24258a2018-10-04 18:39:49 +0200587 schema_new = sdn_new_schema
588 schema_edit = sdn_edit_schema
tierno65ca36d2019-02-12 19:27:52 +0100589 multiproject = True
tiernobdebce92019-07-01 15:36:49 +0000590 password_to_encrypt = "password"
tierno468aa242019-08-01 16:35:04 +0000591 config_to_encrypt = {}
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100592
tierno7adaeb02019-12-17 16:46:12 +0000593 def _obtain_url(self, input, create):
594 if input.get("ip") or input.get("port"):
garciadeblas4568a372021-03-24 09:19:48 +0100595 if not input.get("ip") or not input.get("port") or input.get("url"):
596 raise ValidationError(
597 "You must provide both 'ip' and 'port' (deprecated); or just 'url' (prefered)"
598 )
599 input["url"] = "http://{}:{}/".format(input["ip"], input["port"])
tierno7adaeb02019-12-17 16:46:12 +0000600 del input["ip"]
601 del input["port"]
garciadeblas4568a372021-03-24 09:19:48 +0100602 elif create and not input.get("url"):
tierno7adaeb02019-12-17 16:46:12 +0000603 raise ValidationError("You must provide 'url'")
604 return input
605
606 def _validate_input_new(self, input, force=False):
607 input = super()._validate_input_new(input, force)
608 return self._obtain_url(input, True)
609
Frank Brydendeba68e2020-07-27 13:55:11 +0000610 def _validate_input_edit(self, input, content, force=False):
611 input = super()._validate_input_edit(input, content, force)
tierno7adaeb02019-12-17 16:46:12 +0000612 return self._obtain_url(input, False)
613
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100614
delacruzramofe598fe2019-10-23 18:25:11 +0200615class K8sClusterTopic(CommonVimWimSdn):
616 topic = "k8sclusters"
617 topic_msg = "k8scluster"
618 schema_new = k8scluster_new_schema
619 schema_edit = k8scluster_edit_schema
620 multiproject = True
621 password_to_encrypt = None
622 config_to_encrypt = {}
623
624 def format_on_new(self, content, project_id=None, make_public=False):
625 oid = super().format_on_new(content, project_id, make_public)
garciadeblas4568a372021-03-24 09:19:48 +0100626 self.db.encrypt_decrypt_fields(
627 content["credentials"],
628 "encrypt",
629 ["password", "secret"],
630 schema_version=content["schema_version"],
631 salt=content["_id"],
632 )
delacruzramoc2d5fc62020-02-05 11:50:21 +0000633 # Add Helm/Juju Repo lists
634 repos = {"helm-chart": [], "juju-bundle": []}
635 for proj in content["_admin"]["projects_read"]:
garciadeblas4568a372021-03-24 09:19:48 +0100636 if proj != "ANY":
637 for repo in self.db.get_list(
638 "k8srepos", {"_admin.projects_read": proj}
639 ):
delacruzramoc2d5fc62020-02-05 11:50:21 +0000640 if repo["_id"] not in repos[repo["type"]]:
641 repos[repo["type"]].append(repo["_id"])
642 for k in repos:
garciadeblas4568a372021-03-24 09:19:48 +0100643 content["_admin"][k.replace("-", "_") + "_repos"] = repos[k]
delacruzramofe598fe2019-10-23 18:25:11 +0200644 return oid
645
646 def format_on_edit(self, final_content, edit_content):
647 if final_content.get("schema_version") and edit_content.get("credentials"):
garciadeblas4568a372021-03-24 09:19:48 +0100648 self.db.encrypt_decrypt_fields(
649 edit_content["credentials"],
650 "encrypt",
651 ["password", "secret"],
652 schema_version=final_content["schema_version"],
653 salt=final_content["_id"],
654 )
655 deep_update_rfc7396(
656 final_content["credentials"], edit_content["credentials"]
657 )
delacruzramofe598fe2019-10-23 18:25:11 +0200658 oid = super().format_on_edit(final_content, edit_content)
659 return oid
660
delacruzramoc2d5fc62020-02-05 11:50:21 +0000661 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
garciadeblas4568a372021-03-24 09:19:48 +0100662 final_content = super(CommonVimWimSdn, self).check_conflict_on_edit(
663 session, final_content, edit_content, _id
664 )
665 final_content = super().check_conflict_on_edit(
666 session, final_content, edit_content, _id
667 )
delacruzramoc2d5fc62020-02-05 11:50:21 +0000668 # Update Helm/Juju Repo lists
669 repos = {"helm-chart": [], "juju-bundle": []}
670 for proj in session.get("set_project", []):
garciadeblas4568a372021-03-24 09:19:48 +0100671 if proj != "ANY":
672 for repo in self.db.get_list(
673 "k8srepos", {"_admin.projects_read": proj}
674 ):
delacruzramoc2d5fc62020-02-05 11:50:21 +0000675 if repo["_id"] not in repos[repo["type"]]:
676 repos[repo["type"]].append(repo["_id"])
677 for k in repos:
garciadeblas4568a372021-03-24 09:19:48 +0100678 rlist = k.replace("-", "_") + "_repos"
delacruzramoc2d5fc62020-02-05 11:50:21 +0000679 if rlist not in final_content["_admin"]:
680 final_content["_admin"][rlist] = []
681 final_content["_admin"][rlist] += repos[k]
bravofb995ea22021-02-10 10:57:52 -0300682 return final_content
delacruzramoc2d5fc62020-02-05 11:50:21 +0000683
tiernoe19707b2020-04-21 13:08:04 +0000684 def check_conflict_on_del(self, session, _id, db_content):
685 """
686 Check if deletion can be done because of dependencies if it is not force. To override
687 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
688 :param _id: internal _id
689 :param db_content: The database content of this item _id
690 :return: None if ok or raises EngineException with the conflict
691 """
692 if session["force"]:
693 return
694 # check if used by VNF
695 filter_q = {"kdur.k8s-cluster.id": _id}
696 if session["project_id"]:
697 filter_q["_admin.projects_read.cont"] = session["project_id"]
698 if self.db.get_list("vnfrs", filter_q):
garciadeblas4568a372021-03-24 09:19:48 +0100699 raise EngineException(
700 "There is at least one VNF using this k8scluster",
701 http_code=HTTPStatus.CONFLICT,
702 )
tiernoe19707b2020-04-21 13:08:04 +0000703 super().check_conflict_on_del(session, _id, db_content)
704
delacruzramofe598fe2019-10-23 18:25:11 +0200705
David Garciaecb41322021-03-31 19:10:46 +0200706class VcaTopic(CommonVimWimSdn):
707 topic = "vca"
708 topic_msg = "vca"
709 schema_new = vca_new_schema
710 schema_edit = vca_edit_schema
711 multiproject = True
712 password_to_encrypt = None
713
714 def format_on_new(self, content, project_id=None, make_public=False):
715 oid = super().format_on_new(content, project_id, make_public)
716 content["schema_version"] = schema_version = "1.11"
717 for key in ["secret", "cacert"]:
718 content[key] = self.db.encrypt(
garciadeblas4568a372021-03-24 09:19:48 +0100719 content[key], schema_version=schema_version, salt=content["_id"]
David Garciaecb41322021-03-31 19:10:46 +0200720 )
721 return oid
722
723 def format_on_edit(self, final_content, edit_content):
724 oid = super().format_on_edit(final_content, edit_content)
725 schema_version = final_content.get("schema_version")
726 for key in ["secret", "cacert"]:
727 if key in edit_content:
728 final_content[key] = self.db.encrypt(
729 edit_content[key],
730 schema_version=schema_version,
garciadeblas4568a372021-03-24 09:19:48 +0100731 salt=final_content["_id"],
David Garciaecb41322021-03-31 19:10:46 +0200732 )
733 return oid
734
735 def check_conflict_on_del(self, session, _id, db_content):
736 """
737 Check if deletion can be done because of dependencies if it is not force. To override
738 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
739 :param _id: internal _id
740 :param db_content: The database content of this item _id
741 :return: None if ok or raises EngineException with the conflict
742 """
743 if session["force"]:
744 return
745 # check if used by VNF
746 filter_q = {"vca": _id}
747 if session["project_id"]:
748 filter_q["_admin.projects_read.cont"] = session["project_id"]
749 if self.db.get_list("vim_accounts", filter_q):
garciadeblas4568a372021-03-24 09:19:48 +0100750 raise EngineException(
751 "There is at least one VIM account using this vca",
752 http_code=HTTPStatus.CONFLICT,
753 )
David Garciaecb41322021-03-31 19:10:46 +0200754 super().check_conflict_on_del(session, _id, db_content)
755
756
delacruzramofe598fe2019-10-23 18:25:11 +0200757class K8sRepoTopic(CommonVimWimSdn):
758 topic = "k8srepos"
759 topic_msg = "k8srepo"
760 schema_new = k8srepo_new_schema
761 schema_edit = k8srepo_edit_schema
762 multiproject = True
763 password_to_encrypt = None
764 config_to_encrypt = {}
765
delacruzramoc2d5fc62020-02-05 11:50:21 +0000766 def format_on_new(self, content, project_id=None, make_public=False):
767 oid = super().format_on_new(content, project_id, make_public)
768 # Update Helm/Juju Repo lists
garciadeblas4568a372021-03-24 09:19:48 +0100769 repo_list = content["type"].replace("-", "_") + "_repos"
delacruzramoc2d5fc62020-02-05 11:50:21 +0000770 for proj in content["_admin"]["projects_read"]:
garciadeblas4568a372021-03-24 09:19:48 +0100771 if proj != "ANY":
772 self.db.set_list(
773 "k8sclusters",
774 {
775 "_admin.projects_read": proj,
776 "_admin." + repo_list + ".ne": content["_id"],
777 },
778 {},
779 push={"_admin." + repo_list: content["_id"]},
780 )
delacruzramoc2d5fc62020-02-05 11:50:21 +0000781 return oid
782
783 def delete(self, session, _id, dry_run=False, not_send_msg=None):
784 type = self.db.get_one("k8srepos", {"_id": _id})["type"]
785 oid = super().delete(session, _id, dry_run, not_send_msg)
786 if oid:
787 # Remove from Helm/Juju Repo lists
garciadeblas4568a372021-03-24 09:19:48 +0100788 repo_list = type.replace("-", "_") + "_repos"
789 self.db.set_list(
790 "k8sclusters",
791 {"_admin." + repo_list: _id},
792 {},
793 pull={"_admin." + repo_list: _id},
794 )
delacruzramoc2d5fc62020-02-05 11:50:21 +0000795 return oid
796
delacruzramofe598fe2019-10-23 18:25:11 +0200797
Felipe Vicensb66b0412020-05-06 10:11:00 +0200798class OsmRepoTopic(BaseTopic):
799 topic = "osmrepos"
800 topic_msg = "osmrepos"
801 schema_new = osmrepo_new_schema
802 schema_edit = osmrepo_edit_schema
803 multiproject = True
804 # TODO: Implement user/password
805
806
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100807class UserTopicAuth(UserTopic):
tierno65ca36d2019-02-12 19:27:52 +0100808 # topic = "users"
agarwalat53471982020-10-08 13:06:14 +0000809 topic_msg = "users"
Eduardo Sousaa16a4fa2019-05-23 01:41:18 +0100810 schema_new = user_new_schema
811 schema_edit = user_edit_schema
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100812
813 def __init__(self, db, fs, msg, auth):
delacruzramo32bab472019-09-13 12:24:22 +0200814 UserTopic.__init__(self, db, fs, msg, auth)
815 # self.auth = auth
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100816
tierno65ca36d2019-02-12 19:27:52 +0100817 def check_conflict_on_new(self, session, indata):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100818 """
819 Check that the data to be inserted is valid
820
tierno65ca36d2019-02-12 19:27:52 +0100821 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100822 :param indata: data to be inserted
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100823 :return: None or raises EngineException
824 """
825 username = indata.get("username")
tiernocf042d32019-06-13 09:06:40 +0000826 if is_valid_uuid(username):
garciadeblas4568a372021-03-24 09:19:48 +0100827 raise EngineException(
828 "username '{}' cannot have a uuid format".format(username),
829 HTTPStatus.UNPROCESSABLE_ENTITY,
830 )
tiernocf042d32019-06-13 09:06:40 +0000831
832 # Check that username is not used, regardless keystone already checks this
833 if self.auth.get_user_list(filter_q={"name": username}):
garciadeblas4568a372021-03-24 09:19:48 +0100834 raise EngineException(
835 "username '{}' is already used".format(username), HTTPStatus.CONFLICT
836 )
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100837
Eduardo Sousa339ed782019-05-28 14:25:00 +0100838 if "projects" in indata.keys():
tierno701018c2019-06-25 11:13:14 +0000839 # convert to new format project_role_mappings
delacruzramo01b15d32019-07-02 14:37:47 +0200840 role = self.auth.get_role_list({"name": "project_admin"})
841 if not role:
842 role = self.auth.get_role_list()
843 if not role:
garciadeblas4568a372021-03-24 09:19:48 +0100844 raise AuthconnNotFoundException(
845 "Can't find default role for user '{}'".format(username)
846 )
delacruzramo01b15d32019-07-02 14:37:47 +0200847 rid = role[0]["_id"]
tierno701018c2019-06-25 11:13:14 +0000848 if not indata.get("project_role_mappings"):
849 indata["project_role_mappings"] = []
850 for project in indata["projects"]:
delacruzramo01b15d32019-07-02 14:37:47 +0200851 pid = self.auth.get_project(project)["_id"]
852 prm = {"project": pid, "role": rid}
853 if prm not in indata["project_role_mappings"]:
854 indata["project_role_mappings"].append(prm)
tierno701018c2019-06-25 11:13:14 +0000855 # raise EngineException("Format invalid: the keyword 'projects' is not allowed for keystone authentication",
856 # HTTPStatus.BAD_REQUEST)
Eduardo Sousa339ed782019-05-28 14:25:00 +0100857
tierno65ca36d2019-02-12 19:27:52 +0100858 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100859 """
860 Check that the data to be edited/uploaded is valid
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 final_content: data once modified
864 :param edit_content: incremental data that contains the modifications to apply
865 :param _id: internal _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100866 :return: None or raises EngineException
867 """
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100868
tiernocf042d32019-06-13 09:06:40 +0000869 if "username" in edit_content:
870 username = edit_content.get("username")
871 if is_valid_uuid(username):
garciadeblas4568a372021-03-24 09:19:48 +0100872 raise EngineException(
873 "username '{}' cannot have an uuid format".format(username),
874 HTTPStatus.UNPROCESSABLE_ENTITY,
875 )
tiernocf042d32019-06-13 09:06:40 +0000876
877 # Check that username is not used, regardless keystone already checks this
878 if self.auth.get_user_list(filter_q={"name": username}):
garciadeblas4568a372021-03-24 09:19:48 +0100879 raise EngineException(
880 "username '{}' is already used".format(username),
881 HTTPStatus.CONFLICT,
882 )
tiernocf042d32019-06-13 09:06:40 +0000883
884 if final_content["username"] == "admin":
885 for mapping in edit_content.get("remove_project_role_mappings", ()):
garciadeblas4568a372021-03-24 09:19:48 +0100886 if mapping["project"] == "admin" and mapping.get("role") in (
887 None,
888 "system_admin",
889 ):
tiernocf042d32019-06-13 09:06:40 +0000890 # TODO make this also available for project id and role id
garciadeblas4568a372021-03-24 09:19:48 +0100891 raise EngineException(
892 "You cannot remove system_admin role from admin user",
893 http_code=HTTPStatus.FORBIDDEN,
894 )
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100895
bravofb995ea22021-02-10 10:57:52 -0300896 return final_content
897
tiernob4844ab2019-05-23 08:42:12 +0000898 def check_conflict_on_del(self, session, _id, db_content):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100899 """
900 Check if deletion can be done because of dependencies if it is not force. To override
tierno65ca36d2019-02-12 19:27:52 +0100901 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100902 :param _id: internal _id
tiernob4844ab2019-05-23 08:42:12 +0000903 :param db_content: The database content of this item _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100904 :return: None if ok or raises EngineException with the conflict
905 """
tiernocf042d32019-06-13 09:06:40 +0000906 if db_content["username"] == session["username"]:
garciadeblas4568a372021-03-24 09:19:48 +0100907 raise EngineException(
908 "You cannot delete your own login user ", http_code=HTTPStatus.CONFLICT
909 )
delacruzramo01b15d32019-07-02 14:37:47 +0200910 # TODO: Check that user is not logged in ? How? (Would require listing current tokens)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100911
Eduardo Sousaa16a4fa2019-05-23 01:41:18 +0100912 @staticmethod
913 def format_on_show(content):
914 """
Eduardo Sousa44603902019-06-04 08:10:32 +0100915 Modifies the content of the role information to separate the role
Eduardo Sousaa16a4fa2019-05-23 01:41:18 +0100916 metadata from the role definition.
917 """
918 project_role_mappings = []
919
delacruzramo01b15d32019-07-02 14:37:47 +0200920 if "projects" in content:
921 for project in content["projects"]:
922 for role in project["roles"]:
garciadeblas4568a372021-03-24 09:19:48 +0100923 project_role_mappings.append(
924 {
925 "project": project["_id"],
926 "project_name": project["name"],
927 "role": role["_id"],
928 "role_name": role["name"],
929 }
930 )
delacruzramo01b15d32019-07-02 14:37:47 +0200931 del content["projects"]
Eduardo Sousaa16a4fa2019-05-23 01:41:18 +0100932 content["project_role_mappings"] = project_role_mappings
933
Eduardo Sousa0b1d61b2019-05-30 19:55:52 +0100934 return content
935
tierno65ca36d2019-02-12 19:27:52 +0100936 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100937 """
938 Creates a new entry into the authentication backend.
939
940 NOTE: Overrides BaseTopic functionality because it doesn't require access to database.
941
942 :param rollback: list to append created items at database in case a rollback may to be done
tierno65ca36d2019-02-12 19:27:52 +0100943 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100944 :param indata: data to be inserted
945 :param kwargs: used to override the indata descriptor
946 :param headers: http request headers
delacruzramo01b15d32019-07-02 14:37:47 +0200947 :return: _id: identity of the inserted data, operation _id (None)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100948 """
949 try:
950 content = BaseTopic._remove_envelop(indata)
951
952 # Override descriptor with query string kwargs
953 BaseTopic._update_input_with_kwargs(content, kwargs)
tierno65ca36d2019-02-12 19:27:52 +0100954 content = self._validate_input_new(content, session["force"])
955 self.check_conflict_on_new(session, content)
tiernocf042d32019-06-13 09:06:40 +0000956 # self.format_on_new(content, session["project_id"], make_public=session["public"])
delacruzramo01b15d32019-07-02 14:37:47 +0200957 now = time()
958 content["_admin"] = {"created": now, "modified": now}
959 prms = []
960 for prm in content.get("project_role_mappings", []):
961 proj = self.auth.get_project(prm["project"], not session["force"])
962 role = self.auth.get_role(prm["role"], not session["force"])
963 pid = proj["_id"] if proj else None
964 rid = role["_id"] if role else None
965 prl = {"project": pid, "role": rid}
966 if prl not in prms:
967 prms.append(prl)
968 content["project_role_mappings"] = prms
969 # _id = self.auth.create_user(content["username"], content["password"])["_id"]
970 _id = self.auth.create_user(content)["_id"]
Eduardo Sousa44603902019-06-04 08:10:32 +0100971
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100972 rollback.append({"topic": self.topic, "_id": _id})
tiernocf042d32019-06-13 09:06:40 +0000973 # del content["password"]
agarwalat53471982020-10-08 13:06:14 +0000974 self._send_msg("created", content, not_send_msg=None)
delacruzramo01b15d32019-07-02 14:37:47 +0200975 return _id, None
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100976 except ValidationError as e:
977 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
978
K Sai Kiran57589552021-01-27 21:38:34 +0530979 def show(self, session, _id, filter_q=None, api_req=False):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100980 """
981 Get complete information on an topic
982
tierno65ca36d2019-02-12 19:27:52 +0100983 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tierno5ec768a2020-03-31 09:46:44 +0000984 :param _id: server internal id or username
K Sai Kiran57589552021-01-27 21:38:34 +0530985 :param filter_q: dict: query parameter
K Sai Kirand010e3e2020-08-28 15:11:48 +0530986 :param api_req: True if this call is serving an external API request. False if serving internal request.
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100987 :return: dictionary, raise exception if not found.
988 """
tiernocf042d32019-06-13 09:06:40 +0000989 # Allow _id to be a name or uuid
tiernoad6d5332020-02-19 14:29:49 +0000990 filter_q = {"username": _id}
delacruzramo029405d2019-09-26 10:52:56 +0200991 # users = self.auth.get_user_list(filter_q)
garciadeblas4568a372021-03-24 09:19:48 +0100992 users = self.list(session, filter_q) # To allow default filtering (Bug 853)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100993 if len(users) == 1:
tierno1546f2a2019-08-20 15:38:11 +0000994 return users[0]
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100995 elif len(users) > 1:
garciadeblas4568a372021-03-24 09:19:48 +0100996 raise EngineException(
997 "Too many users found for '{}'".format(_id), HTTPStatus.CONFLICT
998 )
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100999 else:
garciadeblas4568a372021-03-24 09:19:48 +01001000 raise EngineException(
1001 "User '{}' not found".format(_id), HTTPStatus.NOT_FOUND
1002 )
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001003
tierno65ca36d2019-02-12 19:27:52 +01001004 def edit(self, session, _id, indata=None, kwargs=None, content=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001005 """
1006 Updates an user entry.
1007
tierno65ca36d2019-02-12 19:27:52 +01001008 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001009 :param _id:
1010 :param indata: data to be inserted
1011 :param kwargs: used to override the indata descriptor
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001012 :param content:
1013 :return: _id: identity of the inserted data.
1014 """
1015 indata = self._remove_envelop(indata)
1016
1017 # Override descriptor with query string kwargs
1018 if kwargs:
1019 BaseTopic._update_input_with_kwargs(indata, kwargs)
1020 try:
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001021 if not content:
1022 content = self.show(session, _id)
Frank Brydendeba68e2020-07-27 13:55:11 +00001023 indata = self._validate_input_edit(indata, content, force=session["force"])
bravofb995ea22021-02-10 10:57:52 -03001024 content = self.check_conflict_on_edit(session, content, indata, _id=_id)
tiernocf042d32019-06-13 09:06:40 +00001025 # self.format_on_edit(content, indata)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001026
garciadeblas4568a372021-03-24 09:19:48 +01001027 if not (
1028 "password" in indata
1029 or "username" in indata
1030 or indata.get("remove_project_role_mappings")
1031 or indata.get("add_project_role_mappings")
1032 or indata.get("project_role_mappings")
1033 or indata.get("projects")
1034 or indata.get("add_projects")
garciadeblas6d83f8f2023-06-19 22:34:49 +02001035 or indata.get("unlock")
1036 or indata.get("renew")
garciadeblas4568a372021-03-24 09:19:48 +01001037 ):
tiernocf042d32019-06-13 09:06:40 +00001038 return _id
garciadeblas4568a372021-03-24 09:19:48 +01001039 if indata.get("project_role_mappings") and (
1040 indata.get("remove_project_role_mappings")
1041 or indata.get("add_project_role_mappings")
1042 ):
1043 raise EngineException(
1044 "Option 'project_role_mappings' is incompatible with 'add_project_role_mappings"
1045 "' or 'remove_project_role_mappings'",
1046 http_code=HTTPStatus.BAD_REQUEST,
1047 )
Eduardo Sousa44603902019-06-04 08:10:32 +01001048
delacruzramo01b15d32019-07-02 14:37:47 +02001049 if indata.get("projects") or indata.get("add_projects"):
1050 role = self.auth.get_role_list({"name": "project_admin"})
1051 if not role:
1052 role = self.auth.get_role_list()
1053 if not role:
garciadeblas4568a372021-03-24 09:19:48 +01001054 raise AuthconnNotFoundException(
1055 "Can't find a default role for user '{}'".format(
1056 content["username"]
1057 )
1058 )
delacruzramo01b15d32019-07-02 14:37:47 +02001059 rid = role[0]["_id"]
1060 if "add_project_role_mappings" not in indata:
1061 indata["add_project_role_mappings"] = []
tierno1546f2a2019-08-20 15:38:11 +00001062 if "remove_project_role_mappings" not in indata:
1063 indata["remove_project_role_mappings"] = []
1064 if isinstance(indata.get("projects"), dict):
1065 # backward compatible
1066 for k, v in indata["projects"].items():
1067 if k.startswith("$") and v is None:
garciadeblas4568a372021-03-24 09:19:48 +01001068 indata["remove_project_role_mappings"].append(
1069 {"project": k[1:]}
1070 )
tierno1546f2a2019-08-20 15:38:11 +00001071 elif k.startswith("$+"):
garciadeblas4568a372021-03-24 09:19:48 +01001072 indata["add_project_role_mappings"].append(
1073 {"project": v, "role": rid}
1074 )
tierno1546f2a2019-08-20 15:38:11 +00001075 del indata["projects"]
delacruzramo01b15d32019-07-02 14:37:47 +02001076 for proj in indata.get("projects", []) + indata.get("add_projects", []):
garciadeblas4568a372021-03-24 09:19:48 +01001077 indata["add_project_role_mappings"].append(
1078 {"project": proj, "role": rid}
1079 )
delacruzramo01b15d32019-07-02 14:37:47 +02001080
1081 # user = self.show(session, _id) # Already in 'content'
1082 original_mapping = content["project_role_mappings"]
Eduardo Sousa44603902019-06-04 08:10:32 +01001083
tiernocf042d32019-06-13 09:06:40 +00001084 mappings_to_add = []
1085 mappings_to_remove = []
Eduardo Sousa44603902019-06-04 08:10:32 +01001086
tiernocf042d32019-06-13 09:06:40 +00001087 # remove
1088 for to_remove in indata.get("remove_project_role_mappings", ()):
1089 for mapping in original_mapping:
garciadeblas4568a372021-03-24 09:19:48 +01001090 if to_remove["project"] in (
1091 mapping["project"],
1092 mapping["project_name"],
1093 ):
1094 if not to_remove.get("role") or to_remove["role"] in (
1095 mapping["role"],
1096 mapping["role_name"],
1097 ):
tiernocf042d32019-06-13 09:06:40 +00001098 mappings_to_remove.append(mapping)
Eduardo Sousa44603902019-06-04 08:10:32 +01001099
tiernocf042d32019-06-13 09:06:40 +00001100 # add
1101 for to_add in indata.get("add_project_role_mappings", ()):
1102 for mapping in original_mapping:
garciadeblas4568a372021-03-24 09:19:48 +01001103 if to_add["project"] in (
1104 mapping["project"],
1105 mapping["project_name"],
1106 ) and to_add["role"] in (
1107 mapping["role"],
1108 mapping["role_name"],
1109 ):
garciadeblas4568a372021-03-24 09:19:48 +01001110 if mapping in mappings_to_remove: # do not remove
tiernocf042d32019-06-13 09:06:40 +00001111 mappings_to_remove.remove(mapping)
1112 break # do not add, it is already at user
1113 else:
delacruzramo01b15d32019-07-02 14:37:47 +02001114 pid = self.auth.get_project(to_add["project"])["_id"]
1115 rid = self.auth.get_role(to_add["role"])["_id"]
1116 mappings_to_add.append({"project": pid, "role": rid})
tiernocf042d32019-06-13 09:06:40 +00001117
1118 # set
1119 if indata.get("project_role_mappings"):
1120 for to_set in indata["project_role_mappings"]:
1121 for mapping in original_mapping:
garciadeblas4568a372021-03-24 09:19:48 +01001122 if to_set["project"] in (
1123 mapping["project"],
1124 mapping["project_name"],
1125 ) and to_set["role"] in (
1126 mapping["role"],
1127 mapping["role_name"],
1128 ):
1129 if mapping in mappings_to_remove: # do not remove
tiernocf042d32019-06-13 09:06:40 +00001130 mappings_to_remove.remove(mapping)
1131 break # do not add, it is already at user
1132 else:
delacruzramo01b15d32019-07-02 14:37:47 +02001133 pid = self.auth.get_project(to_set["project"])["_id"]
1134 rid = self.auth.get_role(to_set["role"])["_id"]
1135 mappings_to_add.append({"project": pid, "role": rid})
tiernocf042d32019-06-13 09:06:40 +00001136 for mapping in original_mapping:
1137 for to_set in indata["project_role_mappings"]:
garciadeblas4568a372021-03-24 09:19:48 +01001138 if to_set["project"] in (
1139 mapping["project"],
1140 mapping["project_name"],
1141 ) and to_set["role"] in (
1142 mapping["role"],
1143 mapping["role_name"],
1144 ):
tiernocf042d32019-06-13 09:06:40 +00001145 break
1146 else:
1147 # delete
garciadeblas4568a372021-03-24 09:19:48 +01001148 if mapping not in mappings_to_remove: # do not remove
tiernocf042d32019-06-13 09:06:40 +00001149 mappings_to_remove.append(mapping)
1150
garciadeblas4568a372021-03-24 09:19:48 +01001151 self.auth.update_user(
1152 {
1153 "_id": _id,
1154 "username": indata.get("username"),
1155 "password": indata.get("password"),
selvi.ja9a1fc82022-04-04 06:54:30 +00001156 "old_password": indata.get("old_password"),
garciadeblas4568a372021-03-24 09:19:48 +01001157 "add_project_role_mappings": mappings_to_add,
1158 "remove_project_role_mappings": mappings_to_remove,
garciadeblas6d83f8f2023-06-19 22:34:49 +02001159 "system_admin_id": indata.get("system_admin_id"),
1160 "unlock": indata.get("unlock"),
1161 "renew": indata.get("renew"),
garciadeblasf53612b2024-07-12 14:44:37 +02001162 "session_user": session.get("username"),
garciadeblas4568a372021-03-24 09:19:48 +01001163 }
1164 )
1165 data_to_send = {"_id": _id, "changes": indata}
agarwalat53471982020-10-08 13:06:14 +00001166 self._send_msg("edited", data_to_send, not_send_msg=None)
tiernocf042d32019-06-13 09:06:40 +00001167
delacruzramo01b15d32019-07-02 14:37:47 +02001168 # return _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001169 except ValidationError as e:
1170 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1171
tiernoc4e07d02020-08-14 14:25:32 +00001172 def list(self, session, filter_q=None, api_req=False):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001173 """
1174 Get a list of the topic that matches a filter
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 filter_q: filter of data to be applied
K Sai Kirand010e3e2020-08-28 15:11:48 +05301177 :param api_req: True if this call is serving an external API request. False if serving internal request.
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001178 :return: The list, it can be empty if no one match the filter.
1179 """
delacruzramo029405d2019-09-26 10:52:56 +02001180 user_list = self.auth.get_user_list(filter_q)
1181 if not session["allow_show_user_project_role"]:
1182 # Bug 853 - Default filtering
garciadeblas4568a372021-03-24 09:19:48 +01001183 user_list = [
1184 usr for usr in user_list if usr["username"] == session["username"]
1185 ]
delacruzramo029405d2019-09-26 10:52:56 +02001186 return user_list
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001187
tiernobee3bad2019-12-05 12:26:01 +00001188 def delete(self, session, _id, dry_run=False, not_send_msg=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001189 """
1190 Delete item by its internal _id
1191
tierno65ca36d2019-02-12 19:27:52 +01001192 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001193 :param _id: server internal id
1194 :param force: indicates if deletion must be forced in case of conflict
1195 :param dry_run: make checking but do not delete
tiernobee3bad2019-12-05 12:26:01 +00001196 :param not_send_msg: To not send message (False) or store content (list) instead
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001197 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
1198 """
tiernocf042d32019-06-13 09:06:40 +00001199 # Allow _id to be a name or uuid
delacruzramo01b15d32019-07-02 14:37:47 +02001200 user = self.auth.get_user(_id)
1201 uid = user["_id"]
1202 self.check_conflict_on_del(session, uid, user)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001203 if not dry_run:
delacruzramo01b15d32019-07-02 14:37:47 +02001204 v = self.auth.delete_user(uid)
agarwalat53471982020-10-08 13:06:14 +00001205 self._send_msg("deleted", user, not_send_msg=not_send_msg)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001206 return v
1207 return None
1208
1209
1210class ProjectTopicAuth(ProjectTopic):
tierno65ca36d2019-02-12 19:27:52 +01001211 # topic = "projects"
agarwalat53471982020-10-08 13:06:14 +00001212 topic_msg = "project"
Eduardo Sousa44603902019-06-04 08:10:32 +01001213 schema_new = project_new_schema
1214 schema_edit = project_edit_schema
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001215
1216 def __init__(self, db, fs, msg, auth):
delacruzramo32bab472019-09-13 12:24:22 +02001217 ProjectTopic.__init__(self, db, fs, msg, auth)
1218 # self.auth = auth
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001219
tierno65ca36d2019-02-12 19:27:52 +01001220 def check_conflict_on_new(self, session, indata):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001221 """
1222 Check that the data to be inserted is valid
1223
tierno65ca36d2019-02-12 19:27:52 +01001224 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001225 :param indata: data to be inserted
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001226 :return: None or raises EngineException
1227 """
tiernocf042d32019-06-13 09:06:40 +00001228 project_name = indata.get("name")
1229 if is_valid_uuid(project_name):
garciadeblas4568a372021-03-24 09:19:48 +01001230 raise EngineException(
1231 "project name '{}' cannot have an uuid format".format(project_name),
1232 HTTPStatus.UNPROCESSABLE_ENTITY,
1233 )
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001234
tiernocf042d32019-06-13 09:06:40 +00001235 project_list = self.auth.get_project_list(filter_q={"name": project_name})
1236
1237 if project_list:
garciadeblas4568a372021-03-24 09:19:48 +01001238 raise EngineException(
1239 "project '{}' exists".format(project_name), HTTPStatus.CONFLICT
1240 )
tiernocf042d32019-06-13 09:06:40 +00001241
1242 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
1243 """
1244 Check that the data to be edited/uploaded is valid
1245
1246 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1247 :param final_content: data once modified
1248 :param edit_content: incremental data that contains the modifications to apply
1249 :param _id: internal _id
1250 :return: None or raises EngineException
1251 """
1252
1253 project_name = edit_content.get("name")
delacruzramo01b15d32019-07-02 14:37:47 +02001254 if project_name != final_content["name"]: # It is a true renaming
tiernocf042d32019-06-13 09:06:40 +00001255 if is_valid_uuid(project_name):
garciadeblas4568a372021-03-24 09:19:48 +01001256 raise EngineException(
1257 "project name '{}' cannot have an uuid format".format(project_name),
1258 HTTPStatus.UNPROCESSABLE_ENTITY,
1259 )
tiernocf042d32019-06-13 09:06:40 +00001260
delacruzramo01b15d32019-07-02 14:37:47 +02001261 if final_content["name"] == "admin":
garciadeblas4568a372021-03-24 09:19:48 +01001262 raise EngineException(
1263 "You cannot rename project 'admin'", http_code=HTTPStatus.CONFLICT
1264 )
delacruzramo01b15d32019-07-02 14:37:47 +02001265
tiernocf042d32019-06-13 09:06:40 +00001266 # Check that project name is not used, regardless keystone already checks this
garciadeblas4568a372021-03-24 09:19:48 +01001267 if project_name and self.auth.get_project_list(
1268 filter_q={"name": project_name}
1269 ):
1270 raise EngineException(
1271 "project '{}' is already used".format(project_name),
1272 HTTPStatus.CONFLICT,
1273 )
bravofb995ea22021-02-10 10:57:52 -03001274 return final_content
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001275
tiernob4844ab2019-05-23 08:42:12 +00001276 def check_conflict_on_del(self, session, _id, db_content):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001277 """
1278 Check if deletion can be done because of dependencies if it is not force. To override
1279
tierno65ca36d2019-02-12 19:27:52 +01001280 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001281 :param _id: internal _id
tiernob4844ab2019-05-23 08:42:12 +00001282 :param db_content: The database content of this item _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001283 :return: None if ok or raises EngineException with the conflict
1284 """
delacruzramo01b15d32019-07-02 14:37:47 +02001285
1286 def check_rw_projects(topic, title, id_field):
1287 for desc in self.db.get_list(topic):
garciadeblas4568a372021-03-24 09:19:48 +01001288 if (
1289 _id
1290 in desc["_admin"]["projects_read"]
1291 + desc["_admin"]["projects_write"]
1292 ):
1293 raise EngineException(
1294 "Project '{}' ({}) is being used by {} '{}'".format(
1295 db_content["name"], _id, title, desc[id_field]
1296 ),
1297 HTTPStatus.CONFLICT,
1298 )
delacruzramo01b15d32019-07-02 14:37:47 +02001299
1300 if _id in session["project_id"]:
garciadeblas4568a372021-03-24 09:19:48 +01001301 raise EngineException(
1302 "You cannot delete your own project", http_code=HTTPStatus.CONFLICT
1303 )
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001304
delacruzramo01b15d32019-07-02 14:37:47 +02001305 if db_content["name"] == "admin":
garciadeblas4568a372021-03-24 09:19:48 +01001306 raise EngineException(
1307 "You cannot delete project 'admin'", http_code=HTTPStatus.CONFLICT
1308 )
delacruzramo01b15d32019-07-02 14:37:47 +02001309
1310 # If any user is using this project, raise CONFLICT exception
1311 if not session["force"]:
1312 for user in self.auth.get_user_list():
tierno1546f2a2019-08-20 15:38:11 +00001313 for prm in user.get("project_role_mappings"):
1314 if prm["project"] == _id:
garciadeblas4568a372021-03-24 09:19:48 +01001315 raise EngineException(
1316 "Project '{}' ({}) is being used by user '{}'".format(
1317 db_content["name"], _id, user["username"]
1318 ),
1319 HTTPStatus.CONFLICT,
1320 )
delacruzramo01b15d32019-07-02 14:37:47 +02001321
1322 # If any VNFD, NSD, NST, PDU, etc. is using this project, raise CONFLICT exception
1323 if not session["force"]:
1324 check_rw_projects("vnfds", "VNF Descriptor", "id")
1325 check_rw_projects("nsds", "NS Descriptor", "id")
1326 check_rw_projects("nsts", "NS Template", "id")
1327 check_rw_projects("pdus", "PDU Descriptor", "name")
1328
tierno65ca36d2019-02-12 19:27:52 +01001329 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001330 """
1331 Creates a new entry into the authentication backend.
1332
1333 NOTE: Overrides BaseTopic functionality because it doesn't require access to database.
1334
1335 :param rollback: list to append created items at database in case a rollback may to be done
tierno65ca36d2019-02-12 19:27:52 +01001336 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001337 :param indata: data to be inserted
1338 :param kwargs: used to override the indata descriptor
1339 :param headers: http request headers
delacruzramo01b15d32019-07-02 14:37:47 +02001340 :return: _id: identity of the inserted data, operation _id (None)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001341 """
1342 try:
1343 content = BaseTopic._remove_envelop(indata)
1344
1345 # Override descriptor with query string kwargs
1346 BaseTopic._update_input_with_kwargs(content, kwargs)
tierno65ca36d2019-02-12 19:27:52 +01001347 content = self._validate_input_new(content, session["force"])
1348 self.check_conflict_on_new(session, content)
garciadeblas4568a372021-03-24 09:19:48 +01001349 self.format_on_new(
1350 content, project_id=session["project_id"], make_public=session["public"]
1351 )
delacruzramo01b15d32019-07-02 14:37:47 +02001352 _id = self.auth.create_project(content)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001353 rollback.append({"topic": self.topic, "_id": _id})
agarwalat53471982020-10-08 13:06:14 +00001354 self._send_msg("created", content, not_send_msg=None)
delacruzramo01b15d32019-07-02 14:37:47 +02001355 return _id, None
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001356 except ValidationError as e:
1357 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1358
K Sai Kiran57589552021-01-27 21:38:34 +05301359 def show(self, session, _id, filter_q=None, api_req=False):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001360 """
1361 Get complete information on an topic
1362
tierno65ca36d2019-02-12 19:27:52 +01001363 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001364 :param _id: server internal id
K Sai Kiran57589552021-01-27 21:38:34 +05301365 :param filter_q: dict: query parameter
K Sai Kirand010e3e2020-08-28 15:11:48 +05301366 :param api_req: True if this call is serving an external API request. False if serving internal request.
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001367 :return: dictionary, raise exception if not found.
1368 """
tiernocf042d32019-06-13 09:06:40 +00001369 # Allow _id to be a name or uuid
1370 filter_q = {self.id_field(self.topic, _id): _id}
delacruzramo029405d2019-09-26 10:52:56 +02001371 # projects = self.auth.get_project_list(filter_q=filter_q)
garciadeblas4568a372021-03-24 09:19:48 +01001372 projects = self.list(session, filter_q) # To allow default filtering (Bug 853)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001373 if len(projects) == 1:
1374 return projects[0]
1375 elif len(projects) > 1:
1376 raise EngineException("Too many projects found", HTTPStatus.CONFLICT)
1377 else:
1378 raise EngineException("Project not found", HTTPStatus.NOT_FOUND)
1379
tiernoc4e07d02020-08-14 14:25:32 +00001380 def list(self, session, filter_q=None, api_req=False):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001381 """
1382 Get a list of the topic that matches a filter
1383
tierno65ca36d2019-02-12 19:27:52 +01001384 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001385 :param filter_q: filter of data to be applied
1386 :return: The list, it can be empty if no one match the filter.
1387 """
delacruzramo029405d2019-09-26 10:52:56 +02001388 project_list = self.auth.get_project_list(filter_q)
1389 if not session["allow_show_user_project_role"]:
1390 # Bug 853 - Default filtering
1391 user = self.auth.get_user(session["username"])
1392 projects = [prm["project"] for prm in user["project_role_mappings"]]
1393 project_list = [proj for proj in project_list if proj["_id"] in projects]
1394 return project_list
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001395
tiernobee3bad2019-12-05 12:26:01 +00001396 def delete(self, session, _id, dry_run=False, not_send_msg=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001397 """
1398 Delete item by its internal _id
1399
tierno65ca36d2019-02-12 19:27:52 +01001400 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001401 :param _id: server internal id
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001402 :param dry_run: make checking but do not delete
tiernobee3bad2019-12-05 12:26:01 +00001403 :param not_send_msg: To not send message (False) or store content (list) instead
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001404 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
1405 """
tiernocf042d32019-06-13 09:06:40 +00001406 # Allow _id to be a name or uuid
delacruzramo01b15d32019-07-02 14:37:47 +02001407 proj = self.auth.get_project(_id)
1408 pid = proj["_id"]
1409 self.check_conflict_on_del(session, pid, proj)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001410 if not dry_run:
delacruzramo01b15d32019-07-02 14:37:47 +02001411 v = self.auth.delete_project(pid)
agarwalat53471982020-10-08 13:06:14 +00001412 self._send_msg("deleted", proj, not_send_msg=None)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001413 return v
1414 return None
1415
tierno4015b472019-06-10 13:57:29 +00001416 def edit(self, session, _id, indata=None, kwargs=None, content=None):
1417 """
1418 Updates a project entry.
1419
1420 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1421 :param _id:
1422 :param indata: data to be inserted
1423 :param kwargs: used to override the indata descriptor
1424 :param content:
1425 :return: _id: identity of the inserted data.
1426 """
1427 indata = self._remove_envelop(indata)
1428
1429 # Override descriptor with query string kwargs
1430 if kwargs:
1431 BaseTopic._update_input_with_kwargs(indata, kwargs)
1432 try:
tierno4015b472019-06-10 13:57:29 +00001433 if not content:
1434 content = self.show(session, _id)
Frank Brydendeba68e2020-07-27 13:55:11 +00001435 indata = self._validate_input_edit(indata, content, force=session["force"])
bravofb995ea22021-02-10 10:57:52 -03001436 content = self.check_conflict_on_edit(session, content, indata, _id=_id)
delacruzramo01b15d32019-07-02 14:37:47 +02001437 self.format_on_edit(content, indata)
agarwalat53471982020-10-08 13:06:14 +00001438 content_original = copy.deepcopy(content)
delacruzramo32bab472019-09-13 12:24:22 +02001439 deep_update_rfc7396(content, indata)
delacruzramo01b15d32019-07-02 14:37:47 +02001440 self.auth.update_project(content["_id"], content)
agarwalat53471982020-10-08 13:06:14 +00001441 proj_data = {"_id": _id, "changes": indata, "original": content_original}
1442 self._send_msg("edited", proj_data, not_send_msg=None)
tierno4015b472019-06-10 13:57:29 +00001443 except ValidationError as e:
1444 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1445
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001446
1447class RoleTopicAuth(BaseTopic):
delacruzramoceb8baf2019-06-21 14:25:38 +02001448 topic = "roles"
garciadeblas4568a372021-03-24 09:19:48 +01001449 topic_msg = None # "roles"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001450 schema_new = roles_new_schema
1451 schema_edit = roles_edit_schema
tierno65ca36d2019-02-12 19:27:52 +01001452 multiproject = False
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001453
tierno9e87a7f2020-03-23 09:24:10 +00001454 def __init__(self, db, fs, msg, auth):
delacruzramo32bab472019-09-13 12:24:22 +02001455 BaseTopic.__init__(self, db, fs, msg, auth)
1456 # self.auth = auth
tierno9e87a7f2020-03-23 09:24:10 +00001457 self.operations = auth.role_permissions
delacruzramo01b15d32019-07-02 14:37:47 +02001458 # self.topic = "roles_operations" if isinstance(auth, AuthconnKeystone) else "roles"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001459
1460 @staticmethod
1461 def validate_role_definition(operations, role_definitions):
1462 """
1463 Validates the role definition against the operations defined in
1464 the resources to operations files.
1465
1466 :param operations: operations list
1467 :param role_definitions: role definition to test
1468 :return: None if ok, raises ValidationError exception on error
1469 """
tierno1f029d82019-06-13 22:37:04 +00001470 if not role_definitions.get("permissions"):
1471 return
1472 ignore_fields = ["admin", "default"]
1473 for role_def in role_definitions["permissions"].keys():
Eduardo Sousa37de0912019-05-23 02:17:22 +01001474 if role_def in ignore_fields:
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001475 continue
Eduardo Sousac7689372019-06-04 16:01:46 +01001476 if role_def[-1] == ":":
tierno1f029d82019-06-13 22:37:04 +00001477 raise ValidationError("Operation cannot end with ':'")
Eduardo Sousac5a18892019-06-06 14:51:23 +01001478
garciadeblas4568a372021-03-24 09:19:48 +01001479 match = next(
1480 (
1481 op
1482 for op in operations
1483 if op == role_def or op.startswith(role_def + ":")
1484 ),
1485 None,
1486 )
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001487
tierno97639b42020-08-04 12:48:15 +00001488 if not match:
tierno1f029d82019-06-13 22:37:04 +00001489 raise ValidationError("Invalid permission '{}'".format(role_def))
Eduardo Sousa37de0912019-05-23 02:17:22 +01001490
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001491 def _validate_input_new(self, input, force=False):
1492 """
1493 Validates input user content for a new entry.
1494
1495 :param input: user input content for the new topic
1496 :param force: may be used for being more tolerant
1497 :return: The same input content, or a changed version of it.
1498 """
1499 if self.schema_new:
1500 validate_input(input, self.schema_new)
Eduardo Sousa37de0912019-05-23 02:17:22 +01001501 self.validate_role_definition(self.operations, input)
Eduardo Sousac4650362019-06-04 13:24:22 +01001502
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001503 return input
1504
Frank Brydendeba68e2020-07-27 13:55:11 +00001505 def _validate_input_edit(self, input, content, force=False):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001506 """
1507 Validates input user content for updating an entry.
1508
1509 :param input: user input content for the new topic
1510 :param force: may be used for being more tolerant
1511 :return: The same input content, or a changed version of it.
1512 """
1513 if self.schema_edit:
1514 validate_input(input, self.schema_edit)
Eduardo Sousa37de0912019-05-23 02:17:22 +01001515 self.validate_role_definition(self.operations, input)
Eduardo Sousac4650362019-06-04 13:24:22 +01001516
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001517 return input
1518
tierno65ca36d2019-02-12 19:27:52 +01001519 def check_conflict_on_new(self, session, indata):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001520 """
1521 Check that the data to be inserted is valid
1522
tierno65ca36d2019-02-12 19:27:52 +01001523 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001524 :param indata: data to be inserted
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001525 :return: None or raises EngineException
1526 """
delacruzramo79e40f42019-10-10 16:36:40 +02001527 # check name is not uuid
1528 role_name = indata.get("name")
1529 if is_valid_uuid(role_name):
garciadeblas4568a372021-03-24 09:19:48 +01001530 raise EngineException(
1531 "role name '{}' cannot have an uuid format".format(role_name),
1532 HTTPStatus.UNPROCESSABLE_ENTITY,
1533 )
tierno1f029d82019-06-13 22:37:04 +00001534 # check name not exists
delacruzramo01b15d32019-07-02 14:37:47 +02001535 name = indata["name"]
1536 # if self.db.get_one(self.topic, {"name": indata.get("name")}, fail_on_empty=False, fail_on_more=False):
1537 if self.auth.get_role_list({"name": name}):
garciadeblas4568a372021-03-24 09:19:48 +01001538 raise EngineException(
1539 "role name '{}' exists".format(name), HTTPStatus.CONFLICT
1540 )
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001541
tierno65ca36d2019-02-12 19:27:52 +01001542 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001543 """
1544 Check that the data to be edited/uploaded is valid
1545
tierno65ca36d2019-02-12 19:27:52 +01001546 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001547 :param final_content: data once modified
1548 :param edit_content: incremental data that contains the modifications to apply
1549 :param _id: internal _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001550 :return: None or raises EngineException
1551 """
tierno1f029d82019-06-13 22:37:04 +00001552 if "default" not in final_content["permissions"]:
1553 final_content["permissions"]["default"] = False
1554 if "admin" not in final_content["permissions"]:
1555 final_content["permissions"]["admin"] = False
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001556
delacruzramo79e40f42019-10-10 16:36:40 +02001557 # check name is not uuid
1558 role_name = edit_content.get("name")
1559 if is_valid_uuid(role_name):
garciadeblas4568a372021-03-24 09:19:48 +01001560 raise EngineException(
1561 "role name '{}' cannot have an uuid format".format(role_name),
1562 HTTPStatus.UNPROCESSABLE_ENTITY,
1563 )
delacruzramo79e40f42019-10-10 16:36:40 +02001564
1565 # Check renaming of admin roles
1566 role = self.auth.get_role(_id)
1567 if role["name"] in ["system_admin", "project_admin"]:
garciadeblas4568a372021-03-24 09:19:48 +01001568 raise EngineException(
1569 "You cannot rename role '{}'".format(role["name"]),
1570 http_code=HTTPStatus.FORBIDDEN,
1571 )
delacruzramo79e40f42019-10-10 16:36:40 +02001572
tierno1f029d82019-06-13 22:37:04 +00001573 # check name not exists
1574 if "name" in edit_content:
1575 role_name = edit_content["name"]
delacruzramo01b15d32019-07-02 14:37:47 +02001576 # if self.db.get_one(self.topic, {"name":role_name,"_id.ne":_id}, fail_on_empty=False, fail_on_more=False):
1577 roles = self.auth.get_role_list({"name": role_name})
1578 if roles and roles[0][BaseTopic.id_field("roles", _id)] != _id:
garciadeblas4568a372021-03-24 09:19:48 +01001579 raise EngineException(
1580 "role name '{}' exists".format(role_name), HTTPStatus.CONFLICT
1581 )
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001582
bravofb995ea22021-02-10 10:57:52 -03001583 return final_content
1584
tiernob4844ab2019-05-23 08:42:12 +00001585 def check_conflict_on_del(self, session, _id, db_content):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001586 """
1587 Check if deletion can be done because of dependencies if it is not force. To override
1588
tierno65ca36d2019-02-12 19:27:52 +01001589 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001590 :param _id: internal _id
tiernob4844ab2019-05-23 08:42:12 +00001591 :param db_content: The database content of this item _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001592 :return: None if ok or raises EngineException with the conflict
1593 """
delacruzramo01b15d32019-07-02 14:37:47 +02001594 role = self.auth.get_role(_id)
1595 if role["name"] in ["system_admin", "project_admin"]:
garciadeblas4568a372021-03-24 09:19:48 +01001596 raise EngineException(
1597 "You cannot delete role '{}'".format(role["name"]),
1598 http_code=HTTPStatus.FORBIDDEN,
1599 )
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001600
delacruzramo01b15d32019-07-02 14:37:47 +02001601 # If any user is using this role, raise CONFLICT exception
delacruzramoad682a52019-12-10 16:26:34 +01001602 if not session["force"]:
1603 for user in self.auth.get_user_list():
1604 for prm in user.get("project_role_mappings"):
1605 if prm["role"] == _id:
garciadeblas4568a372021-03-24 09:19:48 +01001606 raise EngineException(
1607 "Role '{}' ({}) is being used by user '{}'".format(
1608 role["name"], _id, user["username"]
1609 ),
1610 HTTPStatus.CONFLICT,
1611 )
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001612
1613 @staticmethod
garciadeblas4568a372021-03-24 09:19:48 +01001614 def format_on_new(content, project_id=None, make_public=False): # TO BE REMOVED ?
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001615 """
1616 Modifies content descriptor to include _admin
1617
1618 :param content: descriptor to be modified
1619 :param project_id: if included, it add project read/write permissions
1620 :param make_public: if included it is generated as public for reading.
1621 :return: None, but content is modified
1622 """
1623 now = time()
1624 if "_admin" not in content:
1625 content["_admin"] = {}
1626 if not content["_admin"].get("created"):
1627 content["_admin"]["created"] = now
1628 content["_admin"]["modified"] = now
Eduardo Sousac4650362019-06-04 13:24:22 +01001629
tierno1f029d82019-06-13 22:37:04 +00001630 if "permissions" not in content:
1631 content["permissions"] = {}
Eduardo Sousac4650362019-06-04 13:24:22 +01001632
tierno1f029d82019-06-13 22:37:04 +00001633 if "default" not in content["permissions"]:
1634 content["permissions"]["default"] = False
1635 if "admin" not in content["permissions"]:
1636 content["permissions"]["admin"] = False
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001637
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001638 @staticmethod
1639 def format_on_edit(final_content, edit_content):
1640 """
1641 Modifies final_content descriptor to include the modified date.
1642
1643 :param final_content: final descriptor generated
1644 :param edit_content: alterations to be include
1645 :return: None, but final_content is modified
1646 """
delacruzramo01b15d32019-07-02 14:37:47 +02001647 if "_admin" in final_content:
1648 final_content["_admin"]["modified"] = time()
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001649
tierno1f029d82019-06-13 22:37:04 +00001650 if "permissions" not in final_content:
1651 final_content["permissions"] = {}
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001652
tierno1f029d82019-06-13 22:37:04 +00001653 if "default" not in final_content["permissions"]:
1654 final_content["permissions"]["default"] = False
1655 if "admin" not in final_content["permissions"]:
1656 final_content["permissions"]["admin"] = False
tiernobdebce92019-07-01 15:36:49 +00001657 return None
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001658
K Sai Kiran57589552021-01-27 21:38:34 +05301659 def show(self, session, _id, filter_q=None, api_req=False):
delacruzramo01b15d32019-07-02 14:37:47 +02001660 """
1661 Get complete information on an topic
Eduardo Sousac4650362019-06-04 13:24:22 +01001662
delacruzramo01b15d32019-07-02 14:37:47 +02001663 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1664 :param _id: server internal id
K Sai Kiran57589552021-01-27 21:38:34 +05301665 :param filter_q: dict: query parameter
K Sai Kirand010e3e2020-08-28 15:11:48 +05301666 :param api_req: True if this call is serving an external API request. False if serving internal request.
delacruzramo01b15d32019-07-02 14:37:47 +02001667 :return: dictionary, raise exception if not found.
1668 """
1669 filter_q = {BaseTopic.id_field(self.topic, _id): _id}
delacruzramo029405d2019-09-26 10:52:56 +02001670 # roles = self.auth.get_role_list(filter_q)
garciadeblas4568a372021-03-24 09:19:48 +01001671 roles = self.list(session, filter_q) # To allow default filtering (Bug 853)
delacruzramo01b15d32019-07-02 14:37:47 +02001672 if not roles:
garciadeblas4568a372021-03-24 09:19:48 +01001673 raise AuthconnNotFoundException(
1674 "Not found any role with filter {}".format(filter_q)
1675 )
delacruzramo01b15d32019-07-02 14:37:47 +02001676 elif len(roles) > 1:
garciadeblas4568a372021-03-24 09:19:48 +01001677 raise AuthconnConflictException(
1678 "Found more than one role with filter {}".format(filter_q)
1679 )
delacruzramo01b15d32019-07-02 14:37:47 +02001680 return roles[0]
1681
tiernoc4e07d02020-08-14 14:25:32 +00001682 def list(self, session, filter_q=None, api_req=False):
delacruzramo01b15d32019-07-02 14:37:47 +02001683 """
1684 Get a list of the topic that matches a filter
1685
1686 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1687 :param filter_q: filter of data to be applied
1688 :return: The list, it can be empty if no one match the filter.
1689 """
delacruzramo029405d2019-09-26 10:52:56 +02001690 role_list = self.auth.get_role_list(filter_q)
1691 if not session["allow_show_user_project_role"]:
1692 # Bug 853 - Default filtering
1693 user = self.auth.get_user(session["username"])
1694 roles = [prm["role"] for prm in user["project_role_mappings"]]
1695 role_list = [role for role in role_list if role["_id"] in roles]
1696 return role_list
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001697
tierno65ca36d2019-02-12 19:27:52 +01001698 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001699 """
1700 Creates a new entry into database.
1701
1702 :param rollback: list to append created items at database in case a rollback may to be done
tierno65ca36d2019-02-12 19:27:52 +01001703 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001704 :param indata: data to be inserted
1705 :param kwargs: used to override the indata descriptor
1706 :param headers: http request headers
delacruzramo01b15d32019-07-02 14:37:47 +02001707 :return: _id: identity of the inserted data, operation _id (None)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001708 """
1709 try:
tierno1f029d82019-06-13 22:37:04 +00001710 content = self._remove_envelop(indata)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001711
1712 # Override descriptor with query string kwargs
tierno1f029d82019-06-13 22:37:04 +00001713 self._update_input_with_kwargs(content, kwargs)
tierno65ca36d2019-02-12 19:27:52 +01001714 content = self._validate_input_new(content, session["force"])
1715 self.check_conflict_on_new(session, content)
garciadeblas4568a372021-03-24 09:19:48 +01001716 self.format_on_new(
1717 content, project_id=session["project_id"], make_public=session["public"]
1718 )
delacruzramo01b15d32019-07-02 14:37:47 +02001719 # role_name = content["name"]
1720 rid = self.auth.create_role(content)
1721 content["_id"] = rid
1722 # _id = self.db.create(self.topic, content)
1723 rollback.append({"topic": self.topic, "_id": rid})
tiernobee3bad2019-12-05 12:26:01 +00001724 # self._send_msg("created", content, not_send_msg=not_send_msg)
delacruzramo01b15d32019-07-02 14:37:47 +02001725 return rid, None
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001726 except ValidationError as e:
1727 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1728
tiernobee3bad2019-12-05 12:26:01 +00001729 def delete(self, session, _id, dry_run=False, not_send_msg=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001730 """
1731 Delete item by its internal _id
1732
tierno65ca36d2019-02-12 19:27:52 +01001733 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001734 :param _id: server internal id
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001735 :param dry_run: make checking but do not delete
tiernobee3bad2019-12-05 12:26:01 +00001736 :param not_send_msg: To not send message (False) or store content (list) instead
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001737 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
1738 """
delacruzramo01b15d32019-07-02 14:37:47 +02001739 filter_q = {BaseTopic.id_field(self.topic, _id): _id}
1740 roles = self.auth.get_role_list(filter_q)
1741 if not roles:
garciadeblas4568a372021-03-24 09:19:48 +01001742 raise AuthconnNotFoundException(
1743 "Not found any role with filter {}".format(filter_q)
1744 )
delacruzramo01b15d32019-07-02 14:37:47 +02001745 elif len(roles) > 1:
garciadeblas4568a372021-03-24 09:19:48 +01001746 raise AuthconnConflictException(
1747 "Found more than one role with filter {}".format(filter_q)
1748 )
delacruzramo01b15d32019-07-02 14:37:47 +02001749 rid = roles[0]["_id"]
1750 self.check_conflict_on_del(session, rid, None)
delacruzramoceb8baf2019-06-21 14:25:38 +02001751 # filter_q = {"_id": _id}
delacruzramo01b15d32019-07-02 14:37:47 +02001752 # filter_q = {BaseTopic.id_field(self.topic, _id): _id} # To allow role addressing by name
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001753 if not dry_run:
delacruzramo01b15d32019-07-02 14:37:47 +02001754 v = self.auth.delete_role(rid)
1755 # v = self.db.del_one(self.topic, filter_q)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001756 return v
1757 return None
1758
tierno65ca36d2019-02-12 19:27:52 +01001759 def edit(self, session, _id, indata=None, kwargs=None, content=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001760 """
1761 Updates a role entry.
1762
tierno65ca36d2019-02-12 19:27:52 +01001763 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001764 :param _id:
1765 :param indata: data to be inserted
1766 :param kwargs: used to override the indata descriptor
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001767 :param content:
1768 :return: _id: identity of the inserted data.
1769 """
delacruzramo01b15d32019-07-02 14:37:47 +02001770 if kwargs:
1771 self._update_input_with_kwargs(indata, kwargs)
1772 try:
delacruzramo01b15d32019-07-02 14:37:47 +02001773 if not content:
1774 content = self.show(session, _id)
Frank Brydendeba68e2020-07-27 13:55:11 +00001775 indata = self._validate_input_edit(indata, content, force=session["force"])
delacruzramo01b15d32019-07-02 14:37:47 +02001776 deep_update_rfc7396(content, indata)
bravofb995ea22021-02-10 10:57:52 -03001777 content = self.check_conflict_on_edit(session, content, indata, _id=_id)
delacruzramo01b15d32019-07-02 14:37:47 +02001778 self.format_on_edit(content, indata)
1779 self.auth.update_role(content)
1780 except ValidationError as e:
1781 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)