1 # -*- coding: utf-8 -*-
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
7 # http://www.apache.org/licenses/LICENSE-2.0
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
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
17 from uuid
import uuid4
18 from hashlib
import sha256
19 from http
import HTTPStatus
21 from osm_nbi
.validation
import (
26 vim_account_new_schema
,
27 vim_account_edit_schema
,
30 wim_account_new_schema
,
31 wim_account_edit_schema
,
34 k8scluster_new_schema
,
35 k8scluster_edit_schema
,
45 ) # To check that User/Project Names don't look like UUIDs
46 from osm_nbi
.base_topic
import BaseTopic
, EngineException
47 from osm_nbi
.authconn
import AuthconnNotFoundException
, AuthconnConflictException
48 from osm_common
.dbbase
import deep_update_rfc7396
51 __author__
= "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
54 class UserTopic(BaseTopic
):
57 schema_new
= user_new_schema
58 schema_edit
= user_edit_schema
61 def __init__(self
, db
, fs
, msg
, auth
):
62 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
65 def _get_project_filter(session
):
67 Generates a filter dictionary for querying database users.
68 Current policy is admin can show all, non admin, only its own user.
69 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
72 if session
["admin"]: # allows all
75 return {"username": session
["username"]}
77 def check_conflict_on_new(self
, session
, indata
):
78 # check username not exists
81 {"username": indata
.get("username")},
85 raise EngineException(
86 "username '{}' exists".format(indata
["username"]), HTTPStatus
.CONFLICT
89 if not session
["force"]:
90 for p
in indata
.get("projects") or []:
91 # To allow project addressing by Name as well as ID
92 if not self
.db
.get_one(
94 {BaseTopic
.id_field("projects", p
): p
},
98 raise EngineException(
99 "project '{}' does not exist".format(p
), HTTPStatus
.CONFLICT
102 def check_conflict_on_del(self
, session
, _id
, db_content
):
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
110 if _id
== session
["username"]:
111 raise EngineException(
112 "You cannot delete your own user", http_code
=HTTPStatus
.CONFLICT
116 def format_on_new(content
, project_id
=None, make_public
=False):
117 BaseTopic
.format_on_new(content
, make_public
=False)
118 # Removed so that the UUID is kept, to allow User Name modification
119 # content["_id"] = content["username"]
121 content
["_admin"]["salt"] = salt
122 if content
.get("password"):
123 content
["password"] = sha256(
124 content
["password"].encode("utf-8") + salt
.encode("utf-8")
126 if content
.get("project_role_mappings"):
128 mapping
["project"] for mapping
in content
["project_role_mappings"]
131 if content
.get("projects"):
132 content
["projects"] += projects
134 content
["projects"] = projects
137 def format_on_edit(final_content
, edit_content
):
138 BaseTopic
.format_on_edit(final_content
, edit_content
)
139 if edit_content
.get("password"):
141 final_content
["_admin"]["salt"] = salt
142 final_content
["password"] = sha256(
143 edit_content
["password"].encode("utf-8") + salt
.encode("utf-8")
147 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
148 if not session
["admin"]:
149 raise EngineException(
150 "needed admin privileges", http_code
=HTTPStatus
.UNAUTHORIZED
152 # Names that look like UUIDs are not allowed
153 name
= (indata
if indata
else kwargs
).get("username")
154 if is_valid_uuid(name
):
155 raise EngineException(
156 "Usernames that look like UUIDs are not allowed",
157 http_code
=HTTPStatus
.UNPROCESSABLE_ENTITY
,
159 return BaseTopic
.edit(
160 self
, session
, _id
, indata
=indata
, kwargs
=kwargs
, content
=content
163 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
164 if not session
["admin"]:
165 raise EngineException(
166 "needed admin privileges", http_code
=HTTPStatus
.UNAUTHORIZED
168 # Names that look like UUIDs are not allowed
169 name
= indata
["username"] if indata
else kwargs
["username"]
170 if is_valid_uuid(name
):
171 raise EngineException(
172 "Usernames that look like UUIDs are not allowed",
173 http_code
=HTTPStatus
.UNPROCESSABLE_ENTITY
,
175 return BaseTopic
.new(
176 self
, rollback
, session
, indata
=indata
, kwargs
=kwargs
, headers
=headers
180 class ProjectTopic(BaseTopic
):
182 topic_msg
= "projects"
183 schema_new
= project_new_schema
184 schema_edit
= project_edit_schema
187 def __init__(self
, db
, fs
, msg
, auth
):
188 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
191 def _get_project_filter(session
):
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"
198 if session
["admin"]: # allows all
201 return {"_id.cont": session
["project_id"]}
203 def check_conflict_on_new(self
, session
, indata
):
204 if not indata
.get("name"):
205 raise EngineException("missing 'name'")
206 # check name not exists
209 {"name": indata
.get("name")},
213 raise EngineException(
214 "name '{}' exists".format(indata
["name"]), HTTPStatus
.CONFLICT
218 def format_on_new(content
, project_id
=None, make_public
=False):
219 BaseTopic
.format_on_new(content
, None)
220 # Removed so that the UUID is kept, to allow Project Name modification
221 # content["_id"] = content["name"]
223 def check_conflict_on_del(self
, session
, _id
, db_content
):
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
231 if _id
in session
["project_id"]:
232 raise EngineException(
233 "You cannot delete your own project", http_code
=HTTPStatus
.CONFLICT
237 _filter
= {"projects": _id
}
238 if self
.db
.get_list("users", _filter
):
239 raise EngineException(
240 "There is some USER that contains this project",
241 http_code
=HTTPStatus
.CONFLICT
,
244 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
245 if not session
["admin"]:
246 raise EngineException(
247 "needed admin privileges", http_code
=HTTPStatus
.UNAUTHORIZED
249 # Names that look like UUIDs are not allowed
250 name
= (indata
if indata
else kwargs
).get("name")
251 if is_valid_uuid(name
):
252 raise EngineException(
253 "Project names that look like UUIDs are not allowed",
254 http_code
=HTTPStatus
.UNPROCESSABLE_ENTITY
,
256 return BaseTopic
.edit(
257 self
, session
, _id
, indata
=indata
, kwargs
=kwargs
, content
=content
260 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
261 if not session
["admin"]:
262 raise EngineException(
263 "needed admin privileges", http_code
=HTTPStatus
.UNAUTHORIZED
265 # Names that look like UUIDs are not allowed
266 name
= indata
["name"] if indata
else kwargs
["name"]
267 if is_valid_uuid(name
):
268 raise EngineException(
269 "Project names that look like UUIDs are not allowed",
270 http_code
=HTTPStatus
.UNPROCESSABLE_ENTITY
,
272 return BaseTopic
.new(
273 self
, rollback
, session
, indata
=indata
, kwargs
=kwargs
, headers
=headers
277 class CommonVimWimSdn(BaseTopic
):
278 """Common class for VIM, WIM SDN just to unify methods that are equal to all of them"""
280 config_to_encrypt
= (
282 ) # what keys at config must be encrypted because contains passwords
283 password_to_encrypt
= "" # key that contains a password
286 def _create_operation(op_type
, params
=None):
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
295 "lcmOperationType": op_type
,
296 "operationState": "PROCESSING",
298 "statusEnteredTime": now
,
299 "detailed-status": "",
300 "operationParams": params
,
303 def check_conflict_on_new(self
, session
, indata
):
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
310 self
.check_unique_name(session
, indata
["name"], _id
=None)
312 def check_conflict_on_edit(self
, session
, final_content
, edit_content
, _id
):
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
321 if not session
["force"] and edit_content
.get("name"):
322 self
.check_unique_name(session
, edit_content
["name"], _id
=_id
)
326 def format_on_edit(self
, final_content
, edit_content
):
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
333 super().format_on_edit(final_content
, edit_content
)
336 schema_version
= final_content
.get("schema_version")
338 if edit_content
.get(self
.password_to_encrypt
):
339 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"],
344 config_to_encrypt_keys
= self
.config_to_encrypt
.get(
346 ) or self
.config_to_encrypt
.get("default")
347 if edit_content
.get("config") and config_to_encrypt_keys
:
348 for p
in config_to_encrypt_keys
:
349 if edit_content
["config"].get(p
):
350 final_content
["config"][p
] = self
.db
.encrypt(
351 edit_content
["config"][p
],
352 schema_version
=schema_version
,
353 salt
=final_content
["_id"],
356 # create edit operation
357 final_content
["_admin"]["operations"].append(self
._create
_operation
("edit"))
358 return "{}:{}".format(
359 final_content
["_id"], len(final_content
["_admin"]["operations"]) - 1
362 def format_on_new(self
, content
, project_id
=None, make_public
=False):
364 Modifies content descriptor to include _admin and insert create operation
365 :param content: descriptor to be modified
366 :param project_id: if included, it add project read/write permissions. Can be None or a list
367 :param make_public: if included it is generated as public for reading.
368 :return: op_id: operation id on asynchronous operation, None otherwise. In addition content is modified
370 super().format_on_new(content
, project_id
=project_id
, make_public
=make_public
)
371 content
["schema_version"] = schema_version
= "1.11"
374 if content
.get(self
.password_to_encrypt
):
375 content
[self
.password_to_encrypt
] = self
.db
.encrypt(
376 content
[self
.password_to_encrypt
],
377 schema_version
=schema_version
,
380 config_to_encrypt_keys
= self
.config_to_encrypt
.get(
382 ) or self
.config_to_encrypt
.get("default")
383 if content
.get("config") and config_to_encrypt_keys
:
384 for p
in config_to_encrypt_keys
:
385 if content
["config"].get(p
):
386 content
["config"][p
] = self
.db
.encrypt(
387 content
["config"][p
],
388 schema_version
=schema_version
,
392 content
["_admin"]["operationalState"] = "PROCESSING"
395 content
["_admin"]["operations"] = [self
._create
_operation
("create")]
396 content
["_admin"]["current_operation"] = None
397 # create Resource in Openstack based VIM
398 if content
.get("vim_type"):
399 if content
["vim_type"] == "openstack":
401 "ram": {"total": None, "used": None},
402 "vcpus": {"total": None, "used": None},
403 "instances": {"total": None, "used": None},
406 "volumes": {"total": None, "used": None},
407 "snapshots": {"total": None, "used": None},
408 "storage": {"total": None, "used": None},
411 "networks": {"total": None, "used": None},
412 "subnets": {"total": None, "used": None},
413 "floating_ips": {"total": None, "used": None},
415 content
["resources"] = {
421 return "{}:0".format(content
["_id"])
423 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
425 Delete item by its internal _id
426 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
427 :param _id: server internal id
428 :param dry_run: make checking but do not delete
429 :param not_send_msg: To not send message (False) or store content (list) instead
430 :return: operation id if it is ordered to delete. None otherwise
433 filter_q
= self
._get
_project
_filter
(session
)
434 filter_q
["_id"] = _id
435 db_content
= self
.db
.get_one(self
.topic
, filter_q
)
437 self
.check_conflict_on_del(session
, _id
, db_content
)
441 # remove reference from project_read if there are more projects referencing it. If it last one,
442 # do not remove reference, but order via kafka to delete it
443 if session
["project_id"] and session
["project_id"]:
444 other_projects_referencing
= next(
447 for p
in db_content
["_admin"]["projects_read"]
448 if p
not in session
["project_id"] and p
!= "ANY"
453 # check if there are projects referencing it (apart from ANY, that means, public)....
454 if other_projects_referencing
:
455 # remove references but not delete
457 "_admin.projects_read": session
["project_id"],
458 "_admin.projects_write": session
["project_id"],
461 self
.topic
, filter_q
, update_dict
=None, pull_list
=update_dict_pull
468 for p
in db_content
["_admin"]["projects_write"]
469 if p
== "ANY" or p
in session
["project_id"]
474 raise EngineException(
475 "You have not write permission to delete it",
476 http_code
=HTTPStatus
.UNAUTHORIZED
,
481 self
.db
.del_one(self
.topic
, {"_id": _id
})
484 "deleted", {"_id": _id
, "op_id": op_id
}, not_send_msg
=not_send_msg
487 update_dict
= {"_admin.to_delete": True}
491 update_dict
=update_dict
,
492 push
={"_admin.operations": self
._create
_operation
("delete")},
494 # the number of operations is the operation_id. db_content does not contains the new operation inserted,
495 # so the -1 is not needed
496 op_id
= "{}:{}".format(
497 db_content
["_id"], len(db_content
["_admin"]["operations"])
500 "delete", {"_id": _id
, "op_id": op_id
}, not_send_msg
=not_send_msg
505 class VimAccountTopic(CommonVimWimSdn
):
506 topic
= "vim_accounts"
507 topic_msg
= "vim_account"
508 schema_new
= vim_account_new_schema
509 schema_edit
= vim_account_edit_schema
511 password_to_encrypt
= "vim_password"
512 config_to_encrypt
= {
513 "1.1": ("admin_password", "nsx_password", "vcenter_password"),
522 def check_conflict_on_del(self
, session
, _id
, db_content
):
524 Check if deletion can be done because of dependencies if it is not force. To override
525 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
526 :param _id: internal _id
527 :param db_content: The database content of this item _id
528 :return: None if ok or raises EngineException with the conflict
532 # check if used by VNF
533 if self
.db
.get_list("vnfrs", {"vim-account-id": _id
}):
534 raise EngineException(
535 "There is at least one VNF using this VIM account",
536 http_code
=HTTPStatus
.CONFLICT
,
538 super().check_conflict_on_del(session
, _id
, db_content
)
541 class WimAccountTopic(CommonVimWimSdn
):
542 topic
= "wim_accounts"
543 topic_msg
= "wim_account"
544 schema_new
= wim_account_new_schema
545 schema_edit
= wim_account_edit_schema
547 password_to_encrypt
= "password"
548 config_to_encrypt
= {}
551 class SdnTopic(CommonVimWimSdn
):
554 quota_name
= "sdn_controllers"
555 schema_new
= sdn_new_schema
556 schema_edit
= sdn_edit_schema
558 password_to_encrypt
= "password"
559 config_to_encrypt
= {}
561 def _obtain_url(self
, input, create
):
562 if input.get("ip") or input.get("port"):
563 if not input.get("ip") or not input.get("port") or input.get("url"):
564 raise ValidationError(
565 "You must provide both 'ip' and 'port' (deprecated); or just 'url' (prefered)"
567 input["url"] = "http://{}:{}/".format(input["ip"], input["port"])
570 elif create
and not input.get("url"):
571 raise ValidationError("You must provide 'url'")
574 def _validate_input_new(self
, input, force
=False):
575 input = super()._validate
_input
_new
(input, force
)
576 return self
._obtain
_url
(input, True)
578 def _validate_input_edit(self
, input, content
, force
=False):
579 input = super()._validate
_input
_edit
(input, content
, force
)
580 return self
._obtain
_url
(input, False)
583 class K8sClusterTopic(CommonVimWimSdn
):
584 topic
= "k8sclusters"
585 topic_msg
= "k8scluster"
586 schema_new
= k8scluster_new_schema
587 schema_edit
= k8scluster_edit_schema
589 password_to_encrypt
= None
590 config_to_encrypt
= {}
592 def format_on_new(self
, content
, project_id
=None, make_public
=False):
593 oid
= super().format_on_new(content
, project_id
, make_public
)
594 self
.db
.encrypt_decrypt_fields(
595 content
["credentials"],
597 ["password", "secret"],
598 schema_version
=content
["schema_version"],
601 # Add Helm/Juju Repo lists
602 repos
= {"helm-chart": [], "juju-bundle": []}
603 for proj
in content
["_admin"]["projects_read"]:
605 for repo
in self
.db
.get_list(
606 "k8srepos", {"_admin.projects_read": proj
}
608 if repo
["_id"] not in repos
[repo
["type"]]:
609 repos
[repo
["type"]].append(repo
["_id"])
611 content
["_admin"][k
.replace("-", "_") + "_repos"] = repos
[k
]
614 def format_on_edit(self
, final_content
, edit_content
):
615 if final_content
.get("schema_version") and edit_content
.get("credentials"):
616 self
.db
.encrypt_decrypt_fields(
617 edit_content
["credentials"],
619 ["password", "secret"],
620 schema_version
=final_content
["schema_version"],
621 salt
=final_content
["_id"],
624 final_content
["credentials"], edit_content
["credentials"]
626 oid
= super().format_on_edit(final_content
, edit_content
)
629 def check_conflict_on_edit(self
, session
, final_content
, edit_content
, _id
):
630 final_content
= super(CommonVimWimSdn
, self
).check_conflict_on_edit(
631 session
, final_content
, edit_content
, _id
633 final_content
= super().check_conflict_on_edit(
634 session
, final_content
, edit_content
, _id
636 # Update Helm/Juju Repo lists
637 repos
= {"helm-chart": [], "juju-bundle": []}
638 for proj
in session
.get("set_project", []):
640 for repo
in self
.db
.get_list(
641 "k8srepos", {"_admin.projects_read": proj
}
643 if repo
["_id"] not in repos
[repo
["type"]]:
644 repos
[repo
["type"]].append(repo
["_id"])
646 rlist
= k
.replace("-", "_") + "_repos"
647 if rlist
not in final_content
["_admin"]:
648 final_content
["_admin"][rlist
] = []
649 final_content
["_admin"][rlist
] += repos
[k
]
652 def check_conflict_on_del(self
, session
, _id
, db_content
):
654 Check if deletion can be done because of dependencies if it is not force. To override
655 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
656 :param _id: internal _id
657 :param db_content: The database content of this item _id
658 :return: None if ok or raises EngineException with the conflict
662 # check if used by VNF
663 filter_q
= {"kdur.k8s-cluster.id": _id
}
664 if session
["project_id"]:
665 filter_q
["_admin.projects_read.cont"] = session
["project_id"]
666 if self
.db
.get_list("vnfrs", filter_q
):
667 raise EngineException(
668 "There is at least one VNF using this k8scluster",
669 http_code
=HTTPStatus
.CONFLICT
,
671 super().check_conflict_on_del(session
, _id
, db_content
)
674 class VcaTopic(CommonVimWimSdn
):
677 schema_new
= vca_new_schema
678 schema_edit
= vca_edit_schema
680 password_to_encrypt
= None
682 def format_on_new(self
, content
, project_id
=None, make_public
=False):
683 oid
= super().format_on_new(content
, project_id
, make_public
)
684 content
["schema_version"] = schema_version
= "1.11"
685 for key
in ["secret", "cacert"]:
686 content
[key
] = self
.db
.encrypt(
687 content
[key
], schema_version
=schema_version
, salt
=content
["_id"]
691 def format_on_edit(self
, final_content
, edit_content
):
692 oid
= super().format_on_edit(final_content
, edit_content
)
693 schema_version
= final_content
.get("schema_version")
694 for key
in ["secret", "cacert"]:
695 if key
in edit_content
:
696 final_content
[key
] = self
.db
.encrypt(
698 schema_version
=schema_version
,
699 salt
=final_content
["_id"],
703 def check_conflict_on_del(self
, session
, _id
, db_content
):
705 Check if deletion can be done because of dependencies if it is not force. To override
706 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
707 :param _id: internal _id
708 :param db_content: The database content of this item _id
709 :return: None if ok or raises EngineException with the conflict
713 # check if used by VNF
714 filter_q
= {"vca": _id
}
715 if session
["project_id"]:
716 filter_q
["_admin.projects_read.cont"] = session
["project_id"]
717 if self
.db
.get_list("vim_accounts", filter_q
):
718 raise EngineException(
719 "There is at least one VIM account using this vca",
720 http_code
=HTTPStatus
.CONFLICT
,
722 super().check_conflict_on_del(session
, _id
, db_content
)
725 class K8sRepoTopic(CommonVimWimSdn
):
727 topic_msg
= "k8srepo"
728 schema_new
= k8srepo_new_schema
729 schema_edit
= k8srepo_edit_schema
731 password_to_encrypt
= None
732 config_to_encrypt
= {}
734 def format_on_new(self
, content
, project_id
=None, make_public
=False):
735 oid
= super().format_on_new(content
, project_id
, make_public
)
736 # Update Helm/Juju Repo lists
737 repo_list
= content
["type"].replace("-", "_") + "_repos"
738 for proj
in content
["_admin"]["projects_read"]:
743 "_admin.projects_read": proj
,
744 "_admin." + repo_list
+ ".ne": content
["_id"],
747 push
={"_admin." + repo_list
: content
["_id"]},
751 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
752 type = self
.db
.get_one("k8srepos", {"_id": _id
})["type"]
753 oid
= super().delete(session
, _id
, dry_run
, not_send_msg
)
755 # Remove from Helm/Juju Repo lists
756 repo_list
= type.replace("-", "_") + "_repos"
759 {"_admin." + repo_list
: _id
},
761 pull
={"_admin." + repo_list
: _id
},
766 class OsmRepoTopic(BaseTopic
):
768 topic_msg
= "osmrepos"
769 schema_new
= osmrepo_new_schema
770 schema_edit
= osmrepo_edit_schema
772 # TODO: Implement user/password
775 class UserTopicAuth(UserTopic
):
778 schema_new
= user_new_schema
779 schema_edit
= user_edit_schema
781 def __init__(self
, db
, fs
, msg
, auth
):
782 UserTopic
.__init
__(self
, db
, fs
, msg
, auth
)
785 def check_conflict_on_new(self
, session
, indata
):
787 Check that the data to be inserted is valid
789 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
790 :param indata: data to be inserted
791 :return: None or raises EngineException
793 username
= indata
.get("username")
794 if is_valid_uuid(username
):
795 raise EngineException(
796 "username '{}' cannot have a uuid format".format(username
),
797 HTTPStatus
.UNPROCESSABLE_ENTITY
,
800 # Check that username is not used, regardless keystone already checks this
801 if self
.auth
.get_user_list(filter_q
={"name": username
}):
802 raise EngineException(
803 "username '{}' is already used".format(username
), HTTPStatus
.CONFLICT
806 if "projects" in indata
.keys():
807 # convert to new format project_role_mappings
808 role
= self
.auth
.get_role_list({"name": "project_admin"})
810 role
= self
.auth
.get_role_list()
812 raise AuthconnNotFoundException(
813 "Can't find default role for user '{}'".format(username
)
816 if not indata
.get("project_role_mappings"):
817 indata
["project_role_mappings"] = []
818 for project
in indata
["projects"]:
819 pid
= self
.auth
.get_project(project
)["_id"]
820 prm
= {"project": pid
, "role": rid
}
821 if prm
not in indata
["project_role_mappings"]:
822 indata
["project_role_mappings"].append(prm
)
823 # raise EngineException("Format invalid: the keyword 'projects' is not allowed for keystone authentication",
824 # HTTPStatus.BAD_REQUEST)
826 def check_conflict_on_edit(self
, session
, final_content
, edit_content
, _id
):
828 Check that the data to be edited/uploaded is valid
830 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
831 :param final_content: data once modified
832 :param edit_content: incremental data that contains the modifications to apply
833 :param _id: internal _id
834 :return: None or raises EngineException
837 if "username" in edit_content
:
838 username
= edit_content
.get("username")
839 if is_valid_uuid(username
):
840 raise EngineException(
841 "username '{}' cannot have an uuid format".format(username
),
842 HTTPStatus
.UNPROCESSABLE_ENTITY
,
845 # Check that username is not used, regardless keystone already checks this
846 if self
.auth
.get_user_list(filter_q
={"name": username
}):
847 raise EngineException(
848 "username '{}' is already used".format(username
),
852 if final_content
["username"] == "admin":
853 for mapping
in edit_content
.get("remove_project_role_mappings", ()):
854 if mapping
["project"] == "admin" and mapping
.get("role") in (
858 # TODO make this also available for project id and role id
859 raise EngineException(
860 "You cannot remove system_admin role from admin user",
861 http_code
=HTTPStatus
.FORBIDDEN
,
866 def check_conflict_on_del(self
, session
, _id
, db_content
):
868 Check if deletion can be done because of dependencies if it is not force. To override
869 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
870 :param _id: internal _id
871 :param db_content: The database content of this item _id
872 :return: None if ok or raises EngineException with the conflict
874 if db_content
["username"] == session
["username"]:
875 raise EngineException(
876 "You cannot delete your own login user ", http_code
=HTTPStatus
.CONFLICT
878 # TODO: Check that user is not logged in ? How? (Would require listing current tokens)
881 def format_on_show(content
):
883 Modifies the content of the role information to separate the role
884 metadata from the role definition.
886 project_role_mappings
= []
888 if "projects" in content
:
889 for project
in content
["projects"]:
890 for role
in project
["roles"]:
891 project_role_mappings
.append(
893 "project": project
["_id"],
894 "project_name": project
["name"],
896 "role_name": role
["name"],
899 del content
["projects"]
900 content
["project_role_mappings"] = project_role_mappings
904 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
906 Creates a new entry into the authentication backend.
908 NOTE: Overrides BaseTopic functionality because it doesn't require access to database.
910 :param rollback: list to append created items at database in case a rollback may to be done
911 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
912 :param indata: data to be inserted
913 :param kwargs: used to override the indata descriptor
914 :param headers: http request headers
915 :return: _id: identity of the inserted data, operation _id (None)
918 content
= BaseTopic
._remove
_envelop
(indata
)
920 # Override descriptor with query string kwargs
921 BaseTopic
._update
_input
_with
_kwargs
(content
, kwargs
)
922 content
= self
._validate
_input
_new
(content
, session
["force"])
923 self
.check_conflict_on_new(session
, content
)
924 # self.format_on_new(content, session["project_id"], make_public=session["public"])
926 content
["_admin"] = {"created": now
, "modified": now
}
928 for prm
in content
.get("project_role_mappings", []):
929 proj
= self
.auth
.get_project(prm
["project"], not session
["force"])
930 role
= self
.auth
.get_role(prm
["role"], not session
["force"])
931 pid
= proj
["_id"] if proj
else None
932 rid
= role
["_id"] if role
else None
933 prl
= {"project": pid
, "role": rid
}
936 content
["project_role_mappings"] = prms
937 # _id = self.auth.create_user(content["username"], content["password"])["_id"]
938 _id
= self
.auth
.create_user(content
)["_id"]
940 rollback
.append({"topic": self
.topic
, "_id": _id
})
941 # del content["password"]
942 self
._send
_msg
("created", content
, not_send_msg
=None)
944 except ValidationError
as e
:
945 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
947 def show(self
, session
, _id
, filter_q
=None, api_req
=False):
949 Get complete information on an topic
951 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
952 :param _id: server internal id or username
953 :param filter_q: dict: query parameter
954 :param api_req: True if this call is serving an external API request. False if serving internal request.
955 :return: dictionary, raise exception if not found.
957 # Allow _id to be a name or uuid
958 filter_q
= {"username": _id
}
959 # users = self.auth.get_user_list(filter_q)
960 users
= self
.list(session
, filter_q
) # To allow default filtering (Bug 853)
964 raise EngineException(
965 "Too many users found for '{}'".format(_id
), HTTPStatus
.CONFLICT
968 raise EngineException(
969 "User '{}' not found".format(_id
), HTTPStatus
.NOT_FOUND
972 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
974 Updates an user entry.
976 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
978 :param indata: data to be inserted
979 :param kwargs: used to override the indata descriptor
981 :return: _id: identity of the inserted data.
983 indata
= self
._remove
_envelop
(indata
)
985 # Override descriptor with query string kwargs
987 BaseTopic
._update
_input
_with
_kwargs
(indata
, kwargs
)
990 content
= self
.show(session
, _id
)
991 indata
= self
._validate
_input
_edit
(indata
, content
, force
=session
["force"])
992 content
= self
.check_conflict_on_edit(session
, content
, indata
, _id
=_id
)
993 # self.format_on_edit(content, indata)
997 or "username" in indata
998 or indata
.get("remove_project_role_mappings")
999 or indata
.get("add_project_role_mappings")
1000 or indata
.get("project_role_mappings")
1001 or indata
.get("projects")
1002 or indata
.get("add_projects")
1005 if indata
.get("project_role_mappings") and (
1006 indata
.get("remove_project_role_mappings")
1007 or indata
.get("add_project_role_mappings")
1009 raise EngineException(
1010 "Option 'project_role_mappings' is incompatible with 'add_project_role_mappings"
1011 "' or 'remove_project_role_mappings'",
1012 http_code
=HTTPStatus
.BAD_REQUEST
,
1015 if indata
.get("projects") or indata
.get("add_projects"):
1016 role
= self
.auth
.get_role_list({"name": "project_admin"})
1018 role
= self
.auth
.get_role_list()
1020 raise AuthconnNotFoundException(
1021 "Can't find a default role for user '{}'".format(
1025 rid
= role
[0]["_id"]
1026 if "add_project_role_mappings" not in indata
:
1027 indata
["add_project_role_mappings"] = []
1028 if "remove_project_role_mappings" not in indata
:
1029 indata
["remove_project_role_mappings"] = []
1030 if isinstance(indata
.get("projects"), dict):
1031 # backward compatible
1032 for k
, v
in indata
["projects"].items():
1033 if k
.startswith("$") and v
is None:
1034 indata
["remove_project_role_mappings"].append(
1037 elif k
.startswith("$+"):
1038 indata
["add_project_role_mappings"].append(
1039 {"project": v
, "role": rid
}
1041 del indata
["projects"]
1042 for proj
in indata
.get("projects", []) + indata
.get("add_projects", []):
1043 indata
["add_project_role_mappings"].append(
1044 {"project": proj
, "role": rid
}
1047 # user = self.show(session, _id) # Already in 'content'
1048 original_mapping
= content
["project_role_mappings"]
1050 mappings_to_add
= []
1051 mappings_to_remove
= []
1054 for to_remove
in indata
.get("remove_project_role_mappings", ()):
1055 for mapping
in original_mapping
:
1056 if to_remove
["project"] in (
1058 mapping
["project_name"],
1060 if not to_remove
.get("role") or to_remove
["role"] in (
1062 mapping
["role_name"],
1064 mappings_to_remove
.append(mapping
)
1067 for to_add
in indata
.get("add_project_role_mappings", ()):
1068 for mapping
in original_mapping
:
1069 if to_add
["project"] in (
1071 mapping
["project_name"],
1072 ) and to_add
["role"] in (
1074 mapping
["role_name"],
1076 if mapping
in mappings_to_remove
: # do not remove
1077 mappings_to_remove
.remove(mapping
)
1078 break # do not add, it is already at user
1080 pid
= self
.auth
.get_project(to_add
["project"])["_id"]
1081 rid
= self
.auth
.get_role(to_add
["role"])["_id"]
1082 mappings_to_add
.append({"project": pid
, "role": rid
})
1085 if indata
.get("project_role_mappings"):
1086 for to_set
in indata
["project_role_mappings"]:
1087 for mapping
in original_mapping
:
1088 if to_set
["project"] in (
1090 mapping
["project_name"],
1091 ) and to_set
["role"] in (
1093 mapping
["role_name"],
1095 if mapping
in mappings_to_remove
: # do not remove
1096 mappings_to_remove
.remove(mapping
)
1097 break # do not add, it is already at user
1099 pid
= self
.auth
.get_project(to_set
["project"])["_id"]
1100 rid
= self
.auth
.get_role(to_set
["role"])["_id"]
1101 mappings_to_add
.append({"project": pid
, "role": rid
})
1102 for mapping
in original_mapping
:
1103 for to_set
in indata
["project_role_mappings"]:
1104 if to_set
["project"] in (
1106 mapping
["project_name"],
1107 ) and to_set
["role"] in (
1109 mapping
["role_name"],
1114 if mapping
not in mappings_to_remove
: # do not remove
1115 mappings_to_remove
.append(mapping
)
1117 self
.auth
.update_user(
1120 "username": indata
.get("username"),
1121 "password": indata
.get("password"),
1122 "old_password": indata
.get("old_password"),
1123 "add_project_role_mappings": mappings_to_add
,
1124 "remove_project_role_mappings": mappings_to_remove
,
1127 data_to_send
= {"_id": _id
, "changes": indata
}
1128 self
._send
_msg
("edited", data_to_send
, not_send_msg
=None)
1131 except ValidationError
as e
:
1132 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
1134 def list(self
, session
, filter_q
=None, api_req
=False):
1136 Get a list of the topic that matches a filter
1137 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1138 :param filter_q: filter of data to be applied
1139 :param api_req: True if this call is serving an external API request. False if serving internal request.
1140 :return: The list, it can be empty if no one match the filter.
1142 user_list
= self
.auth
.get_user_list(filter_q
)
1143 if not session
["allow_show_user_project_role"]:
1144 # Bug 853 - Default filtering
1146 usr
for usr
in user_list
if usr
["username"] == session
["username"]
1150 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
1152 Delete item by its internal _id
1154 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1155 :param _id: server internal id
1156 :param force: indicates if deletion must be forced in case of conflict
1157 :param dry_run: make checking but do not delete
1158 :param not_send_msg: To not send message (False) or store content (list) instead
1159 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
1161 # Allow _id to be a name or uuid
1162 user
= self
.auth
.get_user(_id
)
1164 self
.check_conflict_on_del(session
, uid
, user
)
1166 v
= self
.auth
.delete_user(uid
)
1167 self
._send
_msg
("deleted", user
, not_send_msg
=not_send_msg
)
1172 class ProjectTopicAuth(ProjectTopic
):
1173 # topic = "projects"
1174 topic_msg
= "project"
1175 schema_new
= project_new_schema
1176 schema_edit
= project_edit_schema
1178 def __init__(self
, db
, fs
, msg
, auth
):
1179 ProjectTopic
.__init
__(self
, db
, fs
, msg
, auth
)
1182 def check_conflict_on_new(self
, session
, indata
):
1184 Check that the data to be inserted is valid
1186 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1187 :param indata: data to be inserted
1188 :return: None or raises EngineException
1190 project_name
= indata
.get("name")
1191 if is_valid_uuid(project_name
):
1192 raise EngineException(
1193 "project name '{}' cannot have an uuid format".format(project_name
),
1194 HTTPStatus
.UNPROCESSABLE_ENTITY
,
1197 project_list
= self
.auth
.get_project_list(filter_q
={"name": project_name
})
1200 raise EngineException(
1201 "project '{}' exists".format(project_name
), HTTPStatus
.CONFLICT
1204 def check_conflict_on_edit(self
, session
, final_content
, edit_content
, _id
):
1206 Check that the data to be edited/uploaded is valid
1208 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1209 :param final_content: data once modified
1210 :param edit_content: incremental data that contains the modifications to apply
1211 :param _id: internal _id
1212 :return: None or raises EngineException
1215 project_name
= edit_content
.get("name")
1216 if project_name
!= final_content
["name"]: # It is a true renaming
1217 if is_valid_uuid(project_name
):
1218 raise EngineException(
1219 "project name '{}' cannot have an uuid format".format(project_name
),
1220 HTTPStatus
.UNPROCESSABLE_ENTITY
,
1223 if final_content
["name"] == "admin":
1224 raise EngineException(
1225 "You cannot rename project 'admin'", http_code
=HTTPStatus
.CONFLICT
1228 # Check that project name is not used, regardless keystone already checks this
1229 if project_name
and self
.auth
.get_project_list(
1230 filter_q
={"name": project_name
}
1232 raise EngineException(
1233 "project '{}' is already used".format(project_name
),
1234 HTTPStatus
.CONFLICT
,
1236 return final_content
1238 def check_conflict_on_del(self
, session
, _id
, db_content
):
1240 Check if deletion can be done because of dependencies if it is not force. To override
1242 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1243 :param _id: internal _id
1244 :param db_content: The database content of this item _id
1245 :return: None if ok or raises EngineException with the conflict
1248 def check_rw_projects(topic
, title
, id_field
):
1249 for desc
in self
.db
.get_list(topic
):
1252 in desc
["_admin"]["projects_read"]
1253 + desc
["_admin"]["projects_write"]
1255 raise EngineException(
1256 "Project '{}' ({}) is being used by {} '{}'".format(
1257 db_content
["name"], _id
, title
, desc
[id_field
]
1259 HTTPStatus
.CONFLICT
,
1262 if _id
in session
["project_id"]:
1263 raise EngineException(
1264 "You cannot delete your own project", http_code
=HTTPStatus
.CONFLICT
1267 if db_content
["name"] == "admin":
1268 raise EngineException(
1269 "You cannot delete project 'admin'", http_code
=HTTPStatus
.CONFLICT
1272 # If any user is using this project, raise CONFLICT exception
1273 if not session
["force"]:
1274 for user
in self
.auth
.get_user_list():
1275 for prm
in user
.get("project_role_mappings"):
1276 if prm
["project"] == _id
:
1277 raise EngineException(
1278 "Project '{}' ({}) is being used by user '{}'".format(
1279 db_content
["name"], _id
, user
["username"]
1281 HTTPStatus
.CONFLICT
,
1284 # If any VNFD, NSD, NST, PDU, etc. is using this project, raise CONFLICT exception
1285 if not session
["force"]:
1286 check_rw_projects("vnfds", "VNF Descriptor", "id")
1287 check_rw_projects("nsds", "NS Descriptor", "id")
1288 check_rw_projects("nsts", "NS Template", "id")
1289 check_rw_projects("pdus", "PDU Descriptor", "name")
1291 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
1293 Creates a new entry into the authentication backend.
1295 NOTE: Overrides BaseTopic functionality because it doesn't require access to database.
1297 :param rollback: list to append created items at database in case a rollback may to be done
1298 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1299 :param indata: data to be inserted
1300 :param kwargs: used to override the indata descriptor
1301 :param headers: http request headers
1302 :return: _id: identity of the inserted data, operation _id (None)
1305 content
= BaseTopic
._remove
_envelop
(indata
)
1307 # Override descriptor with query string kwargs
1308 BaseTopic
._update
_input
_with
_kwargs
(content
, kwargs
)
1309 content
= self
._validate
_input
_new
(content
, session
["force"])
1310 self
.check_conflict_on_new(session
, content
)
1312 content
, project_id
=session
["project_id"], make_public
=session
["public"]
1314 _id
= self
.auth
.create_project(content
)
1315 rollback
.append({"topic": self
.topic
, "_id": _id
})
1316 self
._send
_msg
("created", content
, not_send_msg
=None)
1318 except ValidationError
as e
:
1319 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
1321 def show(self
, session
, _id
, filter_q
=None, api_req
=False):
1323 Get complete information on an topic
1325 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1326 :param _id: server internal id
1327 :param filter_q: dict: query parameter
1328 :param api_req: True if this call is serving an external API request. False if serving internal request.
1329 :return: dictionary, raise exception if not found.
1331 # Allow _id to be a name or uuid
1332 filter_q
= {self
.id_field(self
.topic
, _id
): _id
}
1333 # projects = self.auth.get_project_list(filter_q=filter_q)
1334 projects
= self
.list(session
, filter_q
) # To allow default filtering (Bug 853)
1335 if len(projects
) == 1:
1337 elif len(projects
) > 1:
1338 raise EngineException("Too many projects found", HTTPStatus
.CONFLICT
)
1340 raise EngineException("Project not found", HTTPStatus
.NOT_FOUND
)
1342 def list(self
, session
, filter_q
=None, api_req
=False):
1344 Get a list of the topic that matches a filter
1346 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1347 :param filter_q: filter of data to be applied
1348 :return: The list, it can be empty if no one match the filter.
1350 project_list
= self
.auth
.get_project_list(filter_q
)
1351 if not session
["allow_show_user_project_role"]:
1352 # Bug 853 - Default filtering
1353 user
= self
.auth
.get_user(session
["username"])
1354 projects
= [prm
["project"] for prm
in user
["project_role_mappings"]]
1355 project_list
= [proj
for proj
in project_list
if proj
["_id"] in projects
]
1358 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
1360 Delete item by its internal _id
1362 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1363 :param _id: server internal id
1364 :param dry_run: make checking but do not delete
1365 :param not_send_msg: To not send message (False) or store content (list) instead
1366 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
1368 # Allow _id to be a name or uuid
1369 proj
= self
.auth
.get_project(_id
)
1371 self
.check_conflict_on_del(session
, pid
, proj
)
1373 v
= self
.auth
.delete_project(pid
)
1374 self
._send
_msg
("deleted", proj
, not_send_msg
=None)
1378 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1380 Updates a project entry.
1382 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1384 :param indata: data to be inserted
1385 :param kwargs: used to override the indata descriptor
1387 :return: _id: identity of the inserted data.
1389 indata
= self
._remove
_envelop
(indata
)
1391 # Override descriptor with query string kwargs
1393 BaseTopic
._update
_input
_with
_kwargs
(indata
, kwargs
)
1396 content
= self
.show(session
, _id
)
1397 indata
= self
._validate
_input
_edit
(indata
, content
, force
=session
["force"])
1398 content
= self
.check_conflict_on_edit(session
, content
, indata
, _id
=_id
)
1399 self
.format_on_edit(content
, indata
)
1400 content_original
= copy
.deepcopy(content
)
1401 deep_update_rfc7396(content
, indata
)
1402 self
.auth
.update_project(content
["_id"], content
)
1403 proj_data
= {"_id": _id
, "changes": indata
, "original": content_original
}
1404 self
._send
_msg
("edited", proj_data
, not_send_msg
=None)
1405 except ValidationError
as e
:
1406 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
1409 class RoleTopicAuth(BaseTopic
):
1411 topic_msg
= None # "roles"
1412 schema_new
= roles_new_schema
1413 schema_edit
= roles_edit_schema
1414 multiproject
= False
1416 def __init__(self
, db
, fs
, msg
, auth
):
1417 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
1419 self
.operations
= auth
.role_permissions
1420 # self.topic = "roles_operations" if isinstance(auth, AuthconnKeystone) else "roles"
1423 def validate_role_definition(operations
, role_definitions
):
1425 Validates the role definition against the operations defined in
1426 the resources to operations files.
1428 :param operations: operations list
1429 :param role_definitions: role definition to test
1430 :return: None if ok, raises ValidationError exception on error
1432 if not role_definitions
.get("permissions"):
1434 ignore_fields
= ["admin", "default"]
1435 for role_def
in role_definitions
["permissions"].keys():
1436 if role_def
in ignore_fields
:
1438 if role_def
[-1] == ":":
1439 raise ValidationError("Operation cannot end with ':'")
1444 for op
in operations
1445 if op
== role_def
or op
.startswith(role_def
+ ":")
1451 raise ValidationError("Invalid permission '{}'".format(role_def
))
1453 def _validate_input_new(self
, input, force
=False):
1455 Validates input user content for a new entry.
1457 :param input: user input content for the new topic
1458 :param force: may be used for being more tolerant
1459 :return: The same input content, or a changed version of it.
1462 validate_input(input, self
.schema_new
)
1463 self
.validate_role_definition(self
.operations
, input)
1467 def _validate_input_edit(self
, input, content
, force
=False):
1469 Validates input user content for updating an entry.
1471 :param input: user input content for the new topic
1472 :param force: may be used for being more tolerant
1473 :return: The same input content, or a changed version of it.
1475 if self
.schema_edit
:
1476 validate_input(input, self
.schema_edit
)
1477 self
.validate_role_definition(self
.operations
, input)
1481 def check_conflict_on_new(self
, session
, indata
):
1483 Check that the data to be inserted is valid
1485 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1486 :param indata: data to be inserted
1487 :return: None or raises EngineException
1489 # check name is not uuid
1490 role_name
= indata
.get("name")
1491 if is_valid_uuid(role_name
):
1492 raise EngineException(
1493 "role name '{}' cannot have an uuid format".format(role_name
),
1494 HTTPStatus
.UNPROCESSABLE_ENTITY
,
1496 # check name not exists
1497 name
= indata
["name"]
1498 # if self.db.get_one(self.topic, {"name": indata.get("name")}, fail_on_empty=False, fail_on_more=False):
1499 if self
.auth
.get_role_list({"name": name
}):
1500 raise EngineException(
1501 "role name '{}' exists".format(name
), HTTPStatus
.CONFLICT
1504 def check_conflict_on_edit(self
, session
, final_content
, edit_content
, _id
):
1506 Check that the data to be edited/uploaded is valid
1508 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1509 :param final_content: data once modified
1510 :param edit_content: incremental data that contains the modifications to apply
1511 :param _id: internal _id
1512 :return: None or raises EngineException
1514 if "default" not in final_content
["permissions"]:
1515 final_content
["permissions"]["default"] = False
1516 if "admin" not in final_content
["permissions"]:
1517 final_content
["permissions"]["admin"] = False
1519 # check name is not uuid
1520 role_name
= edit_content
.get("name")
1521 if is_valid_uuid(role_name
):
1522 raise EngineException(
1523 "role name '{}' cannot have an uuid format".format(role_name
),
1524 HTTPStatus
.UNPROCESSABLE_ENTITY
,
1527 # Check renaming of admin roles
1528 role
= self
.auth
.get_role(_id
)
1529 if role
["name"] in ["system_admin", "project_admin"]:
1530 raise EngineException(
1531 "You cannot rename role '{}'".format(role
["name"]),
1532 http_code
=HTTPStatus
.FORBIDDEN
,
1535 # check name not exists
1536 if "name" in edit_content
:
1537 role_name
= edit_content
["name"]
1538 # if self.db.get_one(self.topic, {"name":role_name,"_id.ne":_id}, fail_on_empty=False, fail_on_more=False):
1539 roles
= self
.auth
.get_role_list({"name": role_name
})
1540 if roles
and roles
[0][BaseTopic
.id_field("roles", _id
)] != _id
:
1541 raise EngineException(
1542 "role name '{}' exists".format(role_name
), HTTPStatus
.CONFLICT
1545 return final_content
1547 def check_conflict_on_del(self
, session
, _id
, db_content
):
1549 Check if deletion can be done because of dependencies if it is not force. To override
1551 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1552 :param _id: internal _id
1553 :param db_content: The database content of this item _id
1554 :return: None if ok or raises EngineException with the conflict
1556 role
= self
.auth
.get_role(_id
)
1557 if role
["name"] in ["system_admin", "project_admin"]:
1558 raise EngineException(
1559 "You cannot delete role '{}'".format(role
["name"]),
1560 http_code
=HTTPStatus
.FORBIDDEN
,
1563 # If any user is using this role, raise CONFLICT exception
1564 if not session
["force"]:
1565 for user
in self
.auth
.get_user_list():
1566 for prm
in user
.get("project_role_mappings"):
1567 if prm
["role"] == _id
:
1568 raise EngineException(
1569 "Role '{}' ({}) is being used by user '{}'".format(
1570 role
["name"], _id
, user
["username"]
1572 HTTPStatus
.CONFLICT
,
1576 def format_on_new(content
, project_id
=None, make_public
=False): # TO BE REMOVED ?
1578 Modifies content descriptor to include _admin
1580 :param content: descriptor to be modified
1581 :param project_id: if included, it add project read/write permissions
1582 :param make_public: if included it is generated as public for reading.
1583 :return: None, but content is modified
1586 if "_admin" not in content
:
1587 content
["_admin"] = {}
1588 if not content
["_admin"].get("created"):
1589 content
["_admin"]["created"] = now
1590 content
["_admin"]["modified"] = now
1592 if "permissions" not in content
:
1593 content
["permissions"] = {}
1595 if "default" not in content
["permissions"]:
1596 content
["permissions"]["default"] = False
1597 if "admin" not in content
["permissions"]:
1598 content
["permissions"]["admin"] = False
1601 def format_on_edit(final_content
, edit_content
):
1603 Modifies final_content descriptor to include the modified date.
1605 :param final_content: final descriptor generated
1606 :param edit_content: alterations to be include
1607 :return: None, but final_content is modified
1609 if "_admin" in final_content
:
1610 final_content
["_admin"]["modified"] = time()
1612 if "permissions" not in final_content
:
1613 final_content
["permissions"] = {}
1615 if "default" not in final_content
["permissions"]:
1616 final_content
["permissions"]["default"] = False
1617 if "admin" not in final_content
["permissions"]:
1618 final_content
["permissions"]["admin"] = False
1621 def show(self
, session
, _id
, filter_q
=None, api_req
=False):
1623 Get complete information on an topic
1625 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1626 :param _id: server internal id
1627 :param filter_q: dict: query parameter
1628 :param api_req: True if this call is serving an external API request. False if serving internal request.
1629 :return: dictionary, raise exception if not found.
1631 filter_q
= {BaseTopic
.id_field(self
.topic
, _id
): _id
}
1632 # roles = self.auth.get_role_list(filter_q)
1633 roles
= self
.list(session
, filter_q
) # To allow default filtering (Bug 853)
1635 raise AuthconnNotFoundException(
1636 "Not found any role with filter {}".format(filter_q
)
1638 elif len(roles
) > 1:
1639 raise AuthconnConflictException(
1640 "Found more than one role with filter {}".format(filter_q
)
1644 def list(self
, session
, filter_q
=None, api_req
=False):
1646 Get a list of the topic that matches a filter
1648 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1649 :param filter_q: filter of data to be applied
1650 :return: The list, it can be empty if no one match the filter.
1652 role_list
= self
.auth
.get_role_list(filter_q
)
1653 if not session
["allow_show_user_project_role"]:
1654 # Bug 853 - Default filtering
1655 user
= self
.auth
.get_user(session
["username"])
1656 roles
= [prm
["role"] for prm
in user
["project_role_mappings"]]
1657 role_list
= [role
for role
in role_list
if role
["_id"] in roles
]
1660 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
1662 Creates a new entry into database.
1664 :param rollback: list to append created items at database in case a rollback may to be done
1665 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1666 :param indata: data to be inserted
1667 :param kwargs: used to override the indata descriptor
1668 :param headers: http request headers
1669 :return: _id: identity of the inserted data, operation _id (None)
1672 content
= self
._remove
_envelop
(indata
)
1674 # Override descriptor with query string kwargs
1675 self
._update
_input
_with
_kwargs
(content
, kwargs
)
1676 content
= self
._validate
_input
_new
(content
, session
["force"])
1677 self
.check_conflict_on_new(session
, content
)
1679 content
, project_id
=session
["project_id"], make_public
=session
["public"]
1681 # role_name = content["name"]
1682 rid
= self
.auth
.create_role(content
)
1683 content
["_id"] = rid
1684 # _id = self.db.create(self.topic, content)
1685 rollback
.append({"topic": self
.topic
, "_id": rid
})
1686 # self._send_msg("created", content, not_send_msg=not_send_msg)
1688 except ValidationError
as e
:
1689 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
1691 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
1693 Delete item by its internal _id
1695 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1696 :param _id: server internal id
1697 :param dry_run: make checking but do not delete
1698 :param not_send_msg: To not send message (False) or store content (list) instead
1699 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
1701 filter_q
= {BaseTopic
.id_field(self
.topic
, _id
): _id
}
1702 roles
= self
.auth
.get_role_list(filter_q
)
1704 raise AuthconnNotFoundException(
1705 "Not found any role with filter {}".format(filter_q
)
1707 elif len(roles
) > 1:
1708 raise AuthconnConflictException(
1709 "Found more than one role with filter {}".format(filter_q
)
1711 rid
= roles
[0]["_id"]
1712 self
.check_conflict_on_del(session
, rid
, None)
1713 # filter_q = {"_id": _id}
1714 # filter_q = {BaseTopic.id_field(self.topic, _id): _id} # To allow role addressing by name
1716 v
= self
.auth
.delete_role(rid
)
1717 # v = self.db.del_one(self.topic, filter_q)
1721 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1723 Updates a role entry.
1725 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1727 :param indata: data to be inserted
1728 :param kwargs: used to override the indata descriptor
1730 :return: _id: identity of the inserted data.
1733 self
._update
_input
_with
_kwargs
(indata
, kwargs
)
1736 content
= self
.show(session
, _id
)
1737 indata
= self
._validate
_input
_edit
(indata
, content
, force
=session
["force"])
1738 deep_update_rfc7396(content
, indata
)
1739 content
= self
.check_conflict_on_edit(session
, content
, indata
, _id
=_id
)
1740 self
.format_on_edit(content
, indata
)
1741 self
.auth
.update_role(content
)
1742 except ValidationError
as e
:
1743 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)