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 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 osmrepo_new_schema
, osmrepo_edit_schema
, \
26 validate_input
, ValidationError
, is_valid_uuid
# To check that User/Project Names don't look like UUIDs
27 from osm_nbi
.base_topic
import BaseTopic
, EngineException
28 from osm_nbi
.authconn
import AuthconnNotFoundException
, AuthconnConflictException
29 from osm_common
.dbbase
import deep_update_rfc7396
32 __author__
= "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
35 class UserTopic(BaseTopic
):
38 schema_new
= user_new_schema
39 schema_edit
= user_edit_schema
42 def __init__(self
, db
, fs
, msg
, auth
):
43 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
46 def _get_project_filter(session
):
48 Generates a filter dictionary for querying database users.
49 Current policy is admin can show all, non admin, only its own user.
50 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
53 if session
["admin"]: # allows all
56 return {"username": session
["username"]}
58 def check_conflict_on_new(self
, session
, indata
):
59 # check username not exists
60 if self
.db
.get_one(self
.topic
, {"username": indata
.get("username")}, fail_on_empty
=False, fail_on_more
=False):
61 raise EngineException("username '{}' exists".format(indata
["username"]), HTTPStatus
.CONFLICT
)
63 if not session
["force"]:
64 for p
in indata
.get("projects") or []:
65 # To allow project addressing by Name as well as ID
66 if not self
.db
.get_one("projects", {BaseTopic
.id_field("projects", p
): p
}, fail_on_empty
=False,
68 raise EngineException("project '{}' does not exist".format(p
), HTTPStatus
.CONFLICT
)
70 def check_conflict_on_del(self
, session
, _id
, db_content
):
72 Check if deletion can be done because of dependencies if it is not force. To override
73 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
74 :param _id: internal _id
75 :param db_content: The database content of this item _id
76 :return: None if ok or raises EngineException with the conflict
78 if _id
== session
["username"]:
79 raise EngineException("You cannot delete your own user", http_code
=HTTPStatus
.CONFLICT
)
82 def format_on_new(content
, project_id
=None, make_public
=False):
83 BaseTopic
.format_on_new(content
, make_public
=False)
84 # Removed so that the UUID is kept, to allow User Name modification
85 # content["_id"] = content["username"]
87 content
["_admin"]["salt"] = salt
88 if content
.get("password"):
89 content
["password"] = sha256(content
["password"].encode('utf-8') + salt
.encode('utf-8')).hexdigest()
90 if content
.get("project_role_mappings"):
91 projects
= [mapping
["project"] for mapping
in content
["project_role_mappings"]]
93 if content
.get("projects"):
94 content
["projects"] += projects
96 content
["projects"] = projects
99 def format_on_edit(final_content
, edit_content
):
100 BaseTopic
.format_on_edit(final_content
, edit_content
)
101 if edit_content
.get("password"):
103 final_content
["_admin"]["salt"] = salt
104 final_content
["password"] = sha256(edit_content
["password"].encode('utf-8') +
105 salt
.encode('utf-8')).hexdigest()
108 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
109 if not session
["admin"]:
110 raise EngineException("needed admin privileges", http_code
=HTTPStatus
.UNAUTHORIZED
)
111 # Names that look like UUIDs are not allowed
112 name
= (indata
if indata
else kwargs
).get("username")
113 if is_valid_uuid(name
):
114 raise EngineException("Usernames that look like UUIDs are not allowed",
115 http_code
=HTTPStatus
.UNPROCESSABLE_ENTITY
)
116 return BaseTopic
.edit(self
, session
, _id
, indata
=indata
, kwargs
=kwargs
, content
=content
)
118 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
119 if not session
["admin"]:
120 raise EngineException("needed admin privileges", http_code
=HTTPStatus
.UNAUTHORIZED
)
121 # Names that look like UUIDs are not allowed
122 name
= indata
["username"] if indata
else kwargs
["username"]
123 if is_valid_uuid(name
):
124 raise EngineException("Usernames that look like UUIDs are not allowed",
125 http_code
=HTTPStatus
.UNPROCESSABLE_ENTITY
)
126 return BaseTopic
.new(self
, rollback
, session
, indata
=indata
, kwargs
=kwargs
, headers
=headers
)
129 class ProjectTopic(BaseTopic
):
131 topic_msg
= "projects"
132 schema_new
= project_new_schema
133 schema_edit
= project_edit_schema
136 def __init__(self
, db
, fs
, msg
, auth
):
137 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
140 def _get_project_filter(session
):
142 Generates a filter dictionary for querying database users.
143 Current policy is admin can show all, non admin, only its own user.
144 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
147 if session
["admin"]: # allows all
150 return {"_id.cont": session
["project_id"]}
152 def check_conflict_on_new(self
, session
, indata
):
153 if not indata
.get("name"):
154 raise EngineException("missing 'name'")
155 # check name not exists
156 if self
.db
.get_one(self
.topic
, {"name": indata
.get("name")}, fail_on_empty
=False, fail_on_more
=False):
157 raise EngineException("name '{}' exists".format(indata
["name"]), HTTPStatus
.CONFLICT
)
160 def format_on_new(content
, project_id
=None, make_public
=False):
161 BaseTopic
.format_on_new(content
, None)
162 # Removed so that the UUID is kept, to allow Project Name modification
163 # content["_id"] = content["name"]
165 def check_conflict_on_del(self
, session
, _id
, db_content
):
167 Check if deletion can be done because of dependencies if it is not force. To override
168 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
169 :param _id: internal _id
170 :param db_content: The database content of this item _id
171 :return: None if ok or raises EngineException with the conflict
173 if _id
in session
["project_id"]:
174 raise EngineException("You cannot delete your own project", http_code
=HTTPStatus
.CONFLICT
)
177 _filter
= {"projects": _id
}
178 if self
.db
.get_list("users", _filter
):
179 raise EngineException("There is some USER that contains this project", http_code
=HTTPStatus
.CONFLICT
)
181 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
182 if not session
["admin"]:
183 raise EngineException("needed admin privileges", http_code
=HTTPStatus
.UNAUTHORIZED
)
184 # Names that look like UUIDs are not allowed
185 name
= (indata
if indata
else kwargs
).get("name")
186 if is_valid_uuid(name
):
187 raise EngineException("Project names that look like UUIDs are not allowed",
188 http_code
=HTTPStatus
.UNPROCESSABLE_ENTITY
)
189 return BaseTopic
.edit(self
, session
, _id
, indata
=indata
, kwargs
=kwargs
, content
=content
)
191 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
192 if not session
["admin"]:
193 raise EngineException("needed admin privileges", http_code
=HTTPStatus
.UNAUTHORIZED
)
194 # Names that look like UUIDs are not allowed
195 name
= indata
["name"] if indata
else kwargs
["name"]
196 if is_valid_uuid(name
):
197 raise EngineException("Project names that look like UUIDs are not allowed",
198 http_code
=HTTPStatus
.UNPROCESSABLE_ENTITY
)
199 return BaseTopic
.new(self
, rollback
, session
, indata
=indata
, kwargs
=kwargs
, headers
=headers
)
202 class CommonVimWimSdn(BaseTopic
):
203 """Common class for VIM, WIM SDN just to unify methods that are equal to all of them"""
204 config_to_encrypt
= {} # what keys at config must be encrypted because contains passwords
205 password_to_encrypt
= "" # key that contains a password
208 def _create_operation(op_type
, params
=None):
210 Creates a dictionary with the information to an operation, similar to ns-lcm-op
211 :param op_type: can be create, edit, delete
212 :param params: operation input parameters
213 :return: new dictionary with
217 "lcmOperationType": op_type
,
218 "operationState": "PROCESSING",
220 "statusEnteredTime": now
,
221 "detailed-status": "",
222 "operationParams": params
,
225 def check_conflict_on_new(self
, session
, indata
):
227 Check that the data to be inserted is valid. It is checked that name is unique
228 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
229 :param indata: data to be inserted
230 :return: None or raises EngineException
232 self
.check_unique_name(session
, indata
["name"], _id
=None)
234 def check_conflict_on_edit(self
, session
, final_content
, edit_content
, _id
):
236 Check that the data to be edited/uploaded is valid. It is checked that name is unique
237 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
238 :param final_content: data once modified. This method may change it.
239 :param edit_content: incremental data that contains the modifications to apply
240 :param _id: internal _id
241 :return: None or raises EngineException
243 if not session
["force"] and edit_content
.get("name"):
244 self
.check_unique_name(session
, edit_content
["name"], _id
=_id
)
246 def format_on_edit(self
, final_content
, edit_content
):
248 Modifies final_content inserting admin information upon edition
249 :param final_content: final content to be stored at database
250 :param edit_content: user requested update content
251 :return: operation id
253 super().format_on_edit(final_content
, edit_content
)
256 schema_version
= final_content
.get("schema_version")
258 if edit_content
.get(self
.password_to_encrypt
):
259 final_content
[self
.password_to_encrypt
] = self
.db
.encrypt(edit_content
[self
.password_to_encrypt
],
260 schema_version
=schema_version
,
261 salt
=final_content
["_id"])
262 config_to_encrypt_keys
= self
.config_to_encrypt
.get(schema_version
) or self
.config_to_encrypt
.get("default")
263 if edit_content
.get("config") and config_to_encrypt_keys
:
265 for p
in config_to_encrypt_keys
:
266 if edit_content
["config"].get(p
):
267 final_content
["config"][p
] = self
.db
.encrypt(edit_content
["config"][p
],
268 schema_version
=schema_version
,
269 salt
=final_content
["_id"])
271 # create edit operation
272 final_content
["_admin"]["operations"].append(self
._create
_operation
("edit"))
273 return "{}:{}".format(final_content
["_id"], len(final_content
["_admin"]["operations"]) - 1)
275 def format_on_new(self
, content
, project_id
=None, make_public
=False):
277 Modifies content descriptor to include _admin and insert create operation
278 :param content: descriptor to be modified
279 :param project_id: if included, it add project read/write permissions. Can be None or a list
280 :param make_public: if included it is generated as public for reading.
281 :return: op_id: operation id on asynchronous operation, None otherwise. In addition content is modified
283 super().format_on_new(content
, project_id
=project_id
, make_public
=make_public
)
284 content
["schema_version"] = schema_version
= "1.11"
287 if content
.get(self
.password_to_encrypt
):
288 content
[self
.password_to_encrypt
] = self
.db
.encrypt(content
[self
.password_to_encrypt
],
289 schema_version
=schema_version
,
291 config_to_encrypt_keys
= self
.config_to_encrypt
.get(schema_version
) or self
.config_to_encrypt
.get("default")
292 if content
.get("config") and config_to_encrypt_keys
:
293 for p
in config_to_encrypt_keys
:
294 if content
["config"].get(p
):
295 content
["config"][p
] = self
.db
.encrypt(content
["config"][p
],
296 schema_version
=schema_version
,
299 content
["_admin"]["operationalState"] = "PROCESSING"
302 content
["_admin"]["operations"] = [self
._create
_operation
("create")]
303 content
["_admin"]["current_operation"] = None
305 return "{}:0".format(content
["_id"])
307 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
309 Delete item by its internal _id
310 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
311 :param _id: server internal id
312 :param dry_run: make checking but do not delete
313 :param not_send_msg: To not send message (False) or store content (list) instead
314 :return: operation id if it is ordered to delete. None otherwise
317 filter_q
= self
._get
_project
_filter
(session
)
318 filter_q
["_id"] = _id
319 db_content
= self
.db
.get_one(self
.topic
, filter_q
)
321 self
.check_conflict_on_del(session
, _id
, db_content
)
325 # remove reference from project_read if there are more projects referencing it. If it last one,
326 # do not remove reference, but order via kafka to delete it
327 if session
["project_id"] and session
["project_id"]:
328 other_projects_referencing
= next((p
for p
in db_content
["_admin"]["projects_read"]
329 if p
not in session
["project_id"] and p
!= "ANY"), None)
331 # check if there are projects referencing it (apart from ANY, that means, public)....
332 if other_projects_referencing
:
333 # remove references but not delete
334 update_dict_pull
= {"_admin.projects_read": session
["project_id"],
335 "_admin.projects_write": session
["project_id"]}
336 self
.db
.set_one(self
.topic
, filter_q
, update_dict
=None, pull_list
=update_dict_pull
)
339 can_write
= next((p
for p
in db_content
["_admin"]["projects_write"] if p
== "ANY" or
340 p
in session
["project_id"]), None)
342 raise EngineException("You have not write permission to delete it",
343 http_code
=HTTPStatus
.UNAUTHORIZED
)
347 self
.db
.del_one(self
.topic
, {"_id": _id
})
349 self
._send
_msg
("deleted", {"_id": _id
, "op_id": op_id
}, not_send_msg
=not_send_msg
)
351 update_dict
= {"_admin.to_delete": True}
352 self
.db
.set_one(self
.topic
, {"_id": _id
},
353 update_dict
=update_dict
,
354 push
={"_admin.operations": self
._create
_operation
("delete")}
356 # the number of operations is the operation_id. db_content does not contains the new operation inserted,
357 # so the -1 is not needed
358 op_id
= "{}:{}".format(db_content
["_id"], len(db_content
["_admin"]["operations"]))
359 self
._send
_msg
("delete", {"_id": _id
, "op_id": op_id
}, not_send_msg
=not_send_msg
)
363 class VimAccountTopic(CommonVimWimSdn
):
364 topic
= "vim_accounts"
365 topic_msg
= "vim_account"
366 schema_new
= vim_account_new_schema
367 schema_edit
= vim_account_edit_schema
369 password_to_encrypt
= "vim_password"
370 config_to_encrypt
= {"1.1": ("admin_password", "nsx_password", "vcenter_password"),
371 "default": ("admin_password", "nsx_password", "vcenter_password", "vrops_password")}
373 def check_conflict_on_del(self
, session
, _id
, db_content
):
375 Check if deletion can be done because of dependencies if it is not force. To override
376 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
377 :param _id: internal _id
378 :param db_content: The database content of this item _id
379 :return: None if ok or raises EngineException with the conflict
383 # check if used by VNF
384 if self
.db
.get_list("vnfrs", {"vim-account-id": _id
}):
385 raise EngineException("There is at least one VNF using this VIM account", http_code
=HTTPStatus
.CONFLICT
)
386 super().check_conflict_on_del(session
, _id
, db_content
)
389 class WimAccountTopic(CommonVimWimSdn
):
390 topic
= "wim_accounts"
391 topic_msg
= "wim_account"
392 schema_new
= wim_account_new_schema
393 schema_edit
= wim_account_edit_schema
395 password_to_encrypt
= "wim_password"
396 config_to_encrypt
= {}
399 class SdnTopic(CommonVimWimSdn
):
402 quota_name
= "sdn_controllers"
403 schema_new
= sdn_new_schema
404 schema_edit
= sdn_edit_schema
406 password_to_encrypt
= "password"
407 config_to_encrypt
= {}
409 def _obtain_url(self
, input, create
):
410 if input.get("ip") or input.get("port"):
411 if not input.get("ip") or not input.get("port") or input.get('url'):
412 raise ValidationError("You must provide both 'ip' and 'port' (deprecated); or just 'url' (prefered)")
413 input['url'] = "http://{}:{}/".format(input["ip"], input["port"])
416 elif create
and not input.get('url'):
417 raise ValidationError("You must provide 'url'")
420 def _validate_input_new(self
, input, force
=False):
421 input = super()._validate
_input
_new
(input, force
)
422 return self
._obtain
_url
(input, True)
424 def _validate_input_edit(self
, input, content
, force
=False):
425 input = super()._validate
_input
_edit
(input, content
, force
)
426 return self
._obtain
_url
(input, False)
429 class K8sClusterTopic(CommonVimWimSdn
):
430 topic
= "k8sclusters"
431 topic_msg
= "k8scluster"
432 schema_new
= k8scluster_new_schema
433 schema_edit
= k8scluster_edit_schema
435 password_to_encrypt
= None
436 config_to_encrypt
= {}
438 def format_on_new(self
, content
, project_id
=None, make_public
=False):
439 oid
= super().format_on_new(content
, project_id
, make_public
)
440 self
.db
.encrypt_decrypt_fields(content
["credentials"], 'encrypt', ['password', 'secret'],
441 schema_version
=content
["schema_version"], salt
=content
["_id"])
442 # Add Helm/Juju Repo lists
443 repos
= {"helm-chart": [], "juju-bundle": []}
444 for proj
in content
["_admin"]["projects_read"]:
446 for repo
in self
.db
.get_list("k8srepos", {"_admin.projects_read": proj
}):
447 if repo
["_id"] not in repos
[repo
["type"]]:
448 repos
[repo
["type"]].append(repo
["_id"])
450 content
["_admin"][k
.replace('-', '_')+"_repos"] = repos
[k
]
453 def format_on_edit(self
, final_content
, edit_content
):
454 if final_content
.get("schema_version") and edit_content
.get("credentials"):
455 self
.db
.encrypt_decrypt_fields(edit_content
["credentials"], 'encrypt', ['password', 'secret'],
456 schema_version
=final_content
["schema_version"], salt
=final_content
["_id"])
457 deep_update_rfc7396(final_content
["credentials"], edit_content
["credentials"])
458 oid
= super().format_on_edit(final_content
, edit_content
)
461 def check_conflict_on_edit(self
, session
, final_content
, edit_content
, _id
):
462 super(CommonVimWimSdn
, self
).check_conflict_on_edit(session
, final_content
, edit_content
, _id
)
463 super().check_conflict_on_edit(session
, final_content
, edit_content
, _id
)
464 # Update Helm/Juju Repo lists
465 repos
= {"helm-chart": [], "juju-bundle": []}
466 for proj
in session
.get("set_project", []):
468 for repo
in self
.db
.get_list("k8srepos", {"_admin.projects_read": proj
}):
469 if repo
["_id"] not in repos
[repo
["type"]]:
470 repos
[repo
["type"]].append(repo
["_id"])
472 rlist
= k
.replace('-', '_') + "_repos"
473 if rlist
not in final_content
["_admin"]:
474 final_content
["_admin"][rlist
] = []
475 final_content
["_admin"][rlist
] += repos
[k
]
477 def check_conflict_on_del(self
, session
, _id
, db_content
):
479 Check if deletion can be done because of dependencies if it is not force. To override
480 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
481 :param _id: internal _id
482 :param db_content: The database content of this item _id
483 :return: None if ok or raises EngineException with the conflict
487 # check if used by VNF
488 filter_q
= {"kdur.k8s-cluster.id": _id
}
489 if session
["project_id"]:
490 filter_q
["_admin.projects_read.cont"] = session
["project_id"]
491 if self
.db
.get_list("vnfrs", filter_q
):
492 raise EngineException("There is at least one VNF using this k8scluster", http_code
=HTTPStatus
.CONFLICT
)
493 super().check_conflict_on_del(session
, _id
, db_content
)
496 class K8sRepoTopic(CommonVimWimSdn
):
498 topic_msg
= "k8srepo"
499 schema_new
= k8srepo_new_schema
500 schema_edit
= k8srepo_edit_schema
502 password_to_encrypt
= None
503 config_to_encrypt
= {}
505 def format_on_new(self
, content
, project_id
=None, make_public
=False):
506 oid
= super().format_on_new(content
, project_id
, make_public
)
507 # Update Helm/Juju Repo lists
508 repo_list
= content
["type"].replace('-', '_')+"_repos"
509 for proj
in content
["_admin"]["projects_read"]:
511 self
.db
.set_list("k8sclusters",
512 {"_admin.projects_read": proj
, "_admin."+repo_list
+".ne": content
["_id"]}, {},
513 push
={"_admin."+repo_list
: content
["_id"]})
516 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
517 type = self
.db
.get_one("k8srepos", {"_id": _id
})["type"]
518 oid
= super().delete(session
, _id
, dry_run
, not_send_msg
)
520 # Remove from Helm/Juju Repo lists
521 repo_list
= type.replace('-', '_') + "_repos"
522 self
.db
.set_list("k8sclusters", {"_admin."+repo_list
: _id
}, {}, pull
={"_admin."+repo_list
: _id
})
526 class OsmRepoTopic(BaseTopic
):
528 topic_msg
= "osmrepos"
529 schema_new
= osmrepo_new_schema
530 schema_edit
= osmrepo_edit_schema
532 # TODO: Implement user/password
535 class UserTopicAuth(UserTopic
):
538 schema_new
= user_new_schema
539 schema_edit
= user_edit_schema
541 def __init__(self
, db
, fs
, msg
, auth
):
542 UserTopic
.__init
__(self
, db
, fs
, msg
, auth
)
545 def check_conflict_on_new(self
, session
, indata
):
547 Check that the data to be inserted is valid
549 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
550 :param indata: data to be inserted
551 :return: None or raises EngineException
553 username
= indata
.get("username")
554 if is_valid_uuid(username
):
555 raise EngineException("username '{}' cannot have a uuid format".format(username
),
556 HTTPStatus
.UNPROCESSABLE_ENTITY
)
558 # Check that username is not used, regardless keystone already checks this
559 if self
.auth
.get_user_list(filter_q
={"name": username
}):
560 raise EngineException("username '{}' is already used".format(username
), HTTPStatus
.CONFLICT
)
562 if "projects" in indata
.keys():
563 # convert to new format project_role_mappings
564 role
= self
.auth
.get_role_list({"name": "project_admin"})
566 role
= self
.auth
.get_role_list()
568 raise AuthconnNotFoundException("Can't find default role for user '{}'".format(username
))
570 if not indata
.get("project_role_mappings"):
571 indata
["project_role_mappings"] = []
572 for project
in indata
["projects"]:
573 pid
= self
.auth
.get_project(project
)["_id"]
574 prm
= {"project": pid
, "role": rid
}
575 if prm
not in indata
["project_role_mappings"]:
576 indata
["project_role_mappings"].append(prm
)
577 # raise EngineException("Format invalid: the keyword 'projects' is not allowed for keystone authentication",
578 # HTTPStatus.BAD_REQUEST)
580 def check_conflict_on_edit(self
, session
, final_content
, edit_content
, _id
):
582 Check that the data to be edited/uploaded is valid
584 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
585 :param final_content: data once modified
586 :param edit_content: incremental data that contains the modifications to apply
587 :param _id: internal _id
588 :return: None or raises EngineException
591 if "username" in edit_content
:
592 username
= edit_content
.get("username")
593 if is_valid_uuid(username
):
594 raise EngineException("username '{}' cannot have an uuid format".format(username
),
595 HTTPStatus
.UNPROCESSABLE_ENTITY
)
597 # Check that username is not used, regardless keystone already checks this
598 if self
.auth
.get_user_list(filter_q
={"name": username
}):
599 raise EngineException("username '{}' is already used".format(username
), HTTPStatus
.CONFLICT
)
601 if final_content
["username"] == "admin":
602 for mapping
in edit_content
.get("remove_project_role_mappings", ()):
603 if mapping
["project"] == "admin" and mapping
.get("role") in (None, "system_admin"):
604 # TODO make this also available for project id and role id
605 raise EngineException("You cannot remove system_admin role from admin user",
606 http_code
=HTTPStatus
.FORBIDDEN
)
608 def check_conflict_on_del(self
, session
, _id
, db_content
):
610 Check if deletion can be done because of dependencies if it is not force. To override
611 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
612 :param _id: internal _id
613 :param db_content: The database content of this item _id
614 :return: None if ok or raises EngineException with the conflict
616 if db_content
["username"] == session
["username"]:
617 raise EngineException("You cannot delete your own login user ", http_code
=HTTPStatus
.CONFLICT
)
618 # TODO: Check that user is not logged in ? How? (Would require listing current tokens)
621 def format_on_show(content
):
623 Modifies the content of the role information to separate the role
624 metadata from the role definition.
626 project_role_mappings
= []
628 if "projects" in content
:
629 for project
in content
["projects"]:
630 for role
in project
["roles"]:
631 project_role_mappings
.append({"project": project
["_id"],
632 "project_name": project
["name"],
634 "role_name": role
["name"]})
635 del content
["projects"]
636 content
["project_role_mappings"] = project_role_mappings
640 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
642 Creates a new entry into the authentication backend.
644 NOTE: Overrides BaseTopic functionality because it doesn't require access to database.
646 :param rollback: list to append created items at database in case a rollback may to be done
647 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
648 :param indata: data to be inserted
649 :param kwargs: used to override the indata descriptor
650 :param headers: http request headers
651 :return: _id: identity of the inserted data, operation _id (None)
654 content
= BaseTopic
._remove
_envelop
(indata
)
656 # Override descriptor with query string kwargs
657 BaseTopic
._update
_input
_with
_kwargs
(content
, kwargs
)
658 content
= self
._validate
_input
_new
(content
, session
["force"])
659 self
.check_conflict_on_new(session
, content
)
660 # self.format_on_new(content, session["project_id"], make_public=session["public"])
662 content
["_admin"] = {"created": now
, "modified": now
}
664 for prm
in content
.get("project_role_mappings", []):
665 proj
= self
.auth
.get_project(prm
["project"], not session
["force"])
666 role
= self
.auth
.get_role(prm
["role"], not session
["force"])
667 pid
= proj
["_id"] if proj
else None
668 rid
= role
["_id"] if role
else None
669 prl
= {"project": pid
, "role": rid
}
672 content
["project_role_mappings"] = prms
673 # _id = self.auth.create_user(content["username"], content["password"])["_id"]
674 _id
= self
.auth
.create_user(content
)["_id"]
676 rollback
.append({"topic": self
.topic
, "_id": _id
})
677 # del content["password"]
678 self
._send
_msg
("created", content
, not_send_msg
=None)
680 except ValidationError
as e
:
681 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
683 def show(self
, session
, _id
, api_req
=False):
685 Get complete information on an topic
687 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
688 :param _id: server internal id or username
689 :param api_req: True if this call is serving an external API request. False if serving internal request.
690 :return: dictionary, raise exception if not found.
692 # Allow _id to be a name or uuid
693 filter_q
= {"username": _id
}
694 # users = self.auth.get_user_list(filter_q)
695 users
= self
.list(session
, filter_q
) # To allow default filtering (Bug 853)
699 raise EngineException("Too many users found for '{}'".format(_id
), HTTPStatus
.CONFLICT
)
701 raise EngineException("User '{}' not found".format(_id
), HTTPStatus
.NOT_FOUND
)
703 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
705 Updates an user entry.
707 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
709 :param indata: data to be inserted
710 :param kwargs: used to override the indata descriptor
712 :return: _id: identity of the inserted data.
714 indata
= self
._remove
_envelop
(indata
)
716 # Override descriptor with query string kwargs
718 BaseTopic
._update
_input
_with
_kwargs
(indata
, kwargs
)
721 content
= self
.show(session
, _id
)
722 indata
= self
._validate
_input
_edit
(indata
, content
, force
=session
["force"])
723 self
.check_conflict_on_edit(session
, content
, indata
, _id
=_id
)
724 # self.format_on_edit(content, indata)
726 if not ("password" in indata
or "username" in indata
or indata
.get("remove_project_role_mappings") or
727 indata
.get("add_project_role_mappings") or indata
.get("project_role_mappings") or
728 indata
.get("projects") or indata
.get("add_projects")):
730 if indata
.get("project_role_mappings") \
731 and (indata
.get("remove_project_role_mappings") or indata
.get("add_project_role_mappings")):
732 raise EngineException("Option 'project_role_mappings' is incompatible with 'add_project_role_mappings"
733 "' or 'remove_project_role_mappings'", http_code
=HTTPStatus
.BAD_REQUEST
)
735 if indata
.get("projects") or indata
.get("add_projects"):
736 role
= self
.auth
.get_role_list({"name": "project_admin"})
738 role
= self
.auth
.get_role_list()
740 raise AuthconnNotFoundException("Can't find a default role for user '{}'"
741 .format(content
["username"]))
743 if "add_project_role_mappings" not in indata
:
744 indata
["add_project_role_mappings"] = []
745 if "remove_project_role_mappings" not in indata
:
746 indata
["remove_project_role_mappings"] = []
747 if isinstance(indata
.get("projects"), dict):
748 # backward compatible
749 for k
, v
in indata
["projects"].items():
750 if k
.startswith("$") and v
is None:
751 indata
["remove_project_role_mappings"].append({"project": k
[1:]})
752 elif k
.startswith("$+"):
753 indata
["add_project_role_mappings"].append({"project": v
, "role": rid
})
754 del indata
["projects"]
755 for proj
in indata
.get("projects", []) + indata
.get("add_projects", []):
756 indata
["add_project_role_mappings"].append({"project": proj
, "role": rid
})
758 # user = self.show(session, _id) # Already in 'content'
759 original_mapping
= content
["project_role_mappings"]
762 mappings_to_remove
= []
765 for to_remove
in indata
.get("remove_project_role_mappings", ()):
766 for mapping
in original_mapping
:
767 if to_remove
["project"] in (mapping
["project"], mapping
["project_name"]):
768 if not to_remove
.get("role") or to_remove
["role"] in (mapping
["role"], mapping
["role_name"]):
769 mappings_to_remove
.append(mapping
)
772 for to_add
in indata
.get("add_project_role_mappings", ()):
773 for mapping
in original_mapping
:
774 if to_add
["project"] in (mapping
["project"], mapping
["project_name"]) and \
775 to_add
["role"] in (mapping
["role"], mapping
["role_name"]):
777 if mapping
in mappings_to_remove
: # do not remove
778 mappings_to_remove
.remove(mapping
)
779 break # do not add, it is already at user
781 pid
= self
.auth
.get_project(to_add
["project"])["_id"]
782 rid
= self
.auth
.get_role(to_add
["role"])["_id"]
783 mappings_to_add
.append({"project": pid
, "role": rid
})
786 if indata
.get("project_role_mappings"):
787 for to_set
in indata
["project_role_mappings"]:
788 for mapping
in original_mapping
:
789 if to_set
["project"] in (mapping
["project"], mapping
["project_name"]) and \
790 to_set
["role"] in (mapping
["role"], mapping
["role_name"]):
791 if mapping
in mappings_to_remove
: # do not remove
792 mappings_to_remove
.remove(mapping
)
793 break # do not add, it is already at user
795 pid
= self
.auth
.get_project(to_set
["project"])["_id"]
796 rid
= self
.auth
.get_role(to_set
["role"])["_id"]
797 mappings_to_add
.append({"project": pid
, "role": rid
})
798 for mapping
in original_mapping
:
799 for to_set
in indata
["project_role_mappings"]:
800 if to_set
["project"] in (mapping
["project"], mapping
["project_name"]) and \
801 to_set
["role"] in (mapping
["role"], mapping
["role_name"]):
805 if mapping
not in mappings_to_remove
: # do not remove
806 mappings_to_remove
.append(mapping
)
808 self
.auth
.update_user({"_id": _id
, "username": indata
.get("username"), "password": indata
.get("password"),
809 "add_project_role_mappings": mappings_to_add
,
810 "remove_project_role_mappings": mappings_to_remove
812 data_to_send
= {'_id': _id
, "changes": indata
}
813 self
._send
_msg
("edited", data_to_send
, not_send_msg
=None)
816 except ValidationError
as e
:
817 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
819 def list(self
, session
, filter_q
=None, api_req
=False):
821 Get a list of the topic that matches a filter
822 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
823 :param filter_q: filter of data to be applied
824 :param api_req: True if this call is serving an external API request. False if serving internal request.
825 :return: The list, it can be empty if no one match the filter.
827 user_list
= self
.auth
.get_user_list(filter_q
)
828 if not session
["allow_show_user_project_role"]:
829 # Bug 853 - Default filtering
830 user_list
= [usr
for usr
in user_list
if usr
["username"] == session
["username"]]
833 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
835 Delete item by its internal _id
837 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
838 :param _id: server internal id
839 :param force: indicates if deletion must be forced in case of conflict
840 :param dry_run: make checking but do not delete
841 :param not_send_msg: To not send message (False) or store content (list) instead
842 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
844 # Allow _id to be a name or uuid
845 user
= self
.auth
.get_user(_id
)
847 self
.check_conflict_on_del(session
, uid
, user
)
849 v
= self
.auth
.delete_user(uid
)
850 self
._send
_msg
("deleted", user
, not_send_msg
=not_send_msg
)
855 class ProjectTopicAuth(ProjectTopic
):
857 topic_msg
= "project"
858 schema_new
= project_new_schema
859 schema_edit
= project_edit_schema
861 def __init__(self
, db
, fs
, msg
, auth
):
862 ProjectTopic
.__init
__(self
, db
, fs
, msg
, auth
)
865 def check_conflict_on_new(self
, session
, indata
):
867 Check that the data to be inserted is valid
869 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
870 :param indata: data to be inserted
871 :return: None or raises EngineException
873 project_name
= indata
.get("name")
874 if is_valid_uuid(project_name
):
875 raise EngineException("project name '{}' cannot have an uuid format".format(project_name
),
876 HTTPStatus
.UNPROCESSABLE_ENTITY
)
878 project_list
= self
.auth
.get_project_list(filter_q
={"name": project_name
})
881 raise EngineException("project '{}' exists".format(project_name
), HTTPStatus
.CONFLICT
)
883 def check_conflict_on_edit(self
, session
, final_content
, edit_content
, _id
):
885 Check that the data to be edited/uploaded is valid
887 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
888 :param final_content: data once modified
889 :param edit_content: incremental data that contains the modifications to apply
890 :param _id: internal _id
891 :return: None or raises EngineException
894 project_name
= edit_content
.get("name")
895 if project_name
!= final_content
["name"]: # It is a true renaming
896 if is_valid_uuid(project_name
):
897 raise EngineException("project name '{}' cannot have an uuid format".format(project_name
),
898 HTTPStatus
.UNPROCESSABLE_ENTITY
)
900 if final_content
["name"] == "admin":
901 raise EngineException("You cannot rename project 'admin'", http_code
=HTTPStatus
.CONFLICT
)
903 # Check that project name is not used, regardless keystone already checks this
904 if project_name
and self
.auth
.get_project_list(filter_q
={"name": project_name
}):
905 raise EngineException("project '{}' is already used".format(project_name
), HTTPStatus
.CONFLICT
)
907 def check_conflict_on_del(self
, session
, _id
, db_content
):
909 Check if deletion can be done because of dependencies if it is not force. To override
911 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
912 :param _id: internal _id
913 :param db_content: The database content of this item _id
914 :return: None if ok or raises EngineException with the conflict
917 def check_rw_projects(topic
, title
, id_field
):
918 for desc
in self
.db
.get_list(topic
):
919 if _id
in desc
["_admin"]["projects_read"] + desc
["_admin"]["projects_write"]:
920 raise EngineException("Project '{}' ({}) is being used by {} '{}'"
921 .format(db_content
["name"], _id
, title
, desc
[id_field
]), HTTPStatus
.CONFLICT
)
923 if _id
in session
["project_id"]:
924 raise EngineException("You cannot delete your own project", http_code
=HTTPStatus
.CONFLICT
)
926 if db_content
["name"] == "admin":
927 raise EngineException("You cannot delete project 'admin'", http_code
=HTTPStatus
.CONFLICT
)
929 # If any user is using this project, raise CONFLICT exception
930 if not session
["force"]:
931 for user
in self
.auth
.get_user_list():
932 for prm
in user
.get("project_role_mappings"):
933 if prm
["project"] == _id
:
934 raise EngineException("Project '{}' ({}) is being used by user '{}'"
935 .format(db_content
["name"], _id
, user
["username"]), HTTPStatus
.CONFLICT
)
937 # If any VNFD, NSD, NST, PDU, etc. is using this project, raise CONFLICT exception
938 if not session
["force"]:
939 check_rw_projects("vnfds", "VNF Descriptor", "id")
940 check_rw_projects("nsds", "NS Descriptor", "id")
941 check_rw_projects("nsts", "NS Template", "id")
942 check_rw_projects("pdus", "PDU Descriptor", "name")
944 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
946 Creates a new entry into the authentication backend.
948 NOTE: Overrides BaseTopic functionality because it doesn't require access to database.
950 :param rollback: list to append created items at database in case a rollback may to be done
951 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
952 :param indata: data to be inserted
953 :param kwargs: used to override the indata descriptor
954 :param headers: http request headers
955 :return: _id: identity of the inserted data, operation _id (None)
958 content
= BaseTopic
._remove
_envelop
(indata
)
960 # Override descriptor with query string kwargs
961 BaseTopic
._update
_input
_with
_kwargs
(content
, kwargs
)
962 content
= self
._validate
_input
_new
(content
, session
["force"])
963 self
.check_conflict_on_new(session
, content
)
964 self
.format_on_new(content
, project_id
=session
["project_id"], make_public
=session
["public"])
965 _id
= self
.auth
.create_project(content
)
966 rollback
.append({"topic": self
.topic
, "_id": _id
})
967 self
._send
_msg
("created", content
, not_send_msg
=None)
969 except ValidationError
as e
:
970 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
972 def show(self
, session
, _id
, api_req
=False):
974 Get complete information on an topic
976 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
977 :param _id: server internal id
978 :param api_req: True if this call is serving an external API request. False if serving internal request.
979 :return: dictionary, raise exception if not found.
981 # Allow _id to be a name or uuid
982 filter_q
= {self
.id_field(self
.topic
, _id
): _id
}
983 # projects = self.auth.get_project_list(filter_q=filter_q)
984 projects
= self
.list(session
, filter_q
) # To allow default filtering (Bug 853)
985 if len(projects
) == 1:
987 elif len(projects
) > 1:
988 raise EngineException("Too many projects found", HTTPStatus
.CONFLICT
)
990 raise EngineException("Project not found", HTTPStatus
.NOT_FOUND
)
992 def list(self
, session
, filter_q
=None, api_req
=False):
994 Get a list of the topic that matches a filter
996 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
997 :param filter_q: filter of data to be applied
998 :return: The list, it can be empty if no one match the filter.
1000 project_list
= self
.auth
.get_project_list(filter_q
)
1001 if not session
["allow_show_user_project_role"]:
1002 # Bug 853 - Default filtering
1003 user
= self
.auth
.get_user(session
["username"])
1004 projects
= [prm
["project"] for prm
in user
["project_role_mappings"]]
1005 project_list
= [proj
for proj
in project_list
if proj
["_id"] in projects
]
1008 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
1010 Delete item by its internal _id
1012 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1013 :param _id: server internal id
1014 :param dry_run: make checking but do not delete
1015 :param not_send_msg: To not send message (False) or store content (list) instead
1016 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
1018 # Allow _id to be a name or uuid
1019 proj
= self
.auth
.get_project(_id
)
1021 self
.check_conflict_on_del(session
, pid
, proj
)
1023 v
= self
.auth
.delete_project(pid
)
1024 self
._send
_msg
("deleted", proj
, not_send_msg
=None)
1028 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1030 Updates a project entry.
1032 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1034 :param indata: data to be inserted
1035 :param kwargs: used to override the indata descriptor
1037 :return: _id: identity of the inserted data.
1039 indata
= self
._remove
_envelop
(indata
)
1041 # Override descriptor with query string kwargs
1043 BaseTopic
._update
_input
_with
_kwargs
(indata
, kwargs
)
1046 content
= self
.show(session
, _id
)
1047 indata
= self
._validate
_input
_edit
(indata
, content
, force
=session
["force"])
1048 self
.check_conflict_on_edit(session
, content
, indata
, _id
=_id
)
1049 self
.format_on_edit(content
, indata
)
1050 content_original
= copy
.deepcopy(content
)
1051 deep_update_rfc7396(content
, indata
)
1052 self
.auth
.update_project(content
["_id"], content
)
1053 proj_data
= {"_id": _id
, "changes": indata
, "original": content_original
}
1054 self
._send
_msg
("edited", proj_data
, not_send_msg
=None)
1055 except ValidationError
as e
:
1056 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
1059 class RoleTopicAuth(BaseTopic
):
1061 topic_msg
= None # "roles"
1062 schema_new
= roles_new_schema
1063 schema_edit
= roles_edit_schema
1064 multiproject
= False
1066 def __init__(self
, db
, fs
, msg
, auth
):
1067 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
1069 self
.operations
= auth
.role_permissions
1070 # self.topic = "roles_operations" if isinstance(auth, AuthconnKeystone) else "roles"
1073 def validate_role_definition(operations
, role_definitions
):
1075 Validates the role definition against the operations defined in
1076 the resources to operations files.
1078 :param operations: operations list
1079 :param role_definitions: role definition to test
1080 :return: None if ok, raises ValidationError exception on error
1082 if not role_definitions
.get("permissions"):
1084 ignore_fields
= ["admin", "default"]
1085 for role_def
in role_definitions
["permissions"].keys():
1086 if role_def
in ignore_fields
:
1088 if role_def
[-1] == ":":
1089 raise ValidationError("Operation cannot end with ':'")
1091 match
= next((op
for op
in operations
if op
== role_def
or op
.startswith(role_def
+ ":")), None)
1094 raise ValidationError("Invalid permission '{}'".format(role_def
))
1096 def _validate_input_new(self
, input, force
=False):
1098 Validates input user content for a new entry.
1100 :param input: user input content for the new topic
1101 :param force: may be used for being more tolerant
1102 :return: The same input content, or a changed version of it.
1105 validate_input(input, self
.schema_new
)
1106 self
.validate_role_definition(self
.operations
, input)
1110 def _validate_input_edit(self
, input, content
, force
=False):
1112 Validates input user content for updating an entry.
1114 :param input: user input content for the new topic
1115 :param force: may be used for being more tolerant
1116 :return: The same input content, or a changed version of it.
1118 if self
.schema_edit
:
1119 validate_input(input, self
.schema_edit
)
1120 self
.validate_role_definition(self
.operations
, input)
1124 def check_conflict_on_new(self
, session
, indata
):
1126 Check that the data to be inserted is valid
1128 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1129 :param indata: data to be inserted
1130 :return: None or raises EngineException
1132 # check name is not uuid
1133 role_name
= indata
.get("name")
1134 if is_valid_uuid(role_name
):
1135 raise EngineException("role name '{}' cannot have an uuid format".format(role_name
),
1136 HTTPStatus
.UNPROCESSABLE_ENTITY
)
1137 # check name not exists
1138 name
= indata
["name"]
1139 # if self.db.get_one(self.topic, {"name": indata.get("name")}, fail_on_empty=False, fail_on_more=False):
1140 if self
.auth
.get_role_list({"name": name
}):
1141 raise EngineException("role name '{}' exists".format(name
), HTTPStatus
.CONFLICT
)
1143 def check_conflict_on_edit(self
, session
, final_content
, edit_content
, _id
):
1145 Check that the data to be edited/uploaded is valid
1147 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1148 :param final_content: data once modified
1149 :param edit_content: incremental data that contains the modifications to apply
1150 :param _id: internal _id
1151 :return: None or raises EngineException
1153 if "default" not in final_content
["permissions"]:
1154 final_content
["permissions"]["default"] = False
1155 if "admin" not in final_content
["permissions"]:
1156 final_content
["permissions"]["admin"] = False
1158 # check name is not uuid
1159 role_name
= edit_content
.get("name")
1160 if is_valid_uuid(role_name
):
1161 raise EngineException("role name '{}' cannot have an uuid format".format(role_name
),
1162 HTTPStatus
.UNPROCESSABLE_ENTITY
)
1164 # Check renaming of admin roles
1165 role
= self
.auth
.get_role(_id
)
1166 if role
["name"] in ["system_admin", "project_admin"]:
1167 raise EngineException("You cannot rename role '{}'".format(role
["name"]), http_code
=HTTPStatus
.FORBIDDEN
)
1169 # check name not exists
1170 if "name" in edit_content
:
1171 role_name
= edit_content
["name"]
1172 # if self.db.get_one(self.topic, {"name":role_name,"_id.ne":_id}, fail_on_empty=False, fail_on_more=False):
1173 roles
= self
.auth
.get_role_list({"name": role_name
})
1174 if roles
and roles
[0][BaseTopic
.id_field("roles", _id
)] != _id
:
1175 raise EngineException("role name '{}' exists".format(role_name
), HTTPStatus
.CONFLICT
)
1177 def check_conflict_on_del(self
, session
, _id
, db_content
):
1179 Check if deletion can be done because of dependencies if it is not force. To override
1181 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1182 :param _id: internal _id
1183 :param db_content: The database content of this item _id
1184 :return: None if ok or raises EngineException with the conflict
1186 role
= self
.auth
.get_role(_id
)
1187 if role
["name"] in ["system_admin", "project_admin"]:
1188 raise EngineException("You cannot delete role '{}'".format(role
["name"]), http_code
=HTTPStatus
.FORBIDDEN
)
1190 # If any user is using this role, raise CONFLICT exception
1191 if not session
["force"]:
1192 for user
in self
.auth
.get_user_list():
1193 for prm
in user
.get("project_role_mappings"):
1194 if prm
["role"] == _id
:
1195 raise EngineException("Role '{}' ({}) is being used by user '{}'"
1196 .format(role
["name"], _id
, user
["username"]), HTTPStatus
.CONFLICT
)
1199 def format_on_new(content
, project_id
=None, make_public
=False): # TO BE REMOVED ?
1201 Modifies content descriptor to include _admin
1203 :param content: descriptor to be modified
1204 :param project_id: if included, it add project read/write permissions
1205 :param make_public: if included it is generated as public for reading.
1206 :return: None, but content is modified
1209 if "_admin" not in content
:
1210 content
["_admin"] = {}
1211 if not content
["_admin"].get("created"):
1212 content
["_admin"]["created"] = now
1213 content
["_admin"]["modified"] = now
1215 if "permissions" not in content
:
1216 content
["permissions"] = {}
1218 if "default" not in content
["permissions"]:
1219 content
["permissions"]["default"] = False
1220 if "admin" not in content
["permissions"]:
1221 content
["permissions"]["admin"] = False
1224 def format_on_edit(final_content
, edit_content
):
1226 Modifies final_content descriptor to include the modified date.
1228 :param final_content: final descriptor generated
1229 :param edit_content: alterations to be include
1230 :return: None, but final_content is modified
1232 if "_admin" in final_content
:
1233 final_content
["_admin"]["modified"] = time()
1235 if "permissions" not in final_content
:
1236 final_content
["permissions"] = {}
1238 if "default" not in final_content
["permissions"]:
1239 final_content
["permissions"]["default"] = False
1240 if "admin" not in final_content
["permissions"]:
1241 final_content
["permissions"]["admin"] = False
1244 def show(self
, session
, _id
, api_req
=False):
1246 Get complete information on an topic
1248 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1249 :param _id: server internal id
1250 :param api_req: True if this call is serving an external API request. False if serving internal request.
1251 :return: dictionary, raise exception if not found.
1253 filter_q
= {BaseTopic
.id_field(self
.topic
, _id
): _id
}
1254 # roles = self.auth.get_role_list(filter_q)
1255 roles
= self
.list(session
, filter_q
) # To allow default filtering (Bug 853)
1257 raise AuthconnNotFoundException("Not found any role with filter {}".format(filter_q
))
1258 elif len(roles
) > 1:
1259 raise AuthconnConflictException("Found more than one role with filter {}".format(filter_q
))
1262 def list(self
, session
, filter_q
=None, api_req
=False):
1264 Get a list of the topic that matches a filter
1266 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1267 :param filter_q: filter of data to be applied
1268 :return: The list, it can be empty if no one match the filter.
1270 role_list
= self
.auth
.get_role_list(filter_q
)
1271 if not session
["allow_show_user_project_role"]:
1272 # Bug 853 - Default filtering
1273 user
= self
.auth
.get_user(session
["username"])
1274 roles
= [prm
["role"] for prm
in user
["project_role_mappings"]]
1275 role_list
= [role
for role
in role_list
if role
["_id"] in roles
]
1278 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
1280 Creates a new entry into database.
1282 :param rollback: list to append created items at database in case a rollback may to be done
1283 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1284 :param indata: data to be inserted
1285 :param kwargs: used to override the indata descriptor
1286 :param headers: http request headers
1287 :return: _id: identity of the inserted data, operation _id (None)
1290 content
= self
._remove
_envelop
(indata
)
1292 # Override descriptor with query string kwargs
1293 self
._update
_input
_with
_kwargs
(content
, kwargs
)
1294 content
= self
._validate
_input
_new
(content
, session
["force"])
1295 self
.check_conflict_on_new(session
, content
)
1296 self
.format_on_new(content
, project_id
=session
["project_id"], make_public
=session
["public"])
1297 # role_name = content["name"]
1298 rid
= self
.auth
.create_role(content
)
1299 content
["_id"] = rid
1300 # _id = self.db.create(self.topic, content)
1301 rollback
.append({"topic": self
.topic
, "_id": rid
})
1302 # self._send_msg("created", content, not_send_msg=not_send_msg)
1304 except ValidationError
as e
:
1305 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
1307 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
1309 Delete item by its internal _id
1311 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1312 :param _id: server internal id
1313 :param dry_run: make checking but do not delete
1314 :param not_send_msg: To not send message (False) or store content (list) instead
1315 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
1317 filter_q
= {BaseTopic
.id_field(self
.topic
, _id
): _id
}
1318 roles
= self
.auth
.get_role_list(filter_q
)
1320 raise AuthconnNotFoundException("Not found any role with filter {}".format(filter_q
))
1321 elif len(roles
) > 1:
1322 raise AuthconnConflictException("Found more than one role with filter {}".format(filter_q
))
1323 rid
= roles
[0]["_id"]
1324 self
.check_conflict_on_del(session
, rid
, None)
1325 # filter_q = {"_id": _id}
1326 # filter_q = {BaseTopic.id_field(self.topic, _id): _id} # To allow role addressing by name
1328 v
= self
.auth
.delete_role(rid
)
1329 # v = self.db.del_one(self.topic, filter_q)
1333 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1335 Updates a role entry.
1337 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1339 :param indata: data to be inserted
1340 :param kwargs: used to override the indata descriptor
1342 :return: _id: identity of the inserted data.
1345 self
._update
_input
_with
_kwargs
(indata
, kwargs
)
1348 content
= self
.show(session
, _id
)
1349 indata
= self
._validate
_input
_edit
(indata
, content
, force
=session
["force"])
1350 deep_update_rfc7396(content
, indata
)
1351 self
.check_conflict_on_edit(session
, content
, indata
, _id
=_id
)
1352 self
.format_on_edit(content
, indata
)
1353 self
.auth
.update_role(content
)
1354 except ValidationError
as e
:
1355 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)