Fix Bug 1011: Multiple interface referenced to a single connection point
[osm/NBI.git] / osm_nbi / admin_topics.py
1 # -*- coding: utf-8 -*-
2
3 # 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
16 # import logging
17 from uuid import uuid4
18 from hashlib import sha256
19 from http import HTTPStatus
20 from time import time
21 from osm_nbi.validation import user_new_schema, user_edit_schema, project_new_schema, project_edit_schema, \
22 vim_account_new_schema, vim_account_edit_schema, sdn_new_schema, sdn_edit_schema, \
23 wim_account_new_schema, wim_account_edit_schema, roles_new_schema, roles_edit_schema, \
24 k8scluster_new_schema, k8scluster_edit_schema, k8srepo_new_schema, k8srepo_edit_schema, \
25 validate_input, ValidationError, is_valid_uuid # To check that User/Project Names don't look like UUIDs
26 from osm_nbi.base_topic import BaseTopic, EngineException
27 from osm_nbi.authconn import AuthconnNotFoundException, AuthconnConflictException
28 from osm_common.dbbase import deep_update_rfc7396
29
30 __author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
31
32
33 class UserTopic(BaseTopic):
34 topic = "users"
35 topic_msg = "users"
36 schema_new = user_new_schema
37 schema_edit = user_edit_schema
38 multiproject = False
39
40 def __init__(self, db, fs, msg, auth):
41 BaseTopic.__init__(self, db, fs, msg, auth)
42
43 @staticmethod
44 def _get_project_filter(session):
45 """
46 Generates a filter dictionary for querying database users.
47 Current policy is admin can show all, non admin, only its own user.
48 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
49 :return:
50 """
51 if session["admin"]: # allows all
52 return {}
53 else:
54 return {"username": session["username"]}
55
56 def check_conflict_on_new(self, session, indata):
57 # check username not exists
58 if self.db.get_one(self.topic, {"username": indata.get("username")}, fail_on_empty=False, fail_on_more=False):
59 raise EngineException("username '{}' exists".format(indata["username"]), HTTPStatus.CONFLICT)
60 # check projects
61 if not session["force"]:
62 for p in indata.get("projects") or []:
63 # To allow project addressing by Name as well as ID
64 if not self.db.get_one("projects", {BaseTopic.id_field("projects", p): p}, fail_on_empty=False,
65 fail_on_more=False):
66 raise EngineException("project '{}' does not exist".format(p), HTTPStatus.CONFLICT)
67
68 def check_conflict_on_del(self, session, _id, db_content):
69 """
70 Check if deletion can be done because of dependencies if it is not force. To override
71 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
72 :param _id: internal _id
73 :param db_content: The database content of this item _id
74 :return: None if ok or raises EngineException with the conflict
75 """
76 if _id == session["username"]:
77 raise EngineException("You cannot delete your own user", http_code=HTTPStatus.CONFLICT)
78
79 @staticmethod
80 def format_on_new(content, project_id=None, make_public=False):
81 BaseTopic.format_on_new(content, make_public=False)
82 # Removed so that the UUID is kept, to allow User Name modification
83 # content["_id"] = content["username"]
84 salt = uuid4().hex
85 content["_admin"]["salt"] = salt
86 if content.get("password"):
87 content["password"] = sha256(content["password"].encode('utf-8') + salt.encode('utf-8')).hexdigest()
88 if content.get("project_role_mappings"):
89 projects = [mapping["project"] for mapping in content["project_role_mappings"]]
90
91 if content.get("projects"):
92 content["projects"] += projects
93 else:
94 content["projects"] = projects
95
96 @staticmethod
97 def format_on_edit(final_content, edit_content):
98 BaseTopic.format_on_edit(final_content, edit_content)
99 if edit_content.get("password"):
100 salt = uuid4().hex
101 final_content["_admin"]["salt"] = salt
102 final_content["password"] = sha256(edit_content["password"].encode('utf-8') +
103 salt.encode('utf-8')).hexdigest()
104 return None
105
106 def edit(self, session, _id, indata=None, kwargs=None, content=None):
107 if not session["admin"]:
108 raise EngineException("needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED)
109 # Names that look like UUIDs are not allowed
110 name = (indata if indata else kwargs).get("username")
111 if is_valid_uuid(name):
112 raise EngineException("Usernames that look like UUIDs are not allowed",
113 http_code=HTTPStatus.UNPROCESSABLE_ENTITY)
114 return BaseTopic.edit(self, session, _id, indata=indata, kwargs=kwargs, content=content)
115
116 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
117 if not session["admin"]:
118 raise EngineException("needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED)
119 # Names that look like UUIDs are not allowed
120 name = indata["username"] if indata else kwargs["username"]
121 if is_valid_uuid(name):
122 raise EngineException("Usernames that look like UUIDs are not allowed",
123 http_code=HTTPStatus.UNPROCESSABLE_ENTITY)
124 return BaseTopic.new(self, rollback, session, indata=indata, kwargs=kwargs, headers=headers)
125
126
127 class ProjectTopic(BaseTopic):
128 topic = "projects"
129 topic_msg = "projects"
130 schema_new = project_new_schema
131 schema_edit = project_edit_schema
132 multiproject = False
133
134 def __init__(self, db, fs, msg, auth):
135 BaseTopic.__init__(self, db, fs, msg, auth)
136
137 @staticmethod
138 def _get_project_filter(session):
139 """
140 Generates a filter dictionary for querying database users.
141 Current policy is admin can show all, non admin, only its own user.
142 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
143 :return:
144 """
145 if session["admin"]: # allows all
146 return {}
147 else:
148 return {"_id.cont": session["project_id"]}
149
150 def check_conflict_on_new(self, session, indata):
151 if not indata.get("name"):
152 raise EngineException("missing 'name'")
153 # check name not exists
154 if self.db.get_one(self.topic, {"name": indata.get("name")}, fail_on_empty=False, fail_on_more=False):
155 raise EngineException("name '{}' exists".format(indata["name"]), HTTPStatus.CONFLICT)
156
157 @staticmethod
158 def format_on_new(content, project_id=None, make_public=False):
159 BaseTopic.format_on_new(content, None)
160 # Removed so that the UUID is kept, to allow Project Name modification
161 # content["_id"] = content["name"]
162
163 def check_conflict_on_del(self, session, _id, db_content):
164 """
165 Check if deletion can be done because of dependencies if it is not force. To override
166 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
167 :param _id: internal _id
168 :param db_content: The database content of this item _id
169 :return: None if ok or raises EngineException with the conflict
170 """
171 if _id in session["project_id"]:
172 raise EngineException("You cannot delete your own project", http_code=HTTPStatus.CONFLICT)
173 if session["force"]:
174 return
175 _filter = {"projects": _id}
176 if self.db.get_list("users", _filter):
177 raise EngineException("There is some USER that contains this project", http_code=HTTPStatus.CONFLICT)
178
179 def edit(self, session, _id, indata=None, kwargs=None, content=None):
180 if not session["admin"]:
181 raise EngineException("needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED)
182 # Names that look like UUIDs are not allowed
183 name = (indata if indata else kwargs).get("name")
184 if is_valid_uuid(name):
185 raise EngineException("Project names that look like UUIDs are not allowed",
186 http_code=HTTPStatus.UNPROCESSABLE_ENTITY)
187 return BaseTopic.edit(self, session, _id, indata=indata, kwargs=kwargs, content=content)
188
189 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
190 if not session["admin"]:
191 raise EngineException("needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED)
192 # Names that look like UUIDs are not allowed
193 name = indata["name"] if indata else kwargs["name"]
194 if is_valid_uuid(name):
195 raise EngineException("Project names that look like UUIDs are not allowed",
196 http_code=HTTPStatus.UNPROCESSABLE_ENTITY)
197 return BaseTopic.new(self, rollback, session, indata=indata, kwargs=kwargs, headers=headers)
198
199
200 class CommonVimWimSdn(BaseTopic):
201 """Common class for VIM, WIM SDN just to unify methods that are equal to all of them"""
202 config_to_encrypt = {} # what keys at config must be encrypted because contains passwords
203 password_to_encrypt = "" # key that contains a password
204
205 @staticmethod
206 def _create_operation(op_type, params=None):
207 """
208 Creates a dictionary with the information to an operation, similar to ns-lcm-op
209 :param op_type: can be create, edit, delete
210 :param params: operation input parameters
211 :return: new dictionary with
212 """
213 now = time()
214 return {
215 "lcmOperationType": op_type,
216 "operationState": "PROCESSING",
217 "startTime": now,
218 "statusEnteredTime": now,
219 "detailed-status": "",
220 "operationParams": params,
221 }
222
223 def check_conflict_on_new(self, session, indata):
224 """
225 Check that the data to be inserted is valid. It is checked that name is unique
226 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
227 :param indata: data to be inserted
228 :return: None or raises EngineException
229 """
230 self.check_unique_name(session, indata["name"], _id=None)
231
232 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
233 """
234 Check that the data to be edited/uploaded is valid. It is checked that name is unique
235 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
236 :param final_content: data once modified. This method may change it.
237 :param edit_content: incremental data that contains the modifications to apply
238 :param _id: internal _id
239 :return: None or raises EngineException
240 """
241 if not session["force"] and edit_content.get("name"):
242 self.check_unique_name(session, edit_content["name"], _id=_id)
243
244 def format_on_edit(self, final_content, edit_content):
245 """
246 Modifies final_content inserting admin information upon edition
247 :param final_content: final content to be stored at database
248 :param edit_content: user requested update content
249 :return: operation id
250 """
251 super().format_on_edit(final_content, edit_content)
252
253 # encrypt passwords
254 schema_version = final_content.get("schema_version")
255 if schema_version:
256 if edit_content.get(self.password_to_encrypt):
257 final_content[self.password_to_encrypt] = self.db.encrypt(edit_content[self.password_to_encrypt],
258 schema_version=schema_version,
259 salt=final_content["_id"])
260 config_to_encrypt_keys = self.config_to_encrypt.get(schema_version) or self.config_to_encrypt.get("default")
261 if edit_content.get("config") and config_to_encrypt_keys:
262
263 for p in config_to_encrypt_keys:
264 if edit_content["config"].get(p):
265 final_content["config"][p] = self.db.encrypt(edit_content["config"][p],
266 schema_version=schema_version,
267 salt=final_content["_id"])
268
269 # create edit operation
270 final_content["_admin"]["operations"].append(self._create_operation("edit"))
271 return "{}:{}".format(final_content["_id"], len(final_content["_admin"]["operations"]) - 1)
272
273 def format_on_new(self, content, project_id=None, make_public=False):
274 """
275 Modifies content descriptor to include _admin and insert create operation
276 :param content: descriptor to be modified
277 :param project_id: if included, it add project read/write permissions. Can be None or a list
278 :param make_public: if included it is generated as public for reading.
279 :return: op_id: operation id on asynchronous operation, None otherwise. In addition content is modified
280 """
281 super().format_on_new(content, project_id=project_id, make_public=make_public)
282 content["schema_version"] = schema_version = "1.11"
283
284 # encrypt passwords
285 if content.get(self.password_to_encrypt):
286 content[self.password_to_encrypt] = self.db.encrypt(content[self.password_to_encrypt],
287 schema_version=schema_version,
288 salt=content["_id"])
289 config_to_encrypt_keys = self.config_to_encrypt.get(schema_version) or self.config_to_encrypt.get("default")
290 if content.get("config") and config_to_encrypt_keys:
291 for p in config_to_encrypt_keys:
292 if content["config"].get(p):
293 content["config"][p] = self.db.encrypt(content["config"][p],
294 schema_version=schema_version,
295 salt=content["_id"])
296
297 content["_admin"]["operationalState"] = "PROCESSING"
298
299 # create operation
300 content["_admin"]["operations"] = [self._create_operation("create")]
301 content["_admin"]["current_operation"] = None
302
303 return "{}:0".format(content["_id"])
304
305 def delete(self, session, _id, dry_run=False, not_send_msg=None):
306 """
307 Delete item by its internal _id
308 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
309 :param _id: server internal id
310 :param dry_run: make checking but do not delete
311 :param not_send_msg: To not send message (False) or store content (list) instead
312 :return: operation id if it is ordered to delete. None otherwise
313 """
314
315 filter_q = self._get_project_filter(session)
316 filter_q["_id"] = _id
317 db_content = self.db.get_one(self.topic, filter_q)
318
319 self.check_conflict_on_del(session, _id, db_content)
320 if dry_run:
321 return None
322
323 # remove reference from project_read. If not last delete
324 if session["project_id"]:
325 for project_id in session["project_id"]:
326 if project_id in db_content["_admin"]["projects_read"]:
327 db_content["_admin"]["projects_read"].remove(project_id)
328 if project_id in db_content["_admin"]["projects_write"]:
329 db_content["_admin"]["projects_write"].remove(project_id)
330 else:
331 db_content["_admin"]["projects_read"].clear()
332 db_content["_admin"]["projects_write"].clear()
333
334 update_dict = {"_admin.projects_read": db_content["_admin"]["projects_read"],
335 "_admin.projects_write": db_content["_admin"]["projects_write"]
336 }
337
338 # check if there are projects referencing it (apart from ANY that means public)....
339 if db_content["_admin"]["projects_read"] and (len(db_content["_admin"]["projects_read"]) > 1 or
340 db_content["_admin"]["projects_read"][0] != "ANY"):
341 self.db.set_one(self.topic, filter_q, update_dict=update_dict) # remove references but not delete
342 return None
343
344 # It must be deleted
345 if session["force"]:
346 self.db.del_one(self.topic, {"_id": _id})
347 op_id = None
348 self._send_msg("deleted", {"_id": _id, "op_id": op_id}, not_send_msg=not_send_msg)
349 else:
350 update_dict["_admin.to_delete"] = True
351 self.db.set_one(self.topic, {"_id": _id},
352 update_dict=update_dict,
353 push={"_admin.operations": self._create_operation("delete")}
354 )
355 # the number of operations is the operation_id. db_content does not contains the new operation inserted,
356 # so the -1 is not needed
357 op_id = "{}:{}".format(db_content["_id"], len(db_content["_admin"]["operations"]))
358 self._send_msg("delete", {"_id": _id, "op_id": op_id}, not_send_msg=not_send_msg)
359 return op_id
360
361
362 class VimAccountTopic(CommonVimWimSdn):
363 topic = "vim_accounts"
364 topic_msg = "vim_account"
365 schema_new = vim_account_new_schema
366 schema_edit = vim_account_edit_schema
367 multiproject = True
368 password_to_encrypt = "vim_password"
369 config_to_encrypt = {"1.1": ("admin_password", "nsx_password", "vcenter_password"),
370 "default": ("admin_password", "nsx_password", "vcenter_password", "vrops_password")}
371
372 def check_conflict_on_del(self, session, _id, db_content):
373 """
374 Check if deletion can be done because of dependencies if it is not force. To override
375 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
376 :param _id: internal _id
377 :param db_content: The database content of this item _id
378 :return: None if ok or raises EngineException with the conflict
379 """
380 if session["force"]:
381 return
382 # check if used by VNF
383 if self.db.get_list("vnfrs", {"vim-account-id": _id}):
384 raise EngineException("There is at least one VNF using this VIM account", http_code=HTTPStatus.CONFLICT)
385 super().check_conflict_on_del(session, _id, db_content)
386
387
388 class WimAccountTopic(CommonVimWimSdn):
389 topic = "wim_accounts"
390 topic_msg = "wim_account"
391 schema_new = wim_account_new_schema
392 schema_edit = wim_account_edit_schema
393 multiproject = True
394 password_to_encrypt = "wim_password"
395 config_to_encrypt = {}
396
397
398 class SdnTopic(CommonVimWimSdn):
399 topic = "sdns"
400 topic_msg = "sdn"
401 schema_new = sdn_new_schema
402 schema_edit = sdn_edit_schema
403 multiproject = True
404 password_to_encrypt = "password"
405 config_to_encrypt = {}
406
407 def _obtain_url(self, input, create):
408 if input.get("ip") or input.get("port"):
409 if not input.get("ip") or not input.get("port") or input.get('url'):
410 raise ValidationError("You must provide both 'ip' and 'port' (deprecated); or just 'url' (prefered)")
411 input['url'] = "http://{}:{}/".format(input["ip"], input["port"])
412 del input["ip"]
413 del input["port"]
414 elif create and not input.get('url'):
415 raise ValidationError("You must provide 'url'")
416 return input
417
418 def _validate_input_new(self, input, force=False):
419 input = super()._validate_input_new(input, force)
420 return self._obtain_url(input, True)
421
422 def _validate_input_edit(self, input, force=False):
423 input = super()._validate_input_edit(input, force)
424 return self._obtain_url(input, False)
425
426
427 class K8sClusterTopic(CommonVimWimSdn):
428 topic = "k8sclusters"
429 topic_msg = "k8scluster"
430 schema_new = k8scluster_new_schema
431 schema_edit = k8scluster_edit_schema
432 multiproject = True
433 password_to_encrypt = None
434 config_to_encrypt = {}
435
436 def format_on_new(self, content, project_id=None, make_public=False):
437 oid = super().format_on_new(content, project_id, make_public)
438 self.db.encrypt_decrypt_fields(content["credentials"], 'encrypt', ['password', 'secret'],
439 schema_version=content["schema_version"], salt=content["_id"])
440 return oid
441
442 def format_on_edit(self, final_content, edit_content):
443 if final_content.get("schema_version") and edit_content.get("credentials"):
444 self.db.encrypt_decrypt_fields(edit_content["credentials"], 'encrypt', ['password', 'secret'],
445 schema_version=final_content["schema_version"], salt=final_content["_id"])
446 deep_update_rfc7396(final_content["credentials"], edit_content["credentials"])
447 oid = super().format_on_edit(final_content, edit_content)
448 return oid
449
450
451 class K8sRepoTopic(CommonVimWimSdn):
452 topic = "k8srepos"
453 topic_msg = "k8srepo"
454 schema_new = k8srepo_new_schema
455 schema_edit = k8srepo_edit_schema
456 multiproject = True
457 password_to_encrypt = None
458 config_to_encrypt = {}
459
460
461 class UserTopicAuth(UserTopic):
462 # topic = "users"
463 # topic_msg = "users"
464 schema_new = user_new_schema
465 schema_edit = user_edit_schema
466
467 def __init__(self, db, fs, msg, auth):
468 UserTopic.__init__(self, db, fs, msg, auth)
469 # self.auth = auth
470
471 def check_conflict_on_new(self, session, indata):
472 """
473 Check that the data to be inserted is valid
474
475 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
476 :param indata: data to be inserted
477 :return: None or raises EngineException
478 """
479 username = indata.get("username")
480 if is_valid_uuid(username):
481 raise EngineException("username '{}' cannot have a uuid format".format(username),
482 HTTPStatus.UNPROCESSABLE_ENTITY)
483
484 # Check that username is not used, regardless keystone already checks this
485 if self.auth.get_user_list(filter_q={"name": username}):
486 raise EngineException("username '{}' is already used".format(username), HTTPStatus.CONFLICT)
487
488 if "projects" in indata.keys():
489 # convert to new format project_role_mappings
490 role = self.auth.get_role_list({"name": "project_admin"})
491 if not role:
492 role = self.auth.get_role_list()
493 if not role:
494 raise AuthconnNotFoundException("Can't find default role for user '{}'".format(username))
495 rid = role[0]["_id"]
496 if not indata.get("project_role_mappings"):
497 indata["project_role_mappings"] = []
498 for project in indata["projects"]:
499 pid = self.auth.get_project(project)["_id"]
500 prm = {"project": pid, "role": rid}
501 if prm not in indata["project_role_mappings"]:
502 indata["project_role_mappings"].append(prm)
503 # raise EngineException("Format invalid: the keyword 'projects' is not allowed for keystone authentication",
504 # HTTPStatus.BAD_REQUEST)
505
506 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
507 """
508 Check that the data to be edited/uploaded is valid
509
510 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
511 :param final_content: data once modified
512 :param edit_content: incremental data that contains the modifications to apply
513 :param _id: internal _id
514 :return: None or raises EngineException
515 """
516
517 if "username" in edit_content:
518 username = edit_content.get("username")
519 if is_valid_uuid(username):
520 raise EngineException("username '{}' cannot have an uuid format".format(username),
521 HTTPStatus.UNPROCESSABLE_ENTITY)
522
523 # Check that username is not used, regardless keystone already checks this
524 if self.auth.get_user_list(filter_q={"name": username}):
525 raise EngineException("username '{}' is already used".format(username), HTTPStatus.CONFLICT)
526
527 if final_content["username"] == "admin":
528 for mapping in edit_content.get("remove_project_role_mappings", ()):
529 if mapping["project"] == "admin" and mapping.get("role") in (None, "system_admin"):
530 # TODO make this also available for project id and role id
531 raise EngineException("You cannot remove system_admin role from admin user",
532 http_code=HTTPStatus.FORBIDDEN)
533
534 def check_conflict_on_del(self, session, _id, db_content):
535 """
536 Check if deletion can be done because of dependencies if it is not force. To override
537 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
538 :param _id: internal _id
539 :param db_content: The database content of this item _id
540 :return: None if ok or raises EngineException with the conflict
541 """
542 if db_content["username"] == session["username"]:
543 raise EngineException("You cannot delete your own login user ", http_code=HTTPStatus.CONFLICT)
544 # TODO: Check that user is not logged in ? How? (Would require listing current tokens)
545
546 @staticmethod
547 def format_on_show(content):
548 """
549 Modifies the content of the role information to separate the role
550 metadata from the role definition.
551 """
552 project_role_mappings = []
553
554 if "projects" in content:
555 for project in content["projects"]:
556 for role in project["roles"]:
557 project_role_mappings.append({"project": project["_id"],
558 "project_name": project["name"],
559 "role": role["_id"],
560 "role_name": role["name"]})
561 del content["projects"]
562 content["project_role_mappings"] = project_role_mappings
563
564 return content
565
566 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
567 """
568 Creates a new entry into the authentication backend.
569
570 NOTE: Overrides BaseTopic functionality because it doesn't require access to database.
571
572 :param rollback: list to append created items at database in case a rollback may to be done
573 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
574 :param indata: data to be inserted
575 :param kwargs: used to override the indata descriptor
576 :param headers: http request headers
577 :return: _id: identity of the inserted data, operation _id (None)
578 """
579 try:
580 content = BaseTopic._remove_envelop(indata)
581
582 # Override descriptor with query string kwargs
583 BaseTopic._update_input_with_kwargs(content, kwargs)
584 content = self._validate_input_new(content, session["force"])
585 self.check_conflict_on_new(session, content)
586 # self.format_on_new(content, session["project_id"], make_public=session["public"])
587 now = time()
588 content["_admin"] = {"created": now, "modified": now}
589 prms = []
590 for prm in content.get("project_role_mappings", []):
591 proj = self.auth.get_project(prm["project"], not session["force"])
592 role = self.auth.get_role(prm["role"], not session["force"])
593 pid = proj["_id"] if proj else None
594 rid = role["_id"] if role else None
595 prl = {"project": pid, "role": rid}
596 if prl not in prms:
597 prms.append(prl)
598 content["project_role_mappings"] = prms
599 # _id = self.auth.create_user(content["username"], content["password"])["_id"]
600 _id = self.auth.create_user(content)["_id"]
601
602 rollback.append({"topic": self.topic, "_id": _id})
603 # del content["password"]
604 # self._send_msg("created", content, not_send_msg=not_send_msg)
605 return _id, None
606 except ValidationError as e:
607 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
608
609 def show(self, session, _id):
610 """
611 Get complete information on an topic
612
613 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
614 :param _id: server internal id
615 :return: dictionary, raise exception if not found.
616 """
617 # Allow _id to be a name or uuid
618 filter_q = {self.id_field(self.topic, _id): _id}
619 # users = self.auth.get_user_list(filter_q)
620 users = self.list(session, filter_q) # To allow default filtering (Bug 853)
621 if len(users) == 1:
622 return users[0]
623 elif len(users) > 1:
624 raise EngineException("Too many users found", HTTPStatus.CONFLICT)
625 else:
626 raise EngineException("User not found", HTTPStatus.NOT_FOUND)
627
628 def edit(self, session, _id, indata=None, kwargs=None, content=None):
629 """
630 Updates an user entry.
631
632 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
633 :param _id:
634 :param indata: data to be inserted
635 :param kwargs: used to override the indata descriptor
636 :param content:
637 :return: _id: identity of the inserted data.
638 """
639 indata = self._remove_envelop(indata)
640
641 # Override descriptor with query string kwargs
642 if kwargs:
643 BaseTopic._update_input_with_kwargs(indata, kwargs)
644 try:
645 indata = self._validate_input_edit(indata, force=session["force"])
646
647 if not content:
648 content = self.show(session, _id)
649 self.check_conflict_on_edit(session, content, indata, _id=_id)
650 # self.format_on_edit(content, indata)
651
652 if not ("password" in indata or "username" in indata or indata.get("remove_project_role_mappings") or
653 indata.get("add_project_role_mappings") or indata.get("project_role_mappings") or
654 indata.get("projects") or indata.get("add_projects")):
655 return _id
656 if indata.get("project_role_mappings") \
657 and (indata.get("remove_project_role_mappings") or indata.get("add_project_role_mappings")):
658 raise EngineException("Option 'project_role_mappings' is incompatible with 'add_project_role_mappings"
659 "' or 'remove_project_role_mappings'", http_code=HTTPStatus.BAD_REQUEST)
660
661 if indata.get("projects") or indata.get("add_projects"):
662 role = self.auth.get_role_list({"name": "project_admin"})
663 if not role:
664 role = self.auth.get_role_list()
665 if not role:
666 raise AuthconnNotFoundException("Can't find a default role for user '{}'"
667 .format(content["username"]))
668 rid = role[0]["_id"]
669 if "add_project_role_mappings" not in indata:
670 indata["add_project_role_mappings"] = []
671 if "remove_project_role_mappings" not in indata:
672 indata["remove_project_role_mappings"] = []
673 if isinstance(indata.get("projects"), dict):
674 # backward compatible
675 for k, v in indata["projects"].items():
676 if k.startswith("$") and v is None:
677 indata["remove_project_role_mappings"].append({"project": k[1:]})
678 elif k.startswith("$+"):
679 indata["add_project_role_mappings"].append({"project": v, "role": rid})
680 del indata["projects"]
681 for proj in indata.get("projects", []) + indata.get("add_projects", []):
682 indata["add_project_role_mappings"].append({"project": proj, "role": rid})
683
684 # user = self.show(session, _id) # Already in 'content'
685 original_mapping = content["project_role_mappings"]
686
687 mappings_to_add = []
688 mappings_to_remove = []
689
690 # remove
691 for to_remove in indata.get("remove_project_role_mappings", ()):
692 for mapping in original_mapping:
693 if to_remove["project"] in (mapping["project"], mapping["project_name"]):
694 if not to_remove.get("role") or to_remove["role"] in (mapping["role"], mapping["role_name"]):
695 mappings_to_remove.append(mapping)
696
697 # add
698 for to_add in indata.get("add_project_role_mappings", ()):
699 for mapping in original_mapping:
700 if to_add["project"] in (mapping["project"], mapping["project_name"]) and \
701 to_add["role"] in (mapping["role"], mapping["role_name"]):
702
703 if mapping in mappings_to_remove: # do not remove
704 mappings_to_remove.remove(mapping)
705 break # do not add, it is already at user
706 else:
707 pid = self.auth.get_project(to_add["project"])["_id"]
708 rid = self.auth.get_role(to_add["role"])["_id"]
709 mappings_to_add.append({"project": pid, "role": rid})
710
711 # set
712 if indata.get("project_role_mappings"):
713 for to_set in indata["project_role_mappings"]:
714 for mapping in original_mapping:
715 if to_set["project"] in (mapping["project"], mapping["project_name"]) and \
716 to_set["role"] in (mapping["role"], mapping["role_name"]):
717 if mapping in mappings_to_remove: # do not remove
718 mappings_to_remove.remove(mapping)
719 break # do not add, it is already at user
720 else:
721 pid = self.auth.get_project(to_set["project"])["_id"]
722 rid = self.auth.get_role(to_set["role"])["_id"]
723 mappings_to_add.append({"project": pid, "role": rid})
724 for mapping in original_mapping:
725 for to_set in indata["project_role_mappings"]:
726 if to_set["project"] in (mapping["project"], mapping["project_name"]) and \
727 to_set["role"] in (mapping["role"], mapping["role_name"]):
728 break
729 else:
730 # delete
731 if mapping not in mappings_to_remove: # do not remove
732 mappings_to_remove.append(mapping)
733
734 self.auth.update_user({"_id": _id, "username": indata.get("username"), "password": indata.get("password"),
735 "add_project_role_mappings": mappings_to_add,
736 "remove_project_role_mappings": mappings_to_remove
737 })
738
739 # return _id
740 except ValidationError as e:
741 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
742
743 def list(self, session, filter_q=None):
744 """
745 Get a list of the topic that matches a filter
746 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
747 :param filter_q: filter of data to be applied
748 :return: The list, it can be empty if no one match the filter.
749 """
750 user_list = self.auth.get_user_list(filter_q)
751 if not session["allow_show_user_project_role"]:
752 # Bug 853 - Default filtering
753 user_list = [usr for usr in user_list if usr["username"] == session["username"]]
754 return user_list
755
756 def delete(self, session, _id, dry_run=False, not_send_msg=None):
757 """
758 Delete item by its internal _id
759
760 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
761 :param _id: server internal id
762 :param force: indicates if deletion must be forced in case of conflict
763 :param dry_run: make checking but do not delete
764 :param not_send_msg: To not send message (False) or store content (list) instead
765 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
766 """
767 # Allow _id to be a name or uuid
768 user = self.auth.get_user(_id)
769 uid = user["_id"]
770 self.check_conflict_on_del(session, uid, user)
771 if not dry_run:
772 v = self.auth.delete_user(uid)
773 return v
774 return None
775
776
777 class ProjectTopicAuth(ProjectTopic):
778 # topic = "projects"
779 # topic_msg = "projects"
780 schema_new = project_new_schema
781 schema_edit = project_edit_schema
782
783 def __init__(self, db, fs, msg, auth):
784 ProjectTopic.__init__(self, db, fs, msg, auth)
785 # self.auth = auth
786
787 def check_conflict_on_new(self, session, indata):
788 """
789 Check that the data to be inserted is valid
790
791 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
792 :param indata: data to be inserted
793 :return: None or raises EngineException
794 """
795 project_name = indata.get("name")
796 if is_valid_uuid(project_name):
797 raise EngineException("project name '{}' cannot have an uuid format".format(project_name),
798 HTTPStatus.UNPROCESSABLE_ENTITY)
799
800 project_list = self.auth.get_project_list(filter_q={"name": project_name})
801
802 if project_list:
803 raise EngineException("project '{}' exists".format(project_name), HTTPStatus.CONFLICT)
804
805 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
806 """
807 Check that the data to be edited/uploaded is valid
808
809 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
810 :param final_content: data once modified
811 :param edit_content: incremental data that contains the modifications to apply
812 :param _id: internal _id
813 :return: None or raises EngineException
814 """
815
816 project_name = edit_content.get("name")
817 if project_name != final_content["name"]: # It is a true renaming
818 if is_valid_uuid(project_name):
819 raise EngineException("project name '{}' cannot have an uuid format".format(project_name),
820 HTTPStatus.UNPROCESSABLE_ENTITY)
821
822 if final_content["name"] == "admin":
823 raise EngineException("You cannot rename project 'admin'", http_code=HTTPStatus.CONFLICT)
824
825 # Check that project name is not used, regardless keystone already checks this
826 if project_name and self.auth.get_project_list(filter_q={"name": project_name}):
827 raise EngineException("project '{}' is already used".format(project_name), HTTPStatus.CONFLICT)
828
829 def check_conflict_on_del(self, session, _id, db_content):
830 """
831 Check if deletion can be done because of dependencies if it is not force. To override
832
833 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
834 :param _id: internal _id
835 :param db_content: The database content of this item _id
836 :return: None if ok or raises EngineException with the conflict
837 """
838
839 def check_rw_projects(topic, title, id_field):
840 for desc in self.db.get_list(topic):
841 if _id in desc["_admin"]["projects_read"] + desc["_admin"]["projects_write"]:
842 raise EngineException("Project '{}' ({}) is being used by {} '{}'"
843 .format(db_content["name"], _id, title, desc[id_field]), HTTPStatus.CONFLICT)
844
845 if _id in session["project_id"]:
846 raise EngineException("You cannot delete your own project", http_code=HTTPStatus.CONFLICT)
847
848 if db_content["name"] == "admin":
849 raise EngineException("You cannot delete project 'admin'", http_code=HTTPStatus.CONFLICT)
850
851 # If any user is using this project, raise CONFLICT exception
852 if not session["force"]:
853 for user in self.auth.get_user_list():
854 for prm in user.get("project_role_mappings"):
855 if prm["project"] == _id:
856 raise EngineException("Project '{}' ({}) is being used by user '{}'"
857 .format(db_content["name"], _id, user["username"]), HTTPStatus.CONFLICT)
858
859 # If any VNFD, NSD, NST, PDU, etc. is using this project, raise CONFLICT exception
860 if not session["force"]:
861 check_rw_projects("vnfds", "VNF Descriptor", "id")
862 check_rw_projects("nsds", "NS Descriptor", "id")
863 check_rw_projects("nsts", "NS Template", "id")
864 check_rw_projects("pdus", "PDU Descriptor", "name")
865
866 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
867 """
868 Creates a new entry into the authentication backend.
869
870 NOTE: Overrides BaseTopic functionality because it doesn't require access to database.
871
872 :param rollback: list to append created items at database in case a rollback may to be done
873 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
874 :param indata: data to be inserted
875 :param kwargs: used to override the indata descriptor
876 :param headers: http request headers
877 :return: _id: identity of the inserted data, operation _id (None)
878 """
879 try:
880 content = BaseTopic._remove_envelop(indata)
881
882 # Override descriptor with query string kwargs
883 BaseTopic._update_input_with_kwargs(content, kwargs)
884 content = self._validate_input_new(content, session["force"])
885 self.check_conflict_on_new(session, content)
886 self.format_on_new(content, project_id=session["project_id"], make_public=session["public"])
887 _id = self.auth.create_project(content)
888 rollback.append({"topic": self.topic, "_id": _id})
889 # self._send_msg("created", content, not_send_msg=not_send_msg)
890 return _id, None
891 except ValidationError as e:
892 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
893
894 def show(self, session, _id):
895 """
896 Get complete information on an topic
897
898 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
899 :param _id: server internal id
900 :return: dictionary, raise exception if not found.
901 """
902 # Allow _id to be a name or uuid
903 filter_q = {self.id_field(self.topic, _id): _id}
904 # projects = self.auth.get_project_list(filter_q=filter_q)
905 projects = self.list(session, filter_q) # To allow default filtering (Bug 853)
906 if len(projects) == 1:
907 return projects[0]
908 elif len(projects) > 1:
909 raise EngineException("Too many projects found", HTTPStatus.CONFLICT)
910 else:
911 raise EngineException("Project not found", HTTPStatus.NOT_FOUND)
912
913 def list(self, session, filter_q=None):
914 """
915 Get a list of the topic that matches a filter
916
917 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
918 :param filter_q: filter of data to be applied
919 :return: The list, it can be empty if no one match the filter.
920 """
921 project_list = self.auth.get_project_list(filter_q)
922 if not session["allow_show_user_project_role"]:
923 # Bug 853 - Default filtering
924 user = self.auth.get_user(session["username"])
925 projects = [prm["project"] for prm in user["project_role_mappings"]]
926 project_list = [proj for proj in project_list if proj["_id"] in projects]
927 return project_list
928
929 def delete(self, session, _id, dry_run=False, not_send_msg=None):
930 """
931 Delete item by its internal _id
932
933 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
934 :param _id: server internal id
935 :param dry_run: make checking but do not delete
936 :param not_send_msg: To not send message (False) or store content (list) instead
937 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
938 """
939 # Allow _id to be a name or uuid
940 proj = self.auth.get_project(_id)
941 pid = proj["_id"]
942 self.check_conflict_on_del(session, pid, proj)
943 if not dry_run:
944 v = self.auth.delete_project(pid)
945 return v
946 return None
947
948 def edit(self, session, _id, indata=None, kwargs=None, content=None):
949 """
950 Updates a project entry.
951
952 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
953 :param _id:
954 :param indata: data to be inserted
955 :param kwargs: used to override the indata descriptor
956 :param content:
957 :return: _id: identity of the inserted data.
958 """
959 indata = self._remove_envelop(indata)
960
961 # Override descriptor with query string kwargs
962 if kwargs:
963 BaseTopic._update_input_with_kwargs(indata, kwargs)
964 try:
965 indata = self._validate_input_edit(indata, force=session["force"])
966
967 if not content:
968 content = self.show(session, _id)
969 self.check_conflict_on_edit(session, content, indata, _id=_id)
970 self.format_on_edit(content, indata)
971
972 deep_update_rfc7396(content, indata)
973 self.auth.update_project(content["_id"], content)
974 except ValidationError as e:
975 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
976
977
978 class RoleTopicAuth(BaseTopic):
979 topic = "roles"
980 topic_msg = None # "roles"
981 schema_new = roles_new_schema
982 schema_edit = roles_edit_schema
983 multiproject = False
984
985 def __init__(self, db, fs, msg, auth, ops):
986 BaseTopic.__init__(self, db, fs, msg, auth)
987 # self.auth = auth
988 self.operations = ops
989 # self.topic = "roles_operations" if isinstance(auth, AuthconnKeystone) else "roles"
990
991 @staticmethod
992 def validate_role_definition(operations, role_definitions):
993 """
994 Validates the role definition against the operations defined in
995 the resources to operations files.
996
997 :param operations: operations list
998 :param role_definitions: role definition to test
999 :return: None if ok, raises ValidationError exception on error
1000 """
1001 if not role_definitions.get("permissions"):
1002 return
1003 ignore_fields = ["admin", "default"]
1004 for role_def in role_definitions["permissions"].keys():
1005 if role_def in ignore_fields:
1006 continue
1007 if role_def[-1] == ":":
1008 raise ValidationError("Operation cannot end with ':'")
1009
1010 role_def_matches = [op for op in operations if op.startswith(role_def)]
1011
1012 if len(role_def_matches) == 0:
1013 raise ValidationError("Invalid permission '{}'".format(role_def))
1014
1015 def _validate_input_new(self, input, force=False):
1016 """
1017 Validates input user content for a new entry.
1018
1019 :param input: user input content for the new topic
1020 :param force: may be used for being more tolerant
1021 :return: The same input content, or a changed version of it.
1022 """
1023 if self.schema_new:
1024 validate_input(input, self.schema_new)
1025 self.validate_role_definition(self.operations, input)
1026
1027 return input
1028
1029 def _validate_input_edit(self, input, force=False):
1030 """
1031 Validates input user content for updating an entry.
1032
1033 :param input: user input content for the new topic
1034 :param force: may be used for being more tolerant
1035 :return: The same input content, or a changed version of it.
1036 """
1037 if self.schema_edit:
1038 validate_input(input, self.schema_edit)
1039 self.validate_role_definition(self.operations, input)
1040
1041 return input
1042
1043 def check_conflict_on_new(self, session, indata):
1044 """
1045 Check that the data to be inserted is valid
1046
1047 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1048 :param indata: data to be inserted
1049 :return: None or raises EngineException
1050 """
1051 # check name is not uuid
1052 role_name = indata.get("name")
1053 if is_valid_uuid(role_name):
1054 raise EngineException("role name '{}' cannot have an uuid format".format(role_name),
1055 HTTPStatus.UNPROCESSABLE_ENTITY)
1056 # check name not exists
1057 name = indata["name"]
1058 # if self.db.get_one(self.topic, {"name": indata.get("name")}, fail_on_empty=False, fail_on_more=False):
1059 if self.auth.get_role_list({"name": name}):
1060 raise EngineException("role name '{}' exists".format(name), HTTPStatus.CONFLICT)
1061
1062 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
1063 """
1064 Check that the data to be edited/uploaded is valid
1065
1066 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1067 :param final_content: data once modified
1068 :param edit_content: incremental data that contains the modifications to apply
1069 :param _id: internal _id
1070 :return: None or raises EngineException
1071 """
1072 if "default" not in final_content["permissions"]:
1073 final_content["permissions"]["default"] = False
1074 if "admin" not in final_content["permissions"]:
1075 final_content["permissions"]["admin"] = False
1076
1077 # check name is not uuid
1078 role_name = edit_content.get("name")
1079 if is_valid_uuid(role_name):
1080 raise EngineException("role name '{}' cannot have an uuid format".format(role_name),
1081 HTTPStatus.UNPROCESSABLE_ENTITY)
1082
1083 # Check renaming of admin roles
1084 role = self.auth.get_role(_id)
1085 if role["name"] in ["system_admin", "project_admin"]:
1086 raise EngineException("You cannot rename role '{}'".format(role["name"]), http_code=HTTPStatus.FORBIDDEN)
1087
1088 # check name not exists
1089 if "name" in edit_content:
1090 role_name = edit_content["name"]
1091 # if self.db.get_one(self.topic, {"name":role_name,"_id.ne":_id}, fail_on_empty=False, fail_on_more=False):
1092 roles = self.auth.get_role_list({"name": role_name})
1093 if roles and roles[0][BaseTopic.id_field("roles", _id)] != _id:
1094 raise EngineException("role name '{}' exists".format(role_name), HTTPStatus.CONFLICT)
1095
1096 def check_conflict_on_del(self, session, _id, db_content):
1097 """
1098 Check if deletion can be done because of dependencies if it is not force. To override
1099
1100 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1101 :param _id: internal _id
1102 :param db_content: The database content of this item _id
1103 :return: None if ok or raises EngineException with the conflict
1104 """
1105 role = self.auth.get_role(_id)
1106 if role["name"] in ["system_admin", "project_admin"]:
1107 raise EngineException("You cannot delete role '{}'".format(role["name"]), http_code=HTTPStatus.FORBIDDEN)
1108
1109 # If any user is using this role, raise CONFLICT exception
1110 if not session["force"]:
1111 for user in self.auth.get_user_list():
1112 for prm in user.get("project_role_mappings"):
1113 if prm["role"] == _id:
1114 raise EngineException("Role '{}' ({}) is being used by user '{}'"
1115 .format(role["name"], _id, user["username"]), HTTPStatus.CONFLICT)
1116
1117 @staticmethod
1118 def format_on_new(content, project_id=None, make_public=False): # TO BE REMOVED ?
1119 """
1120 Modifies content descriptor to include _admin
1121
1122 :param content: descriptor to be modified
1123 :param project_id: if included, it add project read/write permissions
1124 :param make_public: if included it is generated as public for reading.
1125 :return: None, but content is modified
1126 """
1127 now = time()
1128 if "_admin" not in content:
1129 content["_admin"] = {}
1130 if not content["_admin"].get("created"):
1131 content["_admin"]["created"] = now
1132 content["_admin"]["modified"] = now
1133
1134 if "permissions" not in content:
1135 content["permissions"] = {}
1136
1137 if "default" not in content["permissions"]:
1138 content["permissions"]["default"] = False
1139 if "admin" not in content["permissions"]:
1140 content["permissions"]["admin"] = False
1141
1142 @staticmethod
1143 def format_on_edit(final_content, edit_content):
1144 """
1145 Modifies final_content descriptor to include the modified date.
1146
1147 :param final_content: final descriptor generated
1148 :param edit_content: alterations to be include
1149 :return: None, but final_content is modified
1150 """
1151 if "_admin" in final_content:
1152 final_content["_admin"]["modified"] = time()
1153
1154 if "permissions" not in final_content:
1155 final_content["permissions"] = {}
1156
1157 if "default" not in final_content["permissions"]:
1158 final_content["permissions"]["default"] = False
1159 if "admin" not in final_content["permissions"]:
1160 final_content["permissions"]["admin"] = False
1161 return None
1162
1163 def show(self, session, _id):
1164 """
1165 Get complete information on an topic
1166
1167 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1168 :param _id: server internal id
1169 :return: dictionary, raise exception if not found.
1170 """
1171 filter_q = {BaseTopic.id_field(self.topic, _id): _id}
1172 # roles = self.auth.get_role_list(filter_q)
1173 roles = self.list(session, filter_q) # To allow default filtering (Bug 853)
1174 if not roles:
1175 raise AuthconnNotFoundException("Not found any role with filter {}".format(filter_q))
1176 elif len(roles) > 1:
1177 raise AuthconnConflictException("Found more than one role with filter {}".format(filter_q))
1178 return roles[0]
1179
1180 def list(self, session, filter_q=None):
1181 """
1182 Get a list of the topic that matches a filter
1183
1184 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1185 :param filter_q: filter of data to be applied
1186 :return: The list, it can be empty if no one match the filter.
1187 """
1188 role_list = self.auth.get_role_list(filter_q)
1189 if not session["allow_show_user_project_role"]:
1190 # Bug 853 - Default filtering
1191 user = self.auth.get_user(session["username"])
1192 roles = [prm["role"] for prm in user["project_role_mappings"]]
1193 role_list = [role for role in role_list if role["_id"] in roles]
1194 return role_list
1195
1196 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
1197 """
1198 Creates a new entry into database.
1199
1200 :param rollback: list to append created items at database in case a rollback may to be done
1201 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1202 :param indata: data to be inserted
1203 :param kwargs: used to override the indata descriptor
1204 :param headers: http request headers
1205 :return: _id: identity of the inserted data, operation _id (None)
1206 """
1207 try:
1208 content = self._remove_envelop(indata)
1209
1210 # Override descriptor with query string kwargs
1211 self._update_input_with_kwargs(content, kwargs)
1212 content = self._validate_input_new(content, session["force"])
1213 self.check_conflict_on_new(session, content)
1214 self.format_on_new(content, project_id=session["project_id"], make_public=session["public"])
1215 # role_name = content["name"]
1216 rid = self.auth.create_role(content)
1217 content["_id"] = rid
1218 # _id = self.db.create(self.topic, content)
1219 rollback.append({"topic": self.topic, "_id": rid})
1220 # self._send_msg("created", content, not_send_msg=not_send_msg)
1221 return rid, None
1222 except ValidationError as e:
1223 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1224
1225 def delete(self, session, _id, dry_run=False, not_send_msg=None):
1226 """
1227 Delete item by its internal _id
1228
1229 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1230 :param _id: server internal id
1231 :param dry_run: make checking but do not delete
1232 :param not_send_msg: To not send message (False) or store content (list) instead
1233 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
1234 """
1235 filter_q = {BaseTopic.id_field(self.topic, _id): _id}
1236 roles = self.auth.get_role_list(filter_q)
1237 if not roles:
1238 raise AuthconnNotFoundException("Not found any role with filter {}".format(filter_q))
1239 elif len(roles) > 1:
1240 raise AuthconnConflictException("Found more than one role with filter {}".format(filter_q))
1241 rid = roles[0]["_id"]
1242 self.check_conflict_on_del(session, rid, None)
1243 # filter_q = {"_id": _id}
1244 # filter_q = {BaseTopic.id_field(self.topic, _id): _id} # To allow role addressing by name
1245 if not dry_run:
1246 v = self.auth.delete_role(rid)
1247 # v = self.db.del_one(self.topic, filter_q)
1248 return v
1249 return None
1250
1251 def edit(self, session, _id, indata=None, kwargs=None, content=None):
1252 """
1253 Updates a role entry.
1254
1255 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1256 :param _id:
1257 :param indata: data to be inserted
1258 :param kwargs: used to override the indata descriptor
1259 :param content:
1260 :return: _id: identity of the inserted data.
1261 """
1262 if kwargs:
1263 self._update_input_with_kwargs(indata, kwargs)
1264 try:
1265 indata = self._validate_input_edit(indata, force=session["force"])
1266 if not content:
1267 content = self.show(session, _id)
1268 deep_update_rfc7396(content, indata)
1269 self.check_conflict_on_edit(session, content, indata, _id=_id)
1270 self.format_on_edit(content, indata)
1271 self.auth.update_role(content)
1272 except ValidationError as e:
1273 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)