blob: fa75853d394aa64377f83090486a96b0d3ff043a [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:
348
349 for p in config_to_encrypt_keys:
tierno92c1c7d2018-11-12 15:22:37 +0100350 if edit_content["config"].get(p):
garciadeblas4568a372021-03-24 09:19:48 +0100351 final_content["config"][p] = self.db.encrypt(
352 edit_content["config"][p],
353 schema_version=schema_version,
354 salt=final_content["_id"],
355 )
tiernobdebce92019-07-01 15:36:49 +0000356
357 # create edit operation
358 final_content["_admin"]["operations"].append(self._create_operation("edit"))
garciadeblas4568a372021-03-24 09:19:48 +0100359 return "{}:{}".format(
360 final_content["_id"], len(final_content["_admin"]["operations"]) - 1
361 )
tierno92c1c7d2018-11-12 15:22:37 +0100362
363 def format_on_new(self, content, project_id=None, make_public=False):
tiernobdebce92019-07-01 15:36:49 +0000364 """
365 Modifies content descriptor to include _admin and insert create operation
366 :param content: descriptor to be modified
367 :param project_id: if included, it add project read/write permissions. Can be None or a list
368 :param make_public: if included it is generated as public for reading.
369 :return: op_id: operation id on asynchronous operation, None otherwise. In addition content is modified
370 """
371 super().format_on_new(content, project_id=project_id, make_public=make_public)
tierno468aa242019-08-01 16:35:04 +0000372 content["schema_version"] = schema_version = "1.11"
tierno92c1c7d2018-11-12 15:22:37 +0100373
374 # encrypt passwords
tiernobdebce92019-07-01 15:36:49 +0000375 if content.get(self.password_to_encrypt):
garciadeblas4568a372021-03-24 09:19:48 +0100376 content[self.password_to_encrypt] = self.db.encrypt(
377 content[self.password_to_encrypt],
378 schema_version=schema_version,
379 salt=content["_id"],
380 )
381 config_to_encrypt_keys = self.config_to_encrypt.get(
382 schema_version
383 ) or self.config_to_encrypt.get("default")
tierno468aa242019-08-01 16:35:04 +0000384 if content.get("config") and config_to_encrypt_keys:
385 for p in config_to_encrypt_keys:
tierno92c1c7d2018-11-12 15:22:37 +0100386 if content["config"].get(p):
garciadeblas4568a372021-03-24 09:19:48 +0100387 content["config"][p] = self.db.encrypt(
388 content["config"][p],
389 schema_version=schema_version,
390 salt=content["_id"],
391 )
tierno92c1c7d2018-11-12 15:22:37 +0100392
tiernob24258a2018-10-04 18:39:49 +0200393 content["_admin"]["operationalState"] = "PROCESSING"
394
tiernobdebce92019-07-01 15:36:49 +0000395 # create operation
396 content["_admin"]["operations"] = [self._create_operation("create")]
397 content["_admin"]["current_operation"] = None
vijay.rd1eaf982021-05-14 11:54:59 +0000398 # create Resource in Openstack based VIM
399 if content.get("vim_type"):
400 if content["vim_type"] == "openstack":
401 compute = {
garciadeblasf2af4a12023-01-24 16:56:54 +0100402 "ram": {"total": None, "used": None},
403 "vcpus": {"total": None, "used": None},
404 "instances": {"total": None, "used": None},
vijay.rd1eaf982021-05-14 11:54:59 +0000405 }
406 storage = {
garciadeblasf2af4a12023-01-24 16:56:54 +0100407 "volumes": {"total": None, "used": None},
408 "snapshots": {"total": None, "used": None},
409 "storage": {"total": None, "used": None},
vijay.rd1eaf982021-05-14 11:54:59 +0000410 }
411 network = {
garciadeblasf2af4a12023-01-24 16:56:54 +0100412 "networks": {"total": None, "used": None},
413 "subnets": {"total": None, "used": None},
414 "floating_ips": {"total": None, "used": None},
vijay.rd1eaf982021-05-14 11:54:59 +0000415 }
garciadeblasf2af4a12023-01-24 16:56:54 +0100416 content["resources"] = {
417 "compute": compute,
418 "storage": storage,
419 "network": network,
420 }
vijay.rd1eaf982021-05-14 11:54:59 +0000421
tiernobdebce92019-07-01 15:36:49 +0000422 return "{}:0".format(content["_id"])
423
tiernobee3bad2019-12-05 12:26:01 +0000424 def delete(self, session, _id, dry_run=False, not_send_msg=None):
tiernob24258a2018-10-04 18:39:49 +0200425 """
426 Delete item by its internal _id
tierno65ca36d2019-02-12 19:27:52 +0100427 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tiernob24258a2018-10-04 18:39:49 +0200428 :param _id: server internal id
tiernob24258a2018-10-04 18:39:49 +0200429 :param dry_run: make checking but do not delete
tiernobee3bad2019-12-05 12:26:01 +0000430 :param not_send_msg: To not send message (False) or store content (list) instead
tiernobdebce92019-07-01 15:36:49 +0000431 :return: operation id if it is ordered to delete. None otherwise
tiernob24258a2018-10-04 18:39:49 +0200432 """
tiernobdebce92019-07-01 15:36:49 +0000433
434 filter_q = self._get_project_filter(session)
435 filter_q["_id"] = _id
436 db_content = self.db.get_one(self.topic, filter_q)
437
438 self.check_conflict_on_del(session, _id, db_content)
439 if dry_run:
440 return None
441
tiernof5f2e3f2020-03-23 14:42:10 +0000442 # remove reference from project_read if there are more projects referencing it. If it last one,
443 # do not remove reference, but order via kafka to delete it
444 if session["project_id"] and session["project_id"]:
garciadeblas4568a372021-03-24 09:19:48 +0100445 other_projects_referencing = next(
446 (
447 p
448 for p in db_content["_admin"]["projects_read"]
449 if p not in session["project_id"] and p != "ANY"
450 ),
451 None,
452 )
tiernobdebce92019-07-01 15:36:49 +0000453
tiernof5f2e3f2020-03-23 14:42:10 +0000454 # check if there are projects referencing it (apart from ANY, that means, public)....
455 if other_projects_referencing:
456 # remove references but not delete
garciadeblas4568a372021-03-24 09:19:48 +0100457 update_dict_pull = {
458 "_admin.projects_read": session["project_id"],
459 "_admin.projects_write": session["project_id"],
460 }
461 self.db.set_one(
462 self.topic, filter_q, update_dict=None, pull_list=update_dict_pull
463 )
tiernof5f2e3f2020-03-23 14:42:10 +0000464 return None
465 else:
garciadeblas4568a372021-03-24 09:19:48 +0100466 can_write = next(
467 (
468 p
469 for p in db_content["_admin"]["projects_write"]
470 if p == "ANY" or p in session["project_id"]
471 ),
472 None,
473 )
tiernof5f2e3f2020-03-23 14:42:10 +0000474 if not can_write:
garciadeblas4568a372021-03-24 09:19:48 +0100475 raise EngineException(
476 "You have not write permission to delete it",
477 http_code=HTTPStatus.UNAUTHORIZED,
478 )
tiernobdebce92019-07-01 15:36:49 +0000479
480 # It must be deleted
481 if session["force"]:
482 self.db.del_one(self.topic, {"_id": _id})
483 op_id = None
garciadeblas4568a372021-03-24 09:19:48 +0100484 self._send_msg(
485 "deleted", {"_id": _id, "op_id": op_id}, not_send_msg=not_send_msg
486 )
tiernobdebce92019-07-01 15:36:49 +0000487 else:
tiernof5f2e3f2020-03-23 14:42:10 +0000488 update_dict = {"_admin.to_delete": True}
garciadeblas4568a372021-03-24 09:19:48 +0100489 self.db.set_one(
490 self.topic,
491 {"_id": _id},
492 update_dict=update_dict,
493 push={"_admin.operations": self._create_operation("delete")},
494 )
tiernobdebce92019-07-01 15:36:49 +0000495 # the number of operations is the operation_id. db_content does not contains the new operation inserted,
496 # so the -1 is not needed
garciadeblas4568a372021-03-24 09:19:48 +0100497 op_id = "{}:{}".format(
498 db_content["_id"], len(db_content["_admin"]["operations"])
499 )
500 self._send_msg(
501 "delete", {"_id": _id, "op_id": op_id}, not_send_msg=not_send_msg
502 )
tiernobdebce92019-07-01 15:36:49 +0000503 return op_id
tiernob24258a2018-10-04 18:39:49 +0200504
505
tiernobdebce92019-07-01 15:36:49 +0000506class VimAccountTopic(CommonVimWimSdn):
507 topic = "vim_accounts"
508 topic_msg = "vim_account"
509 schema_new = vim_account_new_schema
510 schema_edit = vim_account_edit_schema
511 multiproject = True
512 password_to_encrypt = "vim_password"
garciadeblas4568a372021-03-24 09:19:48 +0100513 config_to_encrypt = {
514 "1.1": ("admin_password", "nsx_password", "vcenter_password"),
515 "default": (
516 "admin_password",
517 "nsx_password",
518 "vcenter_password",
519 "vrops_password",
520 ),
521 }
tiernobdebce92019-07-01 15:36:49 +0000522
delacruzramo35c998b2019-11-21 11:09:16 +0100523 def check_conflict_on_del(self, session, _id, db_content):
524 """
525 Check if deletion can be done because of dependencies if it is not force. To override
526 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
527 :param _id: internal _id
528 :param db_content: The database content of this item _id
529 :return: None if ok or raises EngineException with the conflict
530 """
531 if session["force"]:
532 return
533 # check if used by VNF
534 if self.db.get_list("vnfrs", {"vim-account-id": _id}):
garciadeblas4568a372021-03-24 09:19:48 +0100535 raise EngineException(
536 "There is at least one VNF using this VIM account",
537 http_code=HTTPStatus.CONFLICT,
538 )
delacruzramo35c998b2019-11-21 11:09:16 +0100539 super().check_conflict_on_del(session, _id, db_content)
540
tiernobdebce92019-07-01 15:36:49 +0000541
542class WimAccountTopic(CommonVimWimSdn):
tierno55ba2e62018-12-11 17:22:22 +0000543 topic = "wim_accounts"
544 topic_msg = "wim_account"
545 schema_new = wim_account_new_schema
546 schema_edit = wim_account_edit_schema
tierno65ca36d2019-02-12 19:27:52 +0100547 multiproject = True
gifrerenom44f5ec12022-03-07 16:57:25 +0000548 password_to_encrypt = "password"
tierno468aa242019-08-01 16:35:04 +0000549 config_to_encrypt = {}
tierno55ba2e62018-12-11 17:22:22 +0000550
551
tiernobdebce92019-07-01 15:36:49 +0000552class SdnTopic(CommonVimWimSdn):
tiernob24258a2018-10-04 18:39:49 +0200553 topic = "sdns"
554 topic_msg = "sdn"
tierno6b02b052020-06-02 10:07:41 +0000555 quota_name = "sdn_controllers"
tiernob24258a2018-10-04 18:39:49 +0200556 schema_new = sdn_new_schema
557 schema_edit = sdn_edit_schema
tierno65ca36d2019-02-12 19:27:52 +0100558 multiproject = True
tiernobdebce92019-07-01 15:36:49 +0000559 password_to_encrypt = "password"
tierno468aa242019-08-01 16:35:04 +0000560 config_to_encrypt = {}
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100561
tierno7adaeb02019-12-17 16:46:12 +0000562 def _obtain_url(self, input, create):
563 if input.get("ip") or input.get("port"):
garciadeblas4568a372021-03-24 09:19:48 +0100564 if not input.get("ip") or not input.get("port") or input.get("url"):
565 raise ValidationError(
566 "You must provide both 'ip' and 'port' (deprecated); or just 'url' (prefered)"
567 )
568 input["url"] = "http://{}:{}/".format(input["ip"], input["port"])
tierno7adaeb02019-12-17 16:46:12 +0000569 del input["ip"]
570 del input["port"]
garciadeblas4568a372021-03-24 09:19:48 +0100571 elif create and not input.get("url"):
tierno7adaeb02019-12-17 16:46:12 +0000572 raise ValidationError("You must provide 'url'")
573 return input
574
575 def _validate_input_new(self, input, force=False):
576 input = super()._validate_input_new(input, force)
577 return self._obtain_url(input, True)
578
Frank Brydendeba68e2020-07-27 13:55:11 +0000579 def _validate_input_edit(self, input, content, force=False):
580 input = super()._validate_input_edit(input, content, force)
tierno7adaeb02019-12-17 16:46:12 +0000581 return self._obtain_url(input, False)
582
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100583
delacruzramofe598fe2019-10-23 18:25:11 +0200584class K8sClusterTopic(CommonVimWimSdn):
585 topic = "k8sclusters"
586 topic_msg = "k8scluster"
587 schema_new = k8scluster_new_schema
588 schema_edit = k8scluster_edit_schema
589 multiproject = True
590 password_to_encrypt = None
591 config_to_encrypt = {}
592
593 def format_on_new(self, content, project_id=None, make_public=False):
594 oid = super().format_on_new(content, project_id, make_public)
garciadeblas4568a372021-03-24 09:19:48 +0100595 self.db.encrypt_decrypt_fields(
596 content["credentials"],
597 "encrypt",
598 ["password", "secret"],
599 schema_version=content["schema_version"],
600 salt=content["_id"],
601 )
delacruzramoc2d5fc62020-02-05 11:50:21 +0000602 # Add Helm/Juju Repo lists
603 repos = {"helm-chart": [], "juju-bundle": []}
604 for proj in content["_admin"]["projects_read"]:
garciadeblas4568a372021-03-24 09:19:48 +0100605 if proj != "ANY":
606 for repo in self.db.get_list(
607 "k8srepos", {"_admin.projects_read": proj}
608 ):
delacruzramoc2d5fc62020-02-05 11:50:21 +0000609 if repo["_id"] not in repos[repo["type"]]:
610 repos[repo["type"]].append(repo["_id"])
611 for k in repos:
garciadeblas4568a372021-03-24 09:19:48 +0100612 content["_admin"][k.replace("-", "_") + "_repos"] = repos[k]
delacruzramofe598fe2019-10-23 18:25:11 +0200613 return oid
614
615 def format_on_edit(self, final_content, edit_content):
616 if final_content.get("schema_version") and edit_content.get("credentials"):
garciadeblas4568a372021-03-24 09:19:48 +0100617 self.db.encrypt_decrypt_fields(
618 edit_content["credentials"],
619 "encrypt",
620 ["password", "secret"],
621 schema_version=final_content["schema_version"],
622 salt=final_content["_id"],
623 )
624 deep_update_rfc7396(
625 final_content["credentials"], edit_content["credentials"]
626 )
delacruzramofe598fe2019-10-23 18:25:11 +0200627 oid = super().format_on_edit(final_content, edit_content)
628 return oid
629
delacruzramoc2d5fc62020-02-05 11:50:21 +0000630 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
garciadeblas4568a372021-03-24 09:19:48 +0100631 final_content = super(CommonVimWimSdn, self).check_conflict_on_edit(
632 session, final_content, edit_content, _id
633 )
634 final_content = super().check_conflict_on_edit(
635 session, final_content, edit_content, _id
636 )
delacruzramoc2d5fc62020-02-05 11:50:21 +0000637 # Update Helm/Juju Repo lists
638 repos = {"helm-chart": [], "juju-bundle": []}
639 for proj in session.get("set_project", []):
garciadeblas4568a372021-03-24 09:19:48 +0100640 if proj != "ANY":
641 for repo in self.db.get_list(
642 "k8srepos", {"_admin.projects_read": proj}
643 ):
delacruzramoc2d5fc62020-02-05 11:50:21 +0000644 if repo["_id"] not in repos[repo["type"]]:
645 repos[repo["type"]].append(repo["_id"])
646 for k in repos:
garciadeblas4568a372021-03-24 09:19:48 +0100647 rlist = k.replace("-", "_") + "_repos"
delacruzramoc2d5fc62020-02-05 11:50:21 +0000648 if rlist not in final_content["_admin"]:
649 final_content["_admin"][rlist] = []
650 final_content["_admin"][rlist] += repos[k]
bravofb995ea22021-02-10 10:57:52 -0300651 return final_content
delacruzramoc2d5fc62020-02-05 11:50:21 +0000652
tiernoe19707b2020-04-21 13:08:04 +0000653 def check_conflict_on_del(self, session, _id, db_content):
654 """
655 Check if deletion can be done because of dependencies if it is not force. To override
656 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
657 :param _id: internal _id
658 :param db_content: The database content of this item _id
659 :return: None if ok or raises EngineException with the conflict
660 """
661 if session["force"]:
662 return
663 # check if used by VNF
664 filter_q = {"kdur.k8s-cluster.id": _id}
665 if session["project_id"]:
666 filter_q["_admin.projects_read.cont"] = session["project_id"]
667 if self.db.get_list("vnfrs", filter_q):
garciadeblas4568a372021-03-24 09:19:48 +0100668 raise EngineException(
669 "There is at least one VNF using this k8scluster",
670 http_code=HTTPStatus.CONFLICT,
671 )
tiernoe19707b2020-04-21 13:08:04 +0000672 super().check_conflict_on_del(session, _id, db_content)
673
delacruzramofe598fe2019-10-23 18:25:11 +0200674
David Garciaecb41322021-03-31 19:10:46 +0200675class VcaTopic(CommonVimWimSdn):
676 topic = "vca"
677 topic_msg = "vca"
678 schema_new = vca_new_schema
679 schema_edit = vca_edit_schema
680 multiproject = True
681 password_to_encrypt = None
682
683 def format_on_new(self, content, project_id=None, make_public=False):
684 oid = super().format_on_new(content, project_id, make_public)
685 content["schema_version"] = schema_version = "1.11"
686 for key in ["secret", "cacert"]:
687 content[key] = self.db.encrypt(
garciadeblas4568a372021-03-24 09:19:48 +0100688 content[key], schema_version=schema_version, salt=content["_id"]
David Garciaecb41322021-03-31 19:10:46 +0200689 )
690 return oid
691
692 def format_on_edit(self, final_content, edit_content):
693 oid = super().format_on_edit(final_content, edit_content)
694 schema_version = final_content.get("schema_version")
695 for key in ["secret", "cacert"]:
696 if key in edit_content:
697 final_content[key] = self.db.encrypt(
698 edit_content[key],
699 schema_version=schema_version,
garciadeblas4568a372021-03-24 09:19:48 +0100700 salt=final_content["_id"],
David Garciaecb41322021-03-31 19:10:46 +0200701 )
702 return oid
703
704 def check_conflict_on_del(self, session, _id, db_content):
705 """
706 Check if deletion can be done because of dependencies if it is not force. To override
707 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
708 :param _id: internal _id
709 :param db_content: The database content of this item _id
710 :return: None if ok or raises EngineException with the conflict
711 """
712 if session["force"]:
713 return
714 # check if used by VNF
715 filter_q = {"vca": _id}
716 if session["project_id"]:
717 filter_q["_admin.projects_read.cont"] = session["project_id"]
718 if self.db.get_list("vim_accounts", filter_q):
garciadeblas4568a372021-03-24 09:19:48 +0100719 raise EngineException(
720 "There is at least one VIM account using this vca",
721 http_code=HTTPStatus.CONFLICT,
722 )
David Garciaecb41322021-03-31 19:10:46 +0200723 super().check_conflict_on_del(session, _id, db_content)
724
725
delacruzramofe598fe2019-10-23 18:25:11 +0200726class K8sRepoTopic(CommonVimWimSdn):
727 topic = "k8srepos"
728 topic_msg = "k8srepo"
729 schema_new = k8srepo_new_schema
730 schema_edit = k8srepo_edit_schema
731 multiproject = True
732 password_to_encrypt = None
733 config_to_encrypt = {}
734
delacruzramoc2d5fc62020-02-05 11:50:21 +0000735 def format_on_new(self, content, project_id=None, make_public=False):
736 oid = super().format_on_new(content, project_id, make_public)
737 # Update Helm/Juju Repo lists
garciadeblas4568a372021-03-24 09:19:48 +0100738 repo_list = content["type"].replace("-", "_") + "_repos"
delacruzramoc2d5fc62020-02-05 11:50:21 +0000739 for proj in content["_admin"]["projects_read"]:
garciadeblas4568a372021-03-24 09:19:48 +0100740 if proj != "ANY":
741 self.db.set_list(
742 "k8sclusters",
743 {
744 "_admin.projects_read": proj,
745 "_admin." + repo_list + ".ne": content["_id"],
746 },
747 {},
748 push={"_admin." + repo_list: content["_id"]},
749 )
delacruzramoc2d5fc62020-02-05 11:50:21 +0000750 return oid
751
752 def delete(self, session, _id, dry_run=False, not_send_msg=None):
753 type = self.db.get_one("k8srepos", {"_id": _id})["type"]
754 oid = super().delete(session, _id, dry_run, not_send_msg)
755 if oid:
756 # Remove from Helm/Juju Repo lists
garciadeblas4568a372021-03-24 09:19:48 +0100757 repo_list = type.replace("-", "_") + "_repos"
758 self.db.set_list(
759 "k8sclusters",
760 {"_admin." + repo_list: _id},
761 {},
762 pull={"_admin." + repo_list: _id},
763 )
delacruzramoc2d5fc62020-02-05 11:50:21 +0000764 return oid
765
delacruzramofe598fe2019-10-23 18:25:11 +0200766
Felipe Vicensb66b0412020-05-06 10:11:00 +0200767class OsmRepoTopic(BaseTopic):
768 topic = "osmrepos"
769 topic_msg = "osmrepos"
770 schema_new = osmrepo_new_schema
771 schema_edit = osmrepo_edit_schema
772 multiproject = True
773 # TODO: Implement user/password
774
775
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100776class UserTopicAuth(UserTopic):
tierno65ca36d2019-02-12 19:27:52 +0100777 # topic = "users"
agarwalat53471982020-10-08 13:06:14 +0000778 topic_msg = "users"
Eduardo Sousaa16a4fa2019-05-23 01:41:18 +0100779 schema_new = user_new_schema
780 schema_edit = user_edit_schema
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100781
782 def __init__(self, db, fs, msg, auth):
delacruzramo32bab472019-09-13 12:24:22 +0200783 UserTopic.__init__(self, db, fs, msg, auth)
784 # self.auth = auth
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100785
tierno65ca36d2019-02-12 19:27:52 +0100786 def check_conflict_on_new(self, session, indata):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100787 """
788 Check that the data to be inserted is valid
789
tierno65ca36d2019-02-12 19:27:52 +0100790 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100791 :param indata: data to be inserted
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100792 :return: None or raises EngineException
793 """
794 username = indata.get("username")
tiernocf042d32019-06-13 09:06:40 +0000795 if is_valid_uuid(username):
garciadeblas4568a372021-03-24 09:19:48 +0100796 raise EngineException(
797 "username '{}' cannot have a uuid format".format(username),
798 HTTPStatus.UNPROCESSABLE_ENTITY,
799 )
tiernocf042d32019-06-13 09:06:40 +0000800
801 # Check that username is not used, regardless keystone already checks this
802 if self.auth.get_user_list(filter_q={"name": username}):
garciadeblas4568a372021-03-24 09:19:48 +0100803 raise EngineException(
804 "username '{}' is already used".format(username), HTTPStatus.CONFLICT
805 )
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100806
Eduardo Sousa339ed782019-05-28 14:25:00 +0100807 if "projects" in indata.keys():
tierno701018c2019-06-25 11:13:14 +0000808 # convert to new format project_role_mappings
delacruzramo01b15d32019-07-02 14:37:47 +0200809 role = self.auth.get_role_list({"name": "project_admin"})
810 if not role:
811 role = self.auth.get_role_list()
812 if not role:
garciadeblas4568a372021-03-24 09:19:48 +0100813 raise AuthconnNotFoundException(
814 "Can't find default role for user '{}'".format(username)
815 )
delacruzramo01b15d32019-07-02 14:37:47 +0200816 rid = role[0]["_id"]
tierno701018c2019-06-25 11:13:14 +0000817 if not indata.get("project_role_mappings"):
818 indata["project_role_mappings"] = []
819 for project in indata["projects"]:
delacruzramo01b15d32019-07-02 14:37:47 +0200820 pid = self.auth.get_project(project)["_id"]
821 prm = {"project": pid, "role": rid}
822 if prm not in indata["project_role_mappings"]:
823 indata["project_role_mappings"].append(prm)
tierno701018c2019-06-25 11:13:14 +0000824 # raise EngineException("Format invalid: the keyword 'projects' is not allowed for keystone authentication",
825 # HTTPStatus.BAD_REQUEST)
Eduardo Sousa339ed782019-05-28 14:25:00 +0100826
tierno65ca36d2019-02-12 19:27:52 +0100827 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100828 """
829 Check that the data to be edited/uploaded is valid
830
tierno65ca36d2019-02-12 19:27:52 +0100831 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100832 :param final_content: data once modified
833 :param edit_content: incremental data that contains the modifications to apply
834 :param _id: internal _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100835 :return: None or raises EngineException
836 """
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100837
tiernocf042d32019-06-13 09:06:40 +0000838 if "username" in edit_content:
839 username = edit_content.get("username")
840 if is_valid_uuid(username):
garciadeblas4568a372021-03-24 09:19:48 +0100841 raise EngineException(
842 "username '{}' cannot have an uuid format".format(username),
843 HTTPStatus.UNPROCESSABLE_ENTITY,
844 )
tiernocf042d32019-06-13 09:06:40 +0000845
846 # Check that username is not used, regardless keystone already checks this
847 if self.auth.get_user_list(filter_q={"name": username}):
garciadeblas4568a372021-03-24 09:19:48 +0100848 raise EngineException(
849 "username '{}' is already used".format(username),
850 HTTPStatus.CONFLICT,
851 )
tiernocf042d32019-06-13 09:06:40 +0000852
853 if final_content["username"] == "admin":
854 for mapping in edit_content.get("remove_project_role_mappings", ()):
garciadeblas4568a372021-03-24 09:19:48 +0100855 if mapping["project"] == "admin" and mapping.get("role") in (
856 None,
857 "system_admin",
858 ):
tiernocf042d32019-06-13 09:06:40 +0000859 # TODO make this also available for project id and role id
garciadeblas4568a372021-03-24 09:19:48 +0100860 raise EngineException(
861 "You cannot remove system_admin role from admin user",
862 http_code=HTTPStatus.FORBIDDEN,
863 )
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100864
bravofb995ea22021-02-10 10:57:52 -0300865 return final_content
866
tiernob4844ab2019-05-23 08:42:12 +0000867 def check_conflict_on_del(self, session, _id, db_content):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100868 """
869 Check if deletion can be done because of dependencies if it is not force. To override
tierno65ca36d2019-02-12 19:27:52 +0100870 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100871 :param _id: internal _id
tiernob4844ab2019-05-23 08:42:12 +0000872 :param db_content: The database content of this item _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100873 :return: None if ok or raises EngineException with the conflict
874 """
tiernocf042d32019-06-13 09:06:40 +0000875 if db_content["username"] == session["username"]:
garciadeblas4568a372021-03-24 09:19:48 +0100876 raise EngineException(
877 "You cannot delete your own login user ", http_code=HTTPStatus.CONFLICT
878 )
delacruzramo01b15d32019-07-02 14:37:47 +0200879 # TODO: Check that user is not logged in ? How? (Would require listing current tokens)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100880
Eduardo Sousaa16a4fa2019-05-23 01:41:18 +0100881 @staticmethod
882 def format_on_show(content):
883 """
Eduardo Sousa44603902019-06-04 08:10:32 +0100884 Modifies the content of the role information to separate the role
Eduardo Sousaa16a4fa2019-05-23 01:41:18 +0100885 metadata from the role definition.
886 """
887 project_role_mappings = []
888
delacruzramo01b15d32019-07-02 14:37:47 +0200889 if "projects" in content:
890 for project in content["projects"]:
891 for role in project["roles"]:
garciadeblas4568a372021-03-24 09:19:48 +0100892 project_role_mappings.append(
893 {
894 "project": project["_id"],
895 "project_name": project["name"],
896 "role": role["_id"],
897 "role_name": role["name"],
898 }
899 )
delacruzramo01b15d32019-07-02 14:37:47 +0200900 del content["projects"]
Eduardo Sousaa16a4fa2019-05-23 01:41:18 +0100901 content["project_role_mappings"] = project_role_mappings
902
Eduardo Sousa0b1d61b2019-05-30 19:55:52 +0100903 return content
904
tierno65ca36d2019-02-12 19:27:52 +0100905 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100906 """
907 Creates a new entry into the authentication backend.
908
909 NOTE: Overrides BaseTopic functionality because it doesn't require access to database.
910
911 :param rollback: list to append created items at database in case a rollback may to be done
tierno65ca36d2019-02-12 19:27:52 +0100912 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100913 :param indata: data to be inserted
914 :param kwargs: used to override the indata descriptor
915 :param headers: http request headers
delacruzramo01b15d32019-07-02 14:37:47 +0200916 :return: _id: identity of the inserted data, operation _id (None)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100917 """
918 try:
919 content = BaseTopic._remove_envelop(indata)
920
921 # Override descriptor with query string kwargs
922 BaseTopic._update_input_with_kwargs(content, kwargs)
tierno65ca36d2019-02-12 19:27:52 +0100923 content = self._validate_input_new(content, session["force"])
924 self.check_conflict_on_new(session, content)
tiernocf042d32019-06-13 09:06:40 +0000925 # self.format_on_new(content, session["project_id"], make_public=session["public"])
delacruzramo01b15d32019-07-02 14:37:47 +0200926 now = time()
927 content["_admin"] = {"created": now, "modified": now}
928 prms = []
929 for prm in content.get("project_role_mappings", []):
930 proj = self.auth.get_project(prm["project"], not session["force"])
931 role = self.auth.get_role(prm["role"], not session["force"])
932 pid = proj["_id"] if proj else None
933 rid = role["_id"] if role else None
934 prl = {"project": pid, "role": rid}
935 if prl not in prms:
936 prms.append(prl)
937 content["project_role_mappings"] = prms
938 # _id = self.auth.create_user(content["username"], content["password"])["_id"]
939 _id = self.auth.create_user(content)["_id"]
Eduardo Sousa44603902019-06-04 08:10:32 +0100940
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100941 rollback.append({"topic": self.topic, "_id": _id})
tiernocf042d32019-06-13 09:06:40 +0000942 # del content["password"]
agarwalat53471982020-10-08 13:06:14 +0000943 self._send_msg("created", content, not_send_msg=None)
delacruzramo01b15d32019-07-02 14:37:47 +0200944 return _id, None
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100945 except ValidationError as e:
946 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
947
K Sai Kiran57589552021-01-27 21:38:34 +0530948 def show(self, session, _id, filter_q=None, api_req=False):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100949 """
950 Get complete information on an topic
951
tierno65ca36d2019-02-12 19:27:52 +0100952 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
tierno5ec768a2020-03-31 09:46:44 +0000953 :param _id: server internal id or username
K Sai Kiran57589552021-01-27 21:38:34 +0530954 :param filter_q: dict: query parameter
K Sai Kirand010e3e2020-08-28 15:11:48 +0530955 :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 +0100956 :return: dictionary, raise exception if not found.
957 """
tiernocf042d32019-06-13 09:06:40 +0000958 # Allow _id to be a name or uuid
tiernoad6d5332020-02-19 14:29:49 +0000959 filter_q = {"username": _id}
delacruzramo029405d2019-09-26 10:52:56 +0200960 # users = self.auth.get_user_list(filter_q)
garciadeblas4568a372021-03-24 09:19:48 +0100961 users = self.list(session, filter_q) # To allow default filtering (Bug 853)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100962 if len(users) == 1:
tierno1546f2a2019-08-20 15:38:11 +0000963 return users[0]
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100964 elif len(users) > 1:
garciadeblas4568a372021-03-24 09:19:48 +0100965 raise EngineException(
966 "Too many users found for '{}'".format(_id), HTTPStatus.CONFLICT
967 )
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100968 else:
garciadeblas4568a372021-03-24 09:19:48 +0100969 raise EngineException(
970 "User '{}' not found".format(_id), HTTPStatus.NOT_FOUND
971 )
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100972
tierno65ca36d2019-02-12 19:27:52 +0100973 def edit(self, session, _id, indata=None, kwargs=None, content=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100974 """
975 Updates an user entry.
976
tierno65ca36d2019-02-12 19:27:52 +0100977 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100978 :param _id:
979 :param indata: data to be inserted
980 :param kwargs: used to override the indata descriptor
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100981 :param content:
982 :return: _id: identity of the inserted data.
983 """
984 indata = self._remove_envelop(indata)
985
986 # Override descriptor with query string kwargs
987 if kwargs:
988 BaseTopic._update_input_with_kwargs(indata, kwargs)
989 try:
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100990 if not content:
991 content = self.show(session, _id)
Frank Brydendeba68e2020-07-27 13:55:11 +0000992 indata = self._validate_input_edit(indata, content, force=session["force"])
bravofb995ea22021-02-10 10:57:52 -0300993 content = self.check_conflict_on_edit(session, content, indata, _id=_id)
tiernocf042d32019-06-13 09:06:40 +0000994 # self.format_on_edit(content, indata)
Eduardo Sousa5c01e192019-05-08 02:35:47 +0100995
garciadeblas4568a372021-03-24 09:19:48 +0100996 if not (
997 "password" in indata
998 or "username" in indata
999 or indata.get("remove_project_role_mappings")
1000 or indata.get("add_project_role_mappings")
1001 or indata.get("project_role_mappings")
1002 or indata.get("projects")
1003 or indata.get("add_projects")
1004 ):
tiernocf042d32019-06-13 09:06:40 +00001005 return _id
garciadeblas4568a372021-03-24 09:19:48 +01001006 if indata.get("project_role_mappings") and (
1007 indata.get("remove_project_role_mappings")
1008 or indata.get("add_project_role_mappings")
1009 ):
1010 raise EngineException(
1011 "Option 'project_role_mappings' is incompatible with 'add_project_role_mappings"
1012 "' or 'remove_project_role_mappings'",
1013 http_code=HTTPStatus.BAD_REQUEST,
1014 )
Eduardo Sousa44603902019-06-04 08:10:32 +01001015
delacruzramo01b15d32019-07-02 14:37:47 +02001016 if indata.get("projects") or indata.get("add_projects"):
1017 role = self.auth.get_role_list({"name": "project_admin"})
1018 if not role:
1019 role = self.auth.get_role_list()
1020 if not role:
garciadeblas4568a372021-03-24 09:19:48 +01001021 raise AuthconnNotFoundException(
1022 "Can't find a default role for user '{}'".format(
1023 content["username"]
1024 )
1025 )
delacruzramo01b15d32019-07-02 14:37:47 +02001026 rid = role[0]["_id"]
1027 if "add_project_role_mappings" not in indata:
1028 indata["add_project_role_mappings"] = []
tierno1546f2a2019-08-20 15:38:11 +00001029 if "remove_project_role_mappings" not in indata:
1030 indata["remove_project_role_mappings"] = []
1031 if isinstance(indata.get("projects"), dict):
1032 # backward compatible
1033 for k, v in indata["projects"].items():
1034 if k.startswith("$") and v is None:
garciadeblas4568a372021-03-24 09:19:48 +01001035 indata["remove_project_role_mappings"].append(
1036 {"project": k[1:]}
1037 )
tierno1546f2a2019-08-20 15:38:11 +00001038 elif k.startswith("$+"):
garciadeblas4568a372021-03-24 09:19:48 +01001039 indata["add_project_role_mappings"].append(
1040 {"project": v, "role": rid}
1041 )
tierno1546f2a2019-08-20 15:38:11 +00001042 del indata["projects"]
delacruzramo01b15d32019-07-02 14:37:47 +02001043 for proj in indata.get("projects", []) + indata.get("add_projects", []):
garciadeblas4568a372021-03-24 09:19:48 +01001044 indata["add_project_role_mappings"].append(
1045 {"project": proj, "role": rid}
1046 )
delacruzramo01b15d32019-07-02 14:37:47 +02001047
1048 # user = self.show(session, _id) # Already in 'content'
1049 original_mapping = content["project_role_mappings"]
Eduardo Sousa44603902019-06-04 08:10:32 +01001050
tiernocf042d32019-06-13 09:06:40 +00001051 mappings_to_add = []
1052 mappings_to_remove = []
Eduardo Sousa44603902019-06-04 08:10:32 +01001053
tiernocf042d32019-06-13 09:06:40 +00001054 # remove
1055 for to_remove in indata.get("remove_project_role_mappings", ()):
1056 for mapping in original_mapping:
garciadeblas4568a372021-03-24 09:19:48 +01001057 if to_remove["project"] in (
1058 mapping["project"],
1059 mapping["project_name"],
1060 ):
1061 if not to_remove.get("role") or to_remove["role"] in (
1062 mapping["role"],
1063 mapping["role_name"],
1064 ):
tiernocf042d32019-06-13 09:06:40 +00001065 mappings_to_remove.append(mapping)
Eduardo Sousa44603902019-06-04 08:10:32 +01001066
tiernocf042d32019-06-13 09:06:40 +00001067 # add
1068 for to_add in indata.get("add_project_role_mappings", ()):
1069 for mapping in original_mapping:
garciadeblas4568a372021-03-24 09:19:48 +01001070 if to_add["project"] in (
1071 mapping["project"],
1072 mapping["project_name"],
1073 ) and to_add["role"] in (
1074 mapping["role"],
1075 mapping["role_name"],
1076 ):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001077
garciadeblas4568a372021-03-24 09:19:48 +01001078 if mapping in mappings_to_remove: # do not remove
tiernocf042d32019-06-13 09:06:40 +00001079 mappings_to_remove.remove(mapping)
1080 break # do not add, it is already at user
1081 else:
delacruzramo01b15d32019-07-02 14:37:47 +02001082 pid = self.auth.get_project(to_add["project"])["_id"]
1083 rid = self.auth.get_role(to_add["role"])["_id"]
1084 mappings_to_add.append({"project": pid, "role": rid})
tiernocf042d32019-06-13 09:06:40 +00001085
1086 # set
1087 if indata.get("project_role_mappings"):
1088 for to_set in indata["project_role_mappings"]:
1089 for mapping in original_mapping:
garciadeblas4568a372021-03-24 09:19:48 +01001090 if to_set["project"] in (
1091 mapping["project"],
1092 mapping["project_name"],
1093 ) and to_set["role"] in (
1094 mapping["role"],
1095 mapping["role_name"],
1096 ):
1097 if mapping in mappings_to_remove: # do not remove
tiernocf042d32019-06-13 09:06:40 +00001098 mappings_to_remove.remove(mapping)
1099 break # do not add, it is already at user
1100 else:
delacruzramo01b15d32019-07-02 14:37:47 +02001101 pid = self.auth.get_project(to_set["project"])["_id"]
1102 rid = self.auth.get_role(to_set["role"])["_id"]
1103 mappings_to_add.append({"project": pid, "role": rid})
tiernocf042d32019-06-13 09:06:40 +00001104 for mapping in original_mapping:
1105 for to_set in indata["project_role_mappings"]:
garciadeblas4568a372021-03-24 09:19:48 +01001106 if to_set["project"] in (
1107 mapping["project"],
1108 mapping["project_name"],
1109 ) and to_set["role"] in (
1110 mapping["role"],
1111 mapping["role_name"],
1112 ):
tiernocf042d32019-06-13 09:06:40 +00001113 break
1114 else:
1115 # delete
garciadeblas4568a372021-03-24 09:19:48 +01001116 if mapping not in mappings_to_remove: # do not remove
tiernocf042d32019-06-13 09:06:40 +00001117 mappings_to_remove.append(mapping)
1118
garciadeblas4568a372021-03-24 09:19:48 +01001119 self.auth.update_user(
1120 {
1121 "_id": _id,
1122 "username": indata.get("username"),
1123 "password": indata.get("password"),
selvi.ja9a1fc82022-04-04 06:54:30 +00001124 "old_password": indata.get("old_password"),
garciadeblas4568a372021-03-24 09:19:48 +01001125 "add_project_role_mappings": mappings_to_add,
1126 "remove_project_role_mappings": mappings_to_remove,
1127 }
1128 )
1129 data_to_send = {"_id": _id, "changes": indata}
agarwalat53471982020-10-08 13:06:14 +00001130 self._send_msg("edited", data_to_send, not_send_msg=None)
tiernocf042d32019-06-13 09:06:40 +00001131
delacruzramo01b15d32019-07-02 14:37:47 +02001132 # return _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001133 except ValidationError as e:
1134 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1135
tiernoc4e07d02020-08-14 14:25:32 +00001136 def list(self, session, filter_q=None, api_req=False):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001137 """
1138 Get a list of the topic that matches a filter
tierno65ca36d2019-02-12 19:27:52 +01001139 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001140 :param filter_q: filter of data to be applied
K Sai Kirand010e3e2020-08-28 15:11:48 +05301141 :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 +01001142 :return: The list, it can be empty if no one match the filter.
1143 """
delacruzramo029405d2019-09-26 10:52:56 +02001144 user_list = self.auth.get_user_list(filter_q)
1145 if not session["allow_show_user_project_role"]:
1146 # Bug 853 - Default filtering
garciadeblas4568a372021-03-24 09:19:48 +01001147 user_list = [
1148 usr for usr in user_list if usr["username"] == session["username"]
1149 ]
delacruzramo029405d2019-09-26 10:52:56 +02001150 return user_list
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001151
tiernobee3bad2019-12-05 12:26:01 +00001152 def delete(self, session, _id, dry_run=False, not_send_msg=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001153 """
1154 Delete item by its internal _id
1155
tierno65ca36d2019-02-12 19:27:52 +01001156 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001157 :param _id: server internal id
1158 :param force: indicates if deletion must be forced in case of conflict
1159 :param dry_run: make checking but do not delete
tiernobee3bad2019-12-05 12:26:01 +00001160 :param not_send_msg: To not send message (False) or store content (list) instead
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001161 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
1162 """
tiernocf042d32019-06-13 09:06:40 +00001163 # Allow _id to be a name or uuid
delacruzramo01b15d32019-07-02 14:37:47 +02001164 user = self.auth.get_user(_id)
1165 uid = user["_id"]
1166 self.check_conflict_on_del(session, uid, user)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001167 if not dry_run:
delacruzramo01b15d32019-07-02 14:37:47 +02001168 v = self.auth.delete_user(uid)
agarwalat53471982020-10-08 13:06:14 +00001169 self._send_msg("deleted", user, not_send_msg=not_send_msg)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001170 return v
1171 return None
1172
1173
1174class ProjectTopicAuth(ProjectTopic):
tierno65ca36d2019-02-12 19:27:52 +01001175 # topic = "projects"
agarwalat53471982020-10-08 13:06:14 +00001176 topic_msg = "project"
Eduardo Sousa44603902019-06-04 08:10:32 +01001177 schema_new = project_new_schema
1178 schema_edit = project_edit_schema
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001179
1180 def __init__(self, db, fs, msg, auth):
delacruzramo32bab472019-09-13 12:24:22 +02001181 ProjectTopic.__init__(self, db, fs, msg, auth)
1182 # self.auth = auth
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001183
tierno65ca36d2019-02-12 19:27:52 +01001184 def check_conflict_on_new(self, session, indata):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001185 """
1186 Check that the data to be inserted is valid
1187
tierno65ca36d2019-02-12 19:27:52 +01001188 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001189 :param indata: data to be inserted
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001190 :return: None or raises EngineException
1191 """
tiernocf042d32019-06-13 09:06:40 +00001192 project_name = indata.get("name")
1193 if is_valid_uuid(project_name):
garciadeblas4568a372021-03-24 09:19:48 +01001194 raise EngineException(
1195 "project name '{}' cannot have an uuid format".format(project_name),
1196 HTTPStatus.UNPROCESSABLE_ENTITY,
1197 )
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001198
tiernocf042d32019-06-13 09:06:40 +00001199 project_list = self.auth.get_project_list(filter_q={"name": project_name})
1200
1201 if project_list:
garciadeblas4568a372021-03-24 09:19:48 +01001202 raise EngineException(
1203 "project '{}' exists".format(project_name), HTTPStatus.CONFLICT
1204 )
tiernocf042d32019-06-13 09:06:40 +00001205
1206 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
1207 """
1208 Check that the data to be edited/uploaded is valid
1209
1210 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1211 :param final_content: data once modified
1212 :param edit_content: incremental data that contains the modifications to apply
1213 :param _id: internal _id
1214 :return: None or raises EngineException
1215 """
1216
1217 project_name = edit_content.get("name")
delacruzramo01b15d32019-07-02 14:37:47 +02001218 if project_name != final_content["name"]: # It is a true renaming
tiernocf042d32019-06-13 09:06:40 +00001219 if is_valid_uuid(project_name):
garciadeblas4568a372021-03-24 09:19:48 +01001220 raise EngineException(
1221 "project name '{}' cannot have an uuid format".format(project_name),
1222 HTTPStatus.UNPROCESSABLE_ENTITY,
1223 )
tiernocf042d32019-06-13 09:06:40 +00001224
delacruzramo01b15d32019-07-02 14:37:47 +02001225 if final_content["name"] == "admin":
garciadeblas4568a372021-03-24 09:19:48 +01001226 raise EngineException(
1227 "You cannot rename project 'admin'", http_code=HTTPStatus.CONFLICT
1228 )
delacruzramo01b15d32019-07-02 14:37:47 +02001229
tiernocf042d32019-06-13 09:06:40 +00001230 # Check that project name is not used, regardless keystone already checks this
garciadeblas4568a372021-03-24 09:19:48 +01001231 if project_name and self.auth.get_project_list(
1232 filter_q={"name": project_name}
1233 ):
1234 raise EngineException(
1235 "project '{}' is already used".format(project_name),
1236 HTTPStatus.CONFLICT,
1237 )
bravofb995ea22021-02-10 10:57:52 -03001238 return final_content
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001239
tiernob4844ab2019-05-23 08:42:12 +00001240 def check_conflict_on_del(self, session, _id, db_content):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001241 """
1242 Check if deletion can be done because of dependencies if it is not force. To override
1243
tierno65ca36d2019-02-12 19:27:52 +01001244 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001245 :param _id: internal _id
tiernob4844ab2019-05-23 08:42:12 +00001246 :param db_content: The database content of this item _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001247 :return: None if ok or raises EngineException with the conflict
1248 """
delacruzramo01b15d32019-07-02 14:37:47 +02001249
1250 def check_rw_projects(topic, title, id_field):
1251 for desc in self.db.get_list(topic):
garciadeblas4568a372021-03-24 09:19:48 +01001252 if (
1253 _id
1254 in desc["_admin"]["projects_read"]
1255 + desc["_admin"]["projects_write"]
1256 ):
1257 raise EngineException(
1258 "Project '{}' ({}) is being used by {} '{}'".format(
1259 db_content["name"], _id, title, desc[id_field]
1260 ),
1261 HTTPStatus.CONFLICT,
1262 )
delacruzramo01b15d32019-07-02 14:37:47 +02001263
1264 if _id in session["project_id"]:
garciadeblas4568a372021-03-24 09:19:48 +01001265 raise EngineException(
1266 "You cannot delete your own project", http_code=HTTPStatus.CONFLICT
1267 )
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001268
delacruzramo01b15d32019-07-02 14:37:47 +02001269 if db_content["name"] == "admin":
garciadeblas4568a372021-03-24 09:19:48 +01001270 raise EngineException(
1271 "You cannot delete project 'admin'", http_code=HTTPStatus.CONFLICT
1272 )
delacruzramo01b15d32019-07-02 14:37:47 +02001273
1274 # If any user is using this project, raise CONFLICT exception
1275 if not session["force"]:
1276 for user in self.auth.get_user_list():
tierno1546f2a2019-08-20 15:38:11 +00001277 for prm in user.get("project_role_mappings"):
1278 if prm["project"] == _id:
garciadeblas4568a372021-03-24 09:19:48 +01001279 raise EngineException(
1280 "Project '{}' ({}) is being used by user '{}'".format(
1281 db_content["name"], _id, user["username"]
1282 ),
1283 HTTPStatus.CONFLICT,
1284 )
delacruzramo01b15d32019-07-02 14:37:47 +02001285
1286 # If any VNFD, NSD, NST, PDU, etc. is using this project, raise CONFLICT exception
1287 if not session["force"]:
1288 check_rw_projects("vnfds", "VNF Descriptor", "id")
1289 check_rw_projects("nsds", "NS Descriptor", "id")
1290 check_rw_projects("nsts", "NS Template", "id")
1291 check_rw_projects("pdus", "PDU Descriptor", "name")
1292
tierno65ca36d2019-02-12 19:27:52 +01001293 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001294 """
1295 Creates a new entry into the authentication backend.
1296
1297 NOTE: Overrides BaseTopic functionality because it doesn't require access to database.
1298
1299 :param rollback: list to append created items at database in case a rollback may to be done
tierno65ca36d2019-02-12 19:27:52 +01001300 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001301 :param indata: data to be inserted
1302 :param kwargs: used to override the indata descriptor
1303 :param headers: http request headers
delacruzramo01b15d32019-07-02 14:37:47 +02001304 :return: _id: identity of the inserted data, operation _id (None)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001305 """
1306 try:
1307 content = BaseTopic._remove_envelop(indata)
1308
1309 # Override descriptor with query string kwargs
1310 BaseTopic._update_input_with_kwargs(content, kwargs)
tierno65ca36d2019-02-12 19:27:52 +01001311 content = self._validate_input_new(content, session["force"])
1312 self.check_conflict_on_new(session, content)
garciadeblas4568a372021-03-24 09:19:48 +01001313 self.format_on_new(
1314 content, project_id=session["project_id"], make_public=session["public"]
1315 )
delacruzramo01b15d32019-07-02 14:37:47 +02001316 _id = self.auth.create_project(content)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001317 rollback.append({"topic": self.topic, "_id": _id})
agarwalat53471982020-10-08 13:06:14 +00001318 self._send_msg("created", content, not_send_msg=None)
delacruzramo01b15d32019-07-02 14:37:47 +02001319 return _id, None
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001320 except ValidationError as e:
1321 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1322
K Sai Kiran57589552021-01-27 21:38:34 +05301323 def show(self, session, _id, filter_q=None, api_req=False):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001324 """
1325 Get complete information on an topic
1326
tierno65ca36d2019-02-12 19:27:52 +01001327 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001328 :param _id: server internal id
K Sai Kiran57589552021-01-27 21:38:34 +05301329 :param filter_q: dict: query parameter
K Sai Kirand010e3e2020-08-28 15:11:48 +05301330 :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 +01001331 :return: dictionary, raise exception if not found.
1332 """
tiernocf042d32019-06-13 09:06:40 +00001333 # Allow _id to be a name or uuid
1334 filter_q = {self.id_field(self.topic, _id): _id}
delacruzramo029405d2019-09-26 10:52:56 +02001335 # projects = self.auth.get_project_list(filter_q=filter_q)
garciadeblas4568a372021-03-24 09:19:48 +01001336 projects = self.list(session, filter_q) # To allow default filtering (Bug 853)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001337 if len(projects) == 1:
1338 return projects[0]
1339 elif len(projects) > 1:
1340 raise EngineException("Too many projects found", HTTPStatus.CONFLICT)
1341 else:
1342 raise EngineException("Project not found", HTTPStatus.NOT_FOUND)
1343
tiernoc4e07d02020-08-14 14:25:32 +00001344 def list(self, session, filter_q=None, api_req=False):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001345 """
1346 Get a list of the topic that matches a filter
1347
tierno65ca36d2019-02-12 19:27:52 +01001348 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001349 :param filter_q: filter of data to be applied
1350 :return: The list, it can be empty if no one match the filter.
1351 """
delacruzramo029405d2019-09-26 10:52:56 +02001352 project_list = self.auth.get_project_list(filter_q)
1353 if not session["allow_show_user_project_role"]:
1354 # Bug 853 - Default filtering
1355 user = self.auth.get_user(session["username"])
1356 projects = [prm["project"] for prm in user["project_role_mappings"]]
1357 project_list = [proj for proj in project_list if proj["_id"] in projects]
1358 return project_list
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001359
tiernobee3bad2019-12-05 12:26:01 +00001360 def delete(self, session, _id, dry_run=False, not_send_msg=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001361 """
1362 Delete item by its internal _id
1363
tierno65ca36d2019-02-12 19:27:52 +01001364 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001365 :param _id: server internal id
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001366 :param dry_run: make checking but do not delete
tiernobee3bad2019-12-05 12:26:01 +00001367 :param not_send_msg: To not send message (False) or store content (list) instead
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001368 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
1369 """
tiernocf042d32019-06-13 09:06:40 +00001370 # Allow _id to be a name or uuid
delacruzramo01b15d32019-07-02 14:37:47 +02001371 proj = self.auth.get_project(_id)
1372 pid = proj["_id"]
1373 self.check_conflict_on_del(session, pid, proj)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001374 if not dry_run:
delacruzramo01b15d32019-07-02 14:37:47 +02001375 v = self.auth.delete_project(pid)
agarwalat53471982020-10-08 13:06:14 +00001376 self._send_msg("deleted", proj, not_send_msg=None)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001377 return v
1378 return None
1379
tierno4015b472019-06-10 13:57:29 +00001380 def edit(self, session, _id, indata=None, kwargs=None, content=None):
1381 """
1382 Updates a project entry.
1383
1384 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1385 :param _id:
1386 :param indata: data to be inserted
1387 :param kwargs: used to override the indata descriptor
1388 :param content:
1389 :return: _id: identity of the inserted data.
1390 """
1391 indata = self._remove_envelop(indata)
1392
1393 # Override descriptor with query string kwargs
1394 if kwargs:
1395 BaseTopic._update_input_with_kwargs(indata, kwargs)
1396 try:
tierno4015b472019-06-10 13:57:29 +00001397 if not content:
1398 content = self.show(session, _id)
Frank Brydendeba68e2020-07-27 13:55:11 +00001399 indata = self._validate_input_edit(indata, content, force=session["force"])
bravofb995ea22021-02-10 10:57:52 -03001400 content = self.check_conflict_on_edit(session, content, indata, _id=_id)
delacruzramo01b15d32019-07-02 14:37:47 +02001401 self.format_on_edit(content, indata)
agarwalat53471982020-10-08 13:06:14 +00001402 content_original = copy.deepcopy(content)
delacruzramo32bab472019-09-13 12:24:22 +02001403 deep_update_rfc7396(content, indata)
delacruzramo01b15d32019-07-02 14:37:47 +02001404 self.auth.update_project(content["_id"], content)
agarwalat53471982020-10-08 13:06:14 +00001405 proj_data = {"_id": _id, "changes": indata, "original": content_original}
1406 self._send_msg("edited", proj_data, not_send_msg=None)
tierno4015b472019-06-10 13:57:29 +00001407 except ValidationError as e:
1408 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1409
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001410
1411class RoleTopicAuth(BaseTopic):
delacruzramoceb8baf2019-06-21 14:25:38 +02001412 topic = "roles"
garciadeblas4568a372021-03-24 09:19:48 +01001413 topic_msg = None # "roles"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001414 schema_new = roles_new_schema
1415 schema_edit = roles_edit_schema
tierno65ca36d2019-02-12 19:27:52 +01001416 multiproject = False
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001417
tierno9e87a7f2020-03-23 09:24:10 +00001418 def __init__(self, db, fs, msg, auth):
delacruzramo32bab472019-09-13 12:24:22 +02001419 BaseTopic.__init__(self, db, fs, msg, auth)
1420 # self.auth = auth
tierno9e87a7f2020-03-23 09:24:10 +00001421 self.operations = auth.role_permissions
delacruzramo01b15d32019-07-02 14:37:47 +02001422 # self.topic = "roles_operations" if isinstance(auth, AuthconnKeystone) else "roles"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001423
1424 @staticmethod
1425 def validate_role_definition(operations, role_definitions):
1426 """
1427 Validates the role definition against the operations defined in
1428 the resources to operations files.
1429
1430 :param operations: operations list
1431 :param role_definitions: role definition to test
1432 :return: None if ok, raises ValidationError exception on error
1433 """
tierno1f029d82019-06-13 22:37:04 +00001434 if not role_definitions.get("permissions"):
1435 return
1436 ignore_fields = ["admin", "default"]
1437 for role_def in role_definitions["permissions"].keys():
Eduardo Sousa37de0912019-05-23 02:17:22 +01001438 if role_def in ignore_fields:
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001439 continue
Eduardo Sousac7689372019-06-04 16:01:46 +01001440 if role_def[-1] == ":":
tierno1f029d82019-06-13 22:37:04 +00001441 raise ValidationError("Operation cannot end with ':'")
Eduardo Sousac5a18892019-06-06 14:51:23 +01001442
garciadeblas4568a372021-03-24 09:19:48 +01001443 match = next(
1444 (
1445 op
1446 for op in operations
1447 if op == role_def or op.startswith(role_def + ":")
1448 ),
1449 None,
1450 )
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001451
tierno97639b42020-08-04 12:48:15 +00001452 if not match:
tierno1f029d82019-06-13 22:37:04 +00001453 raise ValidationError("Invalid permission '{}'".format(role_def))
Eduardo Sousa37de0912019-05-23 02:17:22 +01001454
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001455 def _validate_input_new(self, input, force=False):
1456 """
1457 Validates input user content for a new entry.
1458
1459 :param input: user input content for the new topic
1460 :param force: may be used for being more tolerant
1461 :return: The same input content, or a changed version of it.
1462 """
1463 if self.schema_new:
1464 validate_input(input, self.schema_new)
Eduardo Sousa37de0912019-05-23 02:17:22 +01001465 self.validate_role_definition(self.operations, input)
Eduardo Sousac4650362019-06-04 13:24:22 +01001466
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001467 return input
1468
Frank Brydendeba68e2020-07-27 13:55:11 +00001469 def _validate_input_edit(self, input, content, force=False):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001470 """
1471 Validates input user content for updating an entry.
1472
1473 :param input: user input content for the new topic
1474 :param force: may be used for being more tolerant
1475 :return: The same input content, or a changed version of it.
1476 """
1477 if self.schema_edit:
1478 validate_input(input, self.schema_edit)
Eduardo Sousa37de0912019-05-23 02:17:22 +01001479 self.validate_role_definition(self.operations, input)
Eduardo Sousac4650362019-06-04 13:24:22 +01001480
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001481 return input
1482
tierno65ca36d2019-02-12 19:27:52 +01001483 def check_conflict_on_new(self, session, indata):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001484 """
1485 Check that the data to be inserted is valid
1486
tierno65ca36d2019-02-12 19:27:52 +01001487 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001488 :param indata: data to be inserted
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001489 :return: None or raises EngineException
1490 """
delacruzramo79e40f42019-10-10 16:36:40 +02001491 # check name is not uuid
1492 role_name = indata.get("name")
1493 if is_valid_uuid(role_name):
garciadeblas4568a372021-03-24 09:19:48 +01001494 raise EngineException(
1495 "role name '{}' cannot have an uuid format".format(role_name),
1496 HTTPStatus.UNPROCESSABLE_ENTITY,
1497 )
tierno1f029d82019-06-13 22:37:04 +00001498 # check name not exists
delacruzramo01b15d32019-07-02 14:37:47 +02001499 name = indata["name"]
1500 # if self.db.get_one(self.topic, {"name": indata.get("name")}, fail_on_empty=False, fail_on_more=False):
1501 if self.auth.get_role_list({"name": name}):
garciadeblas4568a372021-03-24 09:19:48 +01001502 raise EngineException(
1503 "role name '{}' exists".format(name), HTTPStatus.CONFLICT
1504 )
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001505
tierno65ca36d2019-02-12 19:27:52 +01001506 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001507 """
1508 Check that the data to be edited/uploaded is valid
1509
tierno65ca36d2019-02-12 19:27:52 +01001510 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001511 :param final_content: data once modified
1512 :param edit_content: incremental data that contains the modifications to apply
1513 :param _id: internal _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001514 :return: None or raises EngineException
1515 """
tierno1f029d82019-06-13 22:37:04 +00001516 if "default" not in final_content["permissions"]:
1517 final_content["permissions"]["default"] = False
1518 if "admin" not in final_content["permissions"]:
1519 final_content["permissions"]["admin"] = False
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001520
delacruzramo79e40f42019-10-10 16:36:40 +02001521 # check name is not uuid
1522 role_name = edit_content.get("name")
1523 if is_valid_uuid(role_name):
garciadeblas4568a372021-03-24 09:19:48 +01001524 raise EngineException(
1525 "role name '{}' cannot have an uuid format".format(role_name),
1526 HTTPStatus.UNPROCESSABLE_ENTITY,
1527 )
delacruzramo79e40f42019-10-10 16:36:40 +02001528
1529 # Check renaming of admin roles
1530 role = self.auth.get_role(_id)
1531 if role["name"] in ["system_admin", "project_admin"]:
garciadeblas4568a372021-03-24 09:19:48 +01001532 raise EngineException(
1533 "You cannot rename role '{}'".format(role["name"]),
1534 http_code=HTTPStatus.FORBIDDEN,
1535 )
delacruzramo79e40f42019-10-10 16:36:40 +02001536
tierno1f029d82019-06-13 22:37:04 +00001537 # check name not exists
1538 if "name" in edit_content:
1539 role_name = edit_content["name"]
delacruzramo01b15d32019-07-02 14:37:47 +02001540 # if self.db.get_one(self.topic, {"name":role_name,"_id.ne":_id}, fail_on_empty=False, fail_on_more=False):
1541 roles = self.auth.get_role_list({"name": role_name})
1542 if roles and roles[0][BaseTopic.id_field("roles", _id)] != _id:
garciadeblas4568a372021-03-24 09:19:48 +01001543 raise EngineException(
1544 "role name '{}' exists".format(role_name), HTTPStatus.CONFLICT
1545 )
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001546
bravofb995ea22021-02-10 10:57:52 -03001547 return final_content
1548
tiernob4844ab2019-05-23 08:42:12 +00001549 def check_conflict_on_del(self, session, _id, db_content):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001550 """
1551 Check if deletion can be done because of dependencies if it is not force. To override
1552
tierno65ca36d2019-02-12 19:27:52 +01001553 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001554 :param _id: internal _id
tiernob4844ab2019-05-23 08:42:12 +00001555 :param db_content: The database content of this item _id
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001556 :return: None if ok or raises EngineException with the conflict
1557 """
delacruzramo01b15d32019-07-02 14:37:47 +02001558 role = self.auth.get_role(_id)
1559 if role["name"] in ["system_admin", "project_admin"]:
garciadeblas4568a372021-03-24 09:19:48 +01001560 raise EngineException(
1561 "You cannot delete role '{}'".format(role["name"]),
1562 http_code=HTTPStatus.FORBIDDEN,
1563 )
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001564
delacruzramo01b15d32019-07-02 14:37:47 +02001565 # If any user is using this role, raise CONFLICT exception
delacruzramoad682a52019-12-10 16:26:34 +01001566 if not session["force"]:
1567 for user in self.auth.get_user_list():
1568 for prm in user.get("project_role_mappings"):
1569 if prm["role"] == _id:
garciadeblas4568a372021-03-24 09:19:48 +01001570 raise EngineException(
1571 "Role '{}' ({}) is being used by user '{}'".format(
1572 role["name"], _id, user["username"]
1573 ),
1574 HTTPStatus.CONFLICT,
1575 )
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001576
1577 @staticmethod
garciadeblas4568a372021-03-24 09:19:48 +01001578 def format_on_new(content, project_id=None, make_public=False): # TO BE REMOVED ?
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001579 """
1580 Modifies content descriptor to include _admin
1581
1582 :param content: descriptor to be modified
1583 :param project_id: if included, it add project read/write permissions
1584 :param make_public: if included it is generated as public for reading.
1585 :return: None, but content is modified
1586 """
1587 now = time()
1588 if "_admin" not in content:
1589 content["_admin"] = {}
1590 if not content["_admin"].get("created"):
1591 content["_admin"]["created"] = now
1592 content["_admin"]["modified"] = now
Eduardo Sousac4650362019-06-04 13:24:22 +01001593
tierno1f029d82019-06-13 22:37:04 +00001594 if "permissions" not in content:
1595 content["permissions"] = {}
Eduardo Sousac4650362019-06-04 13:24:22 +01001596
tierno1f029d82019-06-13 22:37:04 +00001597 if "default" not in content["permissions"]:
1598 content["permissions"]["default"] = False
1599 if "admin" not in content["permissions"]:
1600 content["permissions"]["admin"] = False
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001601
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001602 @staticmethod
1603 def format_on_edit(final_content, edit_content):
1604 """
1605 Modifies final_content descriptor to include the modified date.
1606
1607 :param final_content: final descriptor generated
1608 :param edit_content: alterations to be include
1609 :return: None, but final_content is modified
1610 """
delacruzramo01b15d32019-07-02 14:37:47 +02001611 if "_admin" in final_content:
1612 final_content["_admin"]["modified"] = time()
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001613
tierno1f029d82019-06-13 22:37:04 +00001614 if "permissions" not in final_content:
1615 final_content["permissions"] = {}
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001616
tierno1f029d82019-06-13 22:37:04 +00001617 if "default" not in final_content["permissions"]:
1618 final_content["permissions"]["default"] = False
1619 if "admin" not in final_content["permissions"]:
1620 final_content["permissions"]["admin"] = False
tiernobdebce92019-07-01 15:36:49 +00001621 return None
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001622
K Sai Kiran57589552021-01-27 21:38:34 +05301623 def show(self, session, _id, filter_q=None, api_req=False):
delacruzramo01b15d32019-07-02 14:37:47 +02001624 """
1625 Get complete information on an topic
Eduardo Sousac4650362019-06-04 13:24:22 +01001626
delacruzramo01b15d32019-07-02 14:37:47 +02001627 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1628 :param _id: server internal id
K Sai Kiran57589552021-01-27 21:38:34 +05301629 :param filter_q: dict: query parameter
K Sai Kirand010e3e2020-08-28 15:11:48 +05301630 :param api_req: True if this call is serving an external API request. False if serving internal request.
delacruzramo01b15d32019-07-02 14:37:47 +02001631 :return: dictionary, raise exception if not found.
1632 """
1633 filter_q = {BaseTopic.id_field(self.topic, _id): _id}
delacruzramo029405d2019-09-26 10:52:56 +02001634 # roles = self.auth.get_role_list(filter_q)
garciadeblas4568a372021-03-24 09:19:48 +01001635 roles = self.list(session, filter_q) # To allow default filtering (Bug 853)
delacruzramo01b15d32019-07-02 14:37:47 +02001636 if not roles:
garciadeblas4568a372021-03-24 09:19:48 +01001637 raise AuthconnNotFoundException(
1638 "Not found any role with filter {}".format(filter_q)
1639 )
delacruzramo01b15d32019-07-02 14:37:47 +02001640 elif len(roles) > 1:
garciadeblas4568a372021-03-24 09:19:48 +01001641 raise AuthconnConflictException(
1642 "Found more than one role with filter {}".format(filter_q)
1643 )
delacruzramo01b15d32019-07-02 14:37:47 +02001644 return roles[0]
1645
tiernoc4e07d02020-08-14 14:25:32 +00001646 def list(self, session, filter_q=None, api_req=False):
delacruzramo01b15d32019-07-02 14:37:47 +02001647 """
1648 Get a list of the topic that matches a filter
1649
1650 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1651 :param filter_q: filter of data to be applied
1652 :return: The list, it can be empty if no one match the filter.
1653 """
delacruzramo029405d2019-09-26 10:52:56 +02001654 role_list = self.auth.get_role_list(filter_q)
1655 if not session["allow_show_user_project_role"]:
1656 # Bug 853 - Default filtering
1657 user = self.auth.get_user(session["username"])
1658 roles = [prm["role"] for prm in user["project_role_mappings"]]
1659 role_list = [role for role in role_list if role["_id"] in roles]
1660 return role_list
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001661
tierno65ca36d2019-02-12 19:27:52 +01001662 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001663 """
1664 Creates a new entry into database.
1665
1666 :param rollback: list to append created items at database in case a rollback may to be done
tierno65ca36d2019-02-12 19:27:52 +01001667 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001668 :param indata: data to be inserted
1669 :param kwargs: used to override the indata descriptor
1670 :param headers: http request headers
delacruzramo01b15d32019-07-02 14:37:47 +02001671 :return: _id: identity of the inserted data, operation _id (None)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001672 """
1673 try:
tierno1f029d82019-06-13 22:37:04 +00001674 content = self._remove_envelop(indata)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001675
1676 # Override descriptor with query string kwargs
tierno1f029d82019-06-13 22:37:04 +00001677 self._update_input_with_kwargs(content, kwargs)
tierno65ca36d2019-02-12 19:27:52 +01001678 content = self._validate_input_new(content, session["force"])
1679 self.check_conflict_on_new(session, content)
garciadeblas4568a372021-03-24 09:19:48 +01001680 self.format_on_new(
1681 content, project_id=session["project_id"], make_public=session["public"]
1682 )
delacruzramo01b15d32019-07-02 14:37:47 +02001683 # role_name = content["name"]
1684 rid = self.auth.create_role(content)
1685 content["_id"] = rid
1686 # _id = self.db.create(self.topic, content)
1687 rollback.append({"topic": self.topic, "_id": rid})
tiernobee3bad2019-12-05 12:26:01 +00001688 # self._send_msg("created", content, not_send_msg=not_send_msg)
delacruzramo01b15d32019-07-02 14:37:47 +02001689 return rid, None
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001690 except ValidationError as e:
1691 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1692
tiernobee3bad2019-12-05 12:26:01 +00001693 def delete(self, session, _id, dry_run=False, not_send_msg=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001694 """
1695 Delete item by its internal _id
1696
tierno65ca36d2019-02-12 19:27:52 +01001697 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001698 :param _id: server internal id
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001699 :param dry_run: make checking but do not delete
tiernobee3bad2019-12-05 12:26:01 +00001700 :param not_send_msg: To not send message (False) or store content (list) instead
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001701 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
1702 """
delacruzramo01b15d32019-07-02 14:37:47 +02001703 filter_q = {BaseTopic.id_field(self.topic, _id): _id}
1704 roles = self.auth.get_role_list(filter_q)
1705 if not roles:
garciadeblas4568a372021-03-24 09:19:48 +01001706 raise AuthconnNotFoundException(
1707 "Not found any role with filter {}".format(filter_q)
1708 )
delacruzramo01b15d32019-07-02 14:37:47 +02001709 elif len(roles) > 1:
garciadeblas4568a372021-03-24 09:19:48 +01001710 raise AuthconnConflictException(
1711 "Found more than one role with filter {}".format(filter_q)
1712 )
delacruzramo01b15d32019-07-02 14:37:47 +02001713 rid = roles[0]["_id"]
1714 self.check_conflict_on_del(session, rid, None)
delacruzramoceb8baf2019-06-21 14:25:38 +02001715 # filter_q = {"_id": _id}
delacruzramo01b15d32019-07-02 14:37:47 +02001716 # filter_q = {BaseTopic.id_field(self.topic, _id): _id} # To allow role addressing by name
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001717 if not dry_run:
delacruzramo01b15d32019-07-02 14:37:47 +02001718 v = self.auth.delete_role(rid)
1719 # v = self.db.del_one(self.topic, filter_q)
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001720 return v
1721 return None
1722
tierno65ca36d2019-02-12 19:27:52 +01001723 def edit(self, session, _id, indata=None, kwargs=None, content=None):
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001724 """
1725 Updates a role entry.
1726
tierno65ca36d2019-02-12 19:27:52 +01001727 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001728 :param _id:
1729 :param indata: data to be inserted
1730 :param kwargs: used to override the indata descriptor
Eduardo Sousa5c01e192019-05-08 02:35:47 +01001731 :param content:
1732 :return: _id: identity of the inserted data.
1733 """
delacruzramo01b15d32019-07-02 14:37:47 +02001734 if kwargs:
1735 self._update_input_with_kwargs(indata, kwargs)
1736 try:
delacruzramo01b15d32019-07-02 14:37:47 +02001737 if not content:
1738 content = self.show(session, _id)
Frank Brydendeba68e2020-07-27 13:55:11 +00001739 indata = self._validate_input_edit(indata, content, force=session["force"])
delacruzramo01b15d32019-07-02 14:37:47 +02001740 deep_update_rfc7396(content, indata)
bravofb995ea22021-02-10 10:57:52 -03001741 content = self.check_conflict_on_edit(session, content, indata, _id=_id)
delacruzramo01b15d32019-07-02 14:37:47 +02001742 self.format_on_edit(content, indata)
1743 self.auth.update_role(content)
1744 except ValidationError as e:
1745 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)