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
)
248 def format_on_edit(self
, final_content
, edit_content
):
250 Modifies final_content inserting admin information upon edition
251 :param final_content: final content to be stored at database
252 :param edit_content: user requested update content
253 :return: operation id
255 super().format_on_edit(final_content
, edit_content
)
258 schema_version
= final_content
.get("schema_version")
260 if edit_content
.get(self
.password_to_encrypt
):
261 final_content
[self
.password_to_encrypt
] = self
.db
.encrypt(edit_content
[self
.password_to_encrypt
],
262 schema_version
=schema_version
,
263 salt
=final_content
["_id"])
264 config_to_encrypt_keys
= self
.config_to_encrypt
.get(schema_version
) or self
.config_to_encrypt
.get("default")
265 if edit_content
.get("config") and config_to_encrypt_keys
:
267 for p
in config_to_encrypt_keys
:
268 if edit_content
["config"].get(p
):
269 final_content
["config"][p
] = self
.db
.encrypt(edit_content
["config"][p
],
270 schema_version
=schema_version
,
271 salt
=final_content
["_id"])
273 # create edit operation
274 final_content
["_admin"]["operations"].append(self
._create
_operation
("edit"))
275 return "{}:{}".format(final_content
["_id"], len(final_content
["_admin"]["operations"]) - 1)
277 def format_on_new(self
, content
, project_id
=None, make_public
=False):
279 Modifies content descriptor to include _admin and insert create operation
280 :param content: descriptor to be modified
281 :param project_id: if included, it add project read/write permissions. Can be None or a list
282 :param make_public: if included it is generated as public for reading.
283 :return: op_id: operation id on asynchronous operation, None otherwise. In addition content is modified
285 super().format_on_new(content
, project_id
=project_id
, make_public
=make_public
)
286 content
["schema_version"] = schema_version
= "1.11"
289 if content
.get(self
.password_to_encrypt
):
290 content
[self
.password_to_encrypt
] = self
.db
.encrypt(content
[self
.password_to_encrypt
],
291 schema_version
=schema_version
,
293 config_to_encrypt_keys
= self
.config_to_encrypt
.get(schema_version
) or self
.config_to_encrypt
.get("default")
294 if content
.get("config") and config_to_encrypt_keys
:
295 for p
in config_to_encrypt_keys
:
296 if content
["config"].get(p
):
297 content
["config"][p
] = self
.db
.encrypt(content
["config"][p
],
298 schema_version
=schema_version
,
301 content
["_admin"]["operationalState"] = "PROCESSING"
304 content
["_admin"]["operations"] = [self
._create
_operation
("create")]
305 content
["_admin"]["current_operation"] = None
307 return "{}:0".format(content
["_id"])
309 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
311 Delete item by its internal _id
312 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
313 :param _id: server internal id
314 :param dry_run: make checking but do not delete
315 :param not_send_msg: To not send message (False) or store content (list) instead
316 :return: operation id if it is ordered to delete. None otherwise
319 filter_q
= self
._get
_project
_filter
(session
)
320 filter_q
["_id"] = _id
321 db_content
= self
.db
.get_one(self
.topic
, filter_q
)
323 self
.check_conflict_on_del(session
, _id
, db_content
)
327 # remove reference from project_read if there are more projects referencing it. If it last one,
328 # do not remove reference, but order via kafka to delete it
329 if session
["project_id"] and session
["project_id"]:
330 other_projects_referencing
= next((p
for p
in db_content
["_admin"]["projects_read"]
331 if p
not in session
["project_id"] and p
!= "ANY"), None)
333 # check if there are projects referencing it (apart from ANY, that means, public)....
334 if other_projects_referencing
:
335 # remove references but not delete
336 update_dict_pull
= {"_admin.projects_read": session
["project_id"],
337 "_admin.projects_write": session
["project_id"]}
338 self
.db
.set_one(self
.topic
, filter_q
, update_dict
=None, pull_list
=update_dict_pull
)
341 can_write
= next((p
for p
in db_content
["_admin"]["projects_write"] if p
== "ANY" or
342 p
in session
["project_id"]), None)
344 raise EngineException("You have not write permission to delete it",
345 http_code
=HTTPStatus
.UNAUTHORIZED
)
349 self
.db
.del_one(self
.topic
, {"_id": _id
})
351 self
._send
_msg
("deleted", {"_id": _id
, "op_id": op_id
}, not_send_msg
=not_send_msg
)
353 update_dict
= {"_admin.to_delete": True}
354 self
.db
.set_one(self
.topic
, {"_id": _id
},
355 update_dict
=update_dict
,
356 push
={"_admin.operations": self
._create
_operation
("delete")}
358 # the number of operations is the operation_id. db_content does not contains the new operation inserted,
359 # so the -1 is not needed
360 op_id
= "{}:{}".format(db_content
["_id"], len(db_content
["_admin"]["operations"]))
361 self
._send
_msg
("delete", {"_id": _id
, "op_id": op_id
}, not_send_msg
=not_send_msg
)
365 class VimAccountTopic(CommonVimWimSdn
):
366 topic
= "vim_accounts"
367 topic_msg
= "vim_account"
368 schema_new
= vim_account_new_schema
369 schema_edit
= vim_account_edit_schema
371 password_to_encrypt
= "vim_password"
372 config_to_encrypt
= {"1.1": ("admin_password", "nsx_password", "vcenter_password"),
373 "default": ("admin_password", "nsx_password", "vcenter_password", "vrops_password")}
375 def check_conflict_on_del(self
, session
, _id
, db_content
):
377 Check if deletion can be done because of dependencies if it is not force. To override
378 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
379 :param _id: internal _id
380 :param db_content: The database content of this item _id
381 :return: None if ok or raises EngineException with the conflict
385 # check if used by VNF
386 if self
.db
.get_list("vnfrs", {"vim-account-id": _id
}):
387 raise EngineException("There is at least one VNF using this VIM account", http_code
=HTTPStatus
.CONFLICT
)
388 super().check_conflict_on_del(session
, _id
, db_content
)
391 class WimAccountTopic(CommonVimWimSdn
):
392 topic
= "wim_accounts"
393 topic_msg
= "wim_account"
394 schema_new
= wim_account_new_schema
395 schema_edit
= wim_account_edit_schema
397 password_to_encrypt
= "wim_password"
398 config_to_encrypt
= {}
401 class SdnTopic(CommonVimWimSdn
):
404 quota_name
= "sdn_controllers"
405 schema_new
= sdn_new_schema
406 schema_edit
= sdn_edit_schema
408 password_to_encrypt
= "password"
409 config_to_encrypt
= {}
411 def _obtain_url(self
, input, create
):
412 if input.get("ip") or input.get("port"):
413 if not input.get("ip") or not input.get("port") or input.get('url'):
414 raise ValidationError("You must provide both 'ip' and 'port' (deprecated); or just 'url' (prefered)")
415 input['url'] = "http://{}:{}/".format(input["ip"], input["port"])
418 elif create
and not input.get('url'):
419 raise ValidationError("You must provide 'url'")
422 def _validate_input_new(self
, input, force
=False):
423 input = super()._validate
_input
_new
(input, force
)
424 return self
._obtain
_url
(input, True)
426 def _validate_input_edit(self
, input, content
, force
=False):
427 input = super()._validate
_input
_edit
(input, content
, force
)
428 return self
._obtain
_url
(input, False)
431 class K8sClusterTopic(CommonVimWimSdn
):
432 topic
= "k8sclusters"
433 topic_msg
= "k8scluster"
434 schema_new
= k8scluster_new_schema
435 schema_edit
= k8scluster_edit_schema
437 password_to_encrypt
= None
438 config_to_encrypt
= {}
440 def format_on_new(self
, content
, project_id
=None, make_public
=False):
441 oid
= super().format_on_new(content
, project_id
, make_public
)
442 self
.db
.encrypt_decrypt_fields(content
["credentials"], 'encrypt', ['password', 'secret'],
443 schema_version
=content
["schema_version"], salt
=content
["_id"])
444 # Add Helm/Juju Repo lists
445 repos
= {"helm-chart": [], "juju-bundle": []}
446 for proj
in content
["_admin"]["projects_read"]:
448 for repo
in self
.db
.get_list("k8srepos", {"_admin.projects_read": proj
}):
449 if repo
["_id"] not in repos
[repo
["type"]]:
450 repos
[repo
["type"]].append(repo
["_id"])
452 content
["_admin"][k
.replace('-', '_')+"_repos"] = repos
[k
]
455 def format_on_edit(self
, final_content
, edit_content
):
456 if final_content
.get("schema_version") and edit_content
.get("credentials"):
457 self
.db
.encrypt_decrypt_fields(edit_content
["credentials"], 'encrypt', ['password', 'secret'],
458 schema_version
=final_content
["schema_version"], salt
=final_content
["_id"])
459 deep_update_rfc7396(final_content
["credentials"], edit_content
["credentials"])
460 oid
= super().format_on_edit(final_content
, edit_content
)
463 def check_conflict_on_edit(self
, session
, final_content
, edit_content
, _id
):
464 final_content
= super(CommonVimWimSdn
, self
).check_conflict_on_edit(session
, final_content
, edit_content
, _id
)
465 final_content
= super().check_conflict_on_edit(session
, final_content
, edit_content
, _id
)
466 # Update Helm/Juju Repo lists
467 repos
= {"helm-chart": [], "juju-bundle": []}
468 for proj
in session
.get("set_project", []):
470 for repo
in self
.db
.get_list("k8srepos", {"_admin.projects_read": proj
}):
471 if repo
["_id"] not in repos
[repo
["type"]]:
472 repos
[repo
["type"]].append(repo
["_id"])
474 rlist
= k
.replace('-', '_') + "_repos"
475 if rlist
not in final_content
["_admin"]:
476 final_content
["_admin"][rlist
] = []
477 final_content
["_admin"][rlist
] += repos
[k
]
480 def check_conflict_on_del(self
, session
, _id
, db_content
):
482 Check if deletion can be done because of dependencies if it is not force. To override
483 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
484 :param _id: internal _id
485 :param db_content: The database content of this item _id
486 :return: None if ok or raises EngineException with the conflict
490 # check if used by VNF
491 filter_q
= {"kdur.k8s-cluster.id": _id
}
492 if session
["project_id"]:
493 filter_q
["_admin.projects_read.cont"] = session
["project_id"]
494 if self
.db
.get_list("vnfrs", filter_q
):
495 raise EngineException("There is at least one VNF using this k8scluster", http_code
=HTTPStatus
.CONFLICT
)
496 super().check_conflict_on_del(session
, _id
, db_content
)
499 class K8sRepoTopic(CommonVimWimSdn
):
501 topic_msg
= "k8srepo"
502 schema_new
= k8srepo_new_schema
503 schema_edit
= k8srepo_edit_schema
505 password_to_encrypt
= None
506 config_to_encrypt
= {}
508 def format_on_new(self
, content
, project_id
=None, make_public
=False):
509 oid
= super().format_on_new(content
, project_id
, make_public
)
510 # Update Helm/Juju Repo lists
511 repo_list
= content
["type"].replace('-', '_')+"_repos"
512 for proj
in content
["_admin"]["projects_read"]:
514 self
.db
.set_list("k8sclusters",
515 {"_admin.projects_read": proj
, "_admin."+repo_list
+".ne": content
["_id"]}, {},
516 push
={"_admin."+repo_list
: content
["_id"]})
519 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
520 type = self
.db
.get_one("k8srepos", {"_id": _id
})["type"]
521 oid
= super().delete(session
, _id
, dry_run
, not_send_msg
)
523 # Remove from Helm/Juju Repo lists
524 repo_list
= type.replace('-', '_') + "_repos"
525 self
.db
.set_list("k8sclusters", {"_admin."+repo_list
: _id
}, {}, pull
={"_admin."+repo_list
: _id
})
529 class OsmRepoTopic(BaseTopic
):
531 topic_msg
= "osmrepos"
532 schema_new
= osmrepo_new_schema
533 schema_edit
= osmrepo_edit_schema
535 # TODO: Implement user/password
538 class UserTopicAuth(UserTopic
):
541 schema_new
= user_new_schema
542 schema_edit
= user_edit_schema
544 def __init__(self
, db
, fs
, msg
, auth
):
545 UserTopic
.__init
__(self
, db
, fs
, msg
, auth
)
548 def check_conflict_on_new(self
, session
, indata
):
550 Check that the data to be inserted is valid
552 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
553 :param indata: data to be inserted
554 :return: None or raises EngineException
556 username
= indata
.get("username")
557 if is_valid_uuid(username
):
558 raise EngineException("username '{}' cannot have a uuid format".format(username
),
559 HTTPStatus
.UNPROCESSABLE_ENTITY
)
561 # Check that username is not used, regardless keystone already checks this
562 if self
.auth
.get_user_list(filter_q
={"name": username
}):
563 raise EngineException("username '{}' is already used".format(username
), HTTPStatus
.CONFLICT
)
565 if "projects" in indata
.keys():
566 # convert to new format project_role_mappings
567 role
= self
.auth
.get_role_list({"name": "project_admin"})
569 role
= self
.auth
.get_role_list()
571 raise AuthconnNotFoundException("Can't find default role for user '{}'".format(username
))
573 if not indata
.get("project_role_mappings"):
574 indata
["project_role_mappings"] = []
575 for project
in indata
["projects"]:
576 pid
= self
.auth
.get_project(project
)["_id"]
577 prm
= {"project": pid
, "role": rid
}
578 if prm
not in indata
["project_role_mappings"]:
579 indata
["project_role_mappings"].append(prm
)
580 # raise EngineException("Format invalid: the keyword 'projects' is not allowed for keystone authentication",
581 # HTTPStatus.BAD_REQUEST)
583 def check_conflict_on_edit(self
, session
, final_content
, edit_content
, _id
):
585 Check that the data to be edited/uploaded is valid
587 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
588 :param final_content: data once modified
589 :param edit_content: incremental data that contains the modifications to apply
590 :param _id: internal _id
591 :return: None or raises EngineException
594 if "username" in edit_content
:
595 username
= edit_content
.get("username")
596 if is_valid_uuid(username
):
597 raise EngineException("username '{}' cannot have an uuid format".format(username
),
598 HTTPStatus
.UNPROCESSABLE_ENTITY
)
600 # Check that username is not used, regardless keystone already checks this
601 if self
.auth
.get_user_list(filter_q
={"name": username
}):
602 raise EngineException("username '{}' is already used".format(username
), HTTPStatus
.CONFLICT
)
604 if final_content
["username"] == "admin":
605 for mapping
in edit_content
.get("remove_project_role_mappings", ()):
606 if mapping
["project"] == "admin" and mapping
.get("role") in (None, "system_admin"):
607 # TODO make this also available for project id and role id
608 raise EngineException("You cannot remove system_admin role from admin user",
609 http_code
=HTTPStatus
.FORBIDDEN
)
613 def check_conflict_on_del(self
, session
, _id
, db_content
):
615 Check if deletion can be done because of dependencies if it is not force. To override
616 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
617 :param _id: internal _id
618 :param db_content: The database content of this item _id
619 :return: None if ok or raises EngineException with the conflict
621 if db_content
["username"] == session
["username"]:
622 raise EngineException("You cannot delete your own login user ", http_code
=HTTPStatus
.CONFLICT
)
623 # TODO: Check that user is not logged in ? How? (Would require listing current tokens)
626 def format_on_show(content
):
628 Modifies the content of the role information to separate the role
629 metadata from the role definition.
631 project_role_mappings
= []
633 if "projects" in content
:
634 for project
in content
["projects"]:
635 for role
in project
["roles"]:
636 project_role_mappings
.append({"project": project
["_id"],
637 "project_name": project
["name"],
639 "role_name": role
["name"]})
640 del content
["projects"]
641 content
["project_role_mappings"] = project_role_mappings
645 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
647 Creates a new entry into the authentication backend.
649 NOTE: Overrides BaseTopic functionality because it doesn't require access to database.
651 :param rollback: list to append created items at database in case a rollback may to be done
652 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
653 :param indata: data to be inserted
654 :param kwargs: used to override the indata descriptor
655 :param headers: http request headers
656 :return: _id: identity of the inserted data, operation _id (None)
659 content
= BaseTopic
._remove
_envelop
(indata
)
661 # Override descriptor with query string kwargs
662 BaseTopic
._update
_input
_with
_kwargs
(content
, kwargs
)
663 content
= self
._validate
_input
_new
(content
, session
["force"])
664 self
.check_conflict_on_new(session
, content
)
665 # self.format_on_new(content, session["project_id"], make_public=session["public"])
667 content
["_admin"] = {"created": now
, "modified": now
}
669 for prm
in content
.get("project_role_mappings", []):
670 proj
= self
.auth
.get_project(prm
["project"], not session
["force"])
671 role
= self
.auth
.get_role(prm
["role"], not session
["force"])
672 pid
= proj
["_id"] if proj
else None
673 rid
= role
["_id"] if role
else None
674 prl
= {"project": pid
, "role": rid
}
677 content
["project_role_mappings"] = prms
678 # _id = self.auth.create_user(content["username"], content["password"])["_id"]
679 _id
= self
.auth
.create_user(content
)["_id"]
681 rollback
.append({"topic": self
.topic
, "_id": _id
})
682 # del content["password"]
683 self
._send
_msg
("created", content
, not_send_msg
=None)
685 except ValidationError
as e
:
686 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
688 def show(self
, session
, _id
, api_req
=False):
690 Get complete information on an topic
692 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
693 :param _id: server internal id or username
694 :param api_req: True if this call is serving an external API request. False if serving internal request.
695 :return: dictionary, raise exception if not found.
697 # Allow _id to be a name or uuid
698 filter_q
= {"username": _id
}
699 # users = self.auth.get_user_list(filter_q)
700 users
= self
.list(session
, filter_q
) # To allow default filtering (Bug 853)
704 raise EngineException("Too many users found for '{}'".format(_id
), HTTPStatus
.CONFLICT
)
706 raise EngineException("User '{}' not found".format(_id
), HTTPStatus
.NOT_FOUND
)
708 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
710 Updates an user entry.
712 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
714 :param indata: data to be inserted
715 :param kwargs: used to override the indata descriptor
717 :return: _id: identity of the inserted data.
719 indata
= self
._remove
_envelop
(indata
)
721 # Override descriptor with query string kwargs
723 BaseTopic
._update
_input
_with
_kwargs
(indata
, kwargs
)
726 content
= self
.show(session
, _id
)
727 indata
= self
._validate
_input
_edit
(indata
, content
, force
=session
["force"])
728 content
= self
.check_conflict_on_edit(session
, content
, indata
, _id
=_id
)
729 # self.format_on_edit(content, indata)
731 if not ("password" in indata
or "username" in indata
or indata
.get("remove_project_role_mappings") or
732 indata
.get("add_project_role_mappings") or indata
.get("project_role_mappings") or
733 indata
.get("projects") or indata
.get("add_projects")):
735 if indata
.get("project_role_mappings") \
736 and (indata
.get("remove_project_role_mappings") or indata
.get("add_project_role_mappings")):
737 raise EngineException("Option 'project_role_mappings' is incompatible with 'add_project_role_mappings"
738 "' or 'remove_project_role_mappings'", http_code
=HTTPStatus
.BAD_REQUEST
)
740 if indata
.get("projects") or indata
.get("add_projects"):
741 role
= self
.auth
.get_role_list({"name": "project_admin"})
743 role
= self
.auth
.get_role_list()
745 raise AuthconnNotFoundException("Can't find a default role for user '{}'"
746 .format(content
["username"]))
748 if "add_project_role_mappings" not in indata
:
749 indata
["add_project_role_mappings"] = []
750 if "remove_project_role_mappings" not in indata
:
751 indata
["remove_project_role_mappings"] = []
752 if isinstance(indata
.get("projects"), dict):
753 # backward compatible
754 for k
, v
in indata
["projects"].items():
755 if k
.startswith("$") and v
is None:
756 indata
["remove_project_role_mappings"].append({"project": k
[1:]})
757 elif k
.startswith("$+"):
758 indata
["add_project_role_mappings"].append({"project": v
, "role": rid
})
759 del indata
["projects"]
760 for proj
in indata
.get("projects", []) + indata
.get("add_projects", []):
761 indata
["add_project_role_mappings"].append({"project": proj
, "role": rid
})
763 # user = self.show(session, _id) # Already in 'content'
764 original_mapping
= content
["project_role_mappings"]
767 mappings_to_remove
= []
770 for to_remove
in indata
.get("remove_project_role_mappings", ()):
771 for mapping
in original_mapping
:
772 if to_remove
["project"] in (mapping
["project"], mapping
["project_name"]):
773 if not to_remove
.get("role") or to_remove
["role"] in (mapping
["role"], mapping
["role_name"]):
774 mappings_to_remove
.append(mapping
)
777 for to_add
in indata
.get("add_project_role_mappings", ()):
778 for mapping
in original_mapping
:
779 if to_add
["project"] in (mapping
["project"], mapping
["project_name"]) and \
780 to_add
["role"] in (mapping
["role"], mapping
["role_name"]):
782 if mapping
in mappings_to_remove
: # do not remove
783 mappings_to_remove
.remove(mapping
)
784 break # do not add, it is already at user
786 pid
= self
.auth
.get_project(to_add
["project"])["_id"]
787 rid
= self
.auth
.get_role(to_add
["role"])["_id"]
788 mappings_to_add
.append({"project": pid
, "role": rid
})
791 if indata
.get("project_role_mappings"):
792 for to_set
in indata
["project_role_mappings"]:
793 for mapping
in original_mapping
:
794 if to_set
["project"] in (mapping
["project"], mapping
["project_name"]) and \
795 to_set
["role"] in (mapping
["role"], mapping
["role_name"]):
796 if mapping
in mappings_to_remove
: # do not remove
797 mappings_to_remove
.remove(mapping
)
798 break # do not add, it is already at user
800 pid
= self
.auth
.get_project(to_set
["project"])["_id"]
801 rid
= self
.auth
.get_role(to_set
["role"])["_id"]
802 mappings_to_add
.append({"project": pid
, "role": rid
})
803 for mapping
in original_mapping
:
804 for to_set
in indata
["project_role_mappings"]:
805 if to_set
["project"] in (mapping
["project"], mapping
["project_name"]) and \
806 to_set
["role"] in (mapping
["role"], mapping
["role_name"]):
810 if mapping
not in mappings_to_remove
: # do not remove
811 mappings_to_remove
.append(mapping
)
813 self
.auth
.update_user({"_id": _id
, "username": indata
.get("username"), "password": indata
.get("password"),
814 "add_project_role_mappings": mappings_to_add
,
815 "remove_project_role_mappings": mappings_to_remove
817 data_to_send
= {'_id': _id
, "changes": indata
}
818 self
._send
_msg
("edited", data_to_send
, not_send_msg
=None)
821 except ValidationError
as e
:
822 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
824 def list(self
, session
, filter_q
=None, api_req
=False):
826 Get a list of the topic that matches a filter
827 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
828 :param filter_q: filter of data to be applied
829 :param api_req: True if this call is serving an external API request. False if serving internal request.
830 :return: The list, it can be empty if no one match the filter.
832 user_list
= self
.auth
.get_user_list(filter_q
)
833 if not session
["allow_show_user_project_role"]:
834 # Bug 853 - Default filtering
835 user_list
= [usr
for usr
in user_list
if usr
["username"] == session
["username"]]
838 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
840 Delete item by its internal _id
842 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
843 :param _id: server internal id
844 :param force: indicates if deletion must be forced in case of conflict
845 :param dry_run: make checking but do not delete
846 :param not_send_msg: To not send message (False) or store content (list) instead
847 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
849 # Allow _id to be a name or uuid
850 user
= self
.auth
.get_user(_id
)
852 self
.check_conflict_on_del(session
, uid
, user
)
854 v
= self
.auth
.delete_user(uid
)
855 self
._send
_msg
("deleted", user
, not_send_msg
=not_send_msg
)
860 class ProjectTopicAuth(ProjectTopic
):
862 topic_msg
= "project"
863 schema_new
= project_new_schema
864 schema_edit
= project_edit_schema
866 def __init__(self
, db
, fs
, msg
, auth
):
867 ProjectTopic
.__init
__(self
, db
, fs
, msg
, auth
)
870 def check_conflict_on_new(self
, session
, indata
):
872 Check that the data to be inserted is valid
874 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
875 :param indata: data to be inserted
876 :return: None or raises EngineException
878 project_name
= indata
.get("name")
879 if is_valid_uuid(project_name
):
880 raise EngineException("project name '{}' cannot have an uuid format".format(project_name
),
881 HTTPStatus
.UNPROCESSABLE_ENTITY
)
883 project_list
= self
.auth
.get_project_list(filter_q
={"name": project_name
})
886 raise EngineException("project '{}' exists".format(project_name
), HTTPStatus
.CONFLICT
)
888 def check_conflict_on_edit(self
, session
, final_content
, edit_content
, _id
):
890 Check that the data to be edited/uploaded is valid
892 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
893 :param final_content: data once modified
894 :param edit_content: incremental data that contains the modifications to apply
895 :param _id: internal _id
896 :return: None or raises EngineException
899 project_name
= edit_content
.get("name")
900 if project_name
!= final_content
["name"]: # It is a true renaming
901 if is_valid_uuid(project_name
):
902 raise EngineException("project name '{}' cannot have an uuid format".format(project_name
),
903 HTTPStatus
.UNPROCESSABLE_ENTITY
)
905 if final_content
["name"] == "admin":
906 raise EngineException("You cannot rename project 'admin'", http_code
=HTTPStatus
.CONFLICT
)
908 # Check that project name is not used, regardless keystone already checks this
909 if project_name
and self
.auth
.get_project_list(filter_q
={"name": project_name
}):
910 raise EngineException("project '{}' is already used".format(project_name
), HTTPStatus
.CONFLICT
)
913 def check_conflict_on_del(self
, session
, _id
, db_content
):
915 Check if deletion can be done because of dependencies if it is not force. To override
917 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
918 :param _id: internal _id
919 :param db_content: The database content of this item _id
920 :return: None if ok or raises EngineException with the conflict
923 def check_rw_projects(topic
, title
, id_field
):
924 for desc
in self
.db
.get_list(topic
):
925 if _id
in desc
["_admin"]["projects_read"] + desc
["_admin"]["projects_write"]:
926 raise EngineException("Project '{}' ({}) is being used by {} '{}'"
927 .format(db_content
["name"], _id
, title
, desc
[id_field
]), HTTPStatus
.CONFLICT
)
929 if _id
in session
["project_id"]:
930 raise EngineException("You cannot delete your own project", http_code
=HTTPStatus
.CONFLICT
)
932 if db_content
["name"] == "admin":
933 raise EngineException("You cannot delete project 'admin'", http_code
=HTTPStatus
.CONFLICT
)
935 # If any user is using this project, raise CONFLICT exception
936 if not session
["force"]:
937 for user
in self
.auth
.get_user_list():
938 for prm
in user
.get("project_role_mappings"):
939 if prm
["project"] == _id
:
940 raise EngineException("Project '{}' ({}) is being used by user '{}'"
941 .format(db_content
["name"], _id
, user
["username"]), HTTPStatus
.CONFLICT
)
943 # If any VNFD, NSD, NST, PDU, etc. is using this project, raise CONFLICT exception
944 if not session
["force"]:
945 check_rw_projects("vnfds", "VNF Descriptor", "id")
946 check_rw_projects("nsds", "NS Descriptor", "id")
947 check_rw_projects("nsts", "NS Template", "id")
948 check_rw_projects("pdus", "PDU Descriptor", "name")
950 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
952 Creates a new entry into the authentication backend.
954 NOTE: Overrides BaseTopic functionality because it doesn't require access to database.
956 :param rollback: list to append created items at database in case a rollback may to be done
957 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
958 :param indata: data to be inserted
959 :param kwargs: used to override the indata descriptor
960 :param headers: http request headers
961 :return: _id: identity of the inserted data, operation _id (None)
964 content
= BaseTopic
._remove
_envelop
(indata
)
966 # Override descriptor with query string kwargs
967 BaseTopic
._update
_input
_with
_kwargs
(content
, kwargs
)
968 content
= self
._validate
_input
_new
(content
, session
["force"])
969 self
.check_conflict_on_new(session
, content
)
970 self
.format_on_new(content
, project_id
=session
["project_id"], make_public
=session
["public"])
971 _id
= self
.auth
.create_project(content
)
972 rollback
.append({"topic": self
.topic
, "_id": _id
})
973 self
._send
_msg
("created", content
, not_send_msg
=None)
975 except ValidationError
as e
:
976 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
978 def show(self
, session
, _id
, api_req
=False):
980 Get complete information on an topic
982 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
983 :param _id: server internal id
984 :param api_req: True if this call is serving an external API request. False if serving internal request.
985 :return: dictionary, raise exception if not found.
987 # Allow _id to be a name or uuid
988 filter_q
= {self
.id_field(self
.topic
, _id
): _id
}
989 # projects = self.auth.get_project_list(filter_q=filter_q)
990 projects
= self
.list(session
, filter_q
) # To allow default filtering (Bug 853)
991 if len(projects
) == 1:
993 elif len(projects
) > 1:
994 raise EngineException("Too many projects found", HTTPStatus
.CONFLICT
)
996 raise EngineException("Project not found", HTTPStatus
.NOT_FOUND
)
998 def list(self
, session
, filter_q
=None, api_req
=False):
1000 Get a list of the topic that matches a filter
1002 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1003 :param filter_q: filter of data to be applied
1004 :return: The list, it can be empty if no one match the filter.
1006 project_list
= self
.auth
.get_project_list(filter_q
)
1007 if not session
["allow_show_user_project_role"]:
1008 # Bug 853 - Default filtering
1009 user
= self
.auth
.get_user(session
["username"])
1010 projects
= [prm
["project"] for prm
in user
["project_role_mappings"]]
1011 project_list
= [proj
for proj
in project_list
if proj
["_id"] in projects
]
1014 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
1016 Delete item by its internal _id
1018 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1019 :param _id: server internal id
1020 :param dry_run: make checking but do not delete
1021 :param not_send_msg: To not send message (False) or store content (list) instead
1022 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
1024 # Allow _id to be a name or uuid
1025 proj
= self
.auth
.get_project(_id
)
1027 self
.check_conflict_on_del(session
, pid
, proj
)
1029 v
= self
.auth
.delete_project(pid
)
1030 self
._send
_msg
("deleted", proj
, not_send_msg
=None)
1034 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1036 Updates a project entry.
1038 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1040 :param indata: data to be inserted
1041 :param kwargs: used to override the indata descriptor
1043 :return: _id: identity of the inserted data.
1045 indata
= self
._remove
_envelop
(indata
)
1047 # Override descriptor with query string kwargs
1049 BaseTopic
._update
_input
_with
_kwargs
(indata
, kwargs
)
1052 content
= self
.show(session
, _id
)
1053 indata
= self
._validate
_input
_edit
(indata
, content
, force
=session
["force"])
1054 content
= self
.check_conflict_on_edit(session
, content
, indata
, _id
=_id
)
1055 self
.format_on_edit(content
, indata
)
1056 content_original
= copy
.deepcopy(content
)
1057 deep_update_rfc7396(content
, indata
)
1058 self
.auth
.update_project(content
["_id"], content
)
1059 proj_data
= {"_id": _id
, "changes": indata
, "original": content_original
}
1060 self
._send
_msg
("edited", proj_data
, not_send_msg
=None)
1061 except ValidationError
as e
:
1062 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
1065 class RoleTopicAuth(BaseTopic
):
1067 topic_msg
= None # "roles"
1068 schema_new
= roles_new_schema
1069 schema_edit
= roles_edit_schema
1070 multiproject
= False
1072 def __init__(self
, db
, fs
, msg
, auth
):
1073 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
1075 self
.operations
= auth
.role_permissions
1076 # self.topic = "roles_operations" if isinstance(auth, AuthconnKeystone) else "roles"
1079 def validate_role_definition(operations
, role_definitions
):
1081 Validates the role definition against the operations defined in
1082 the resources to operations files.
1084 :param operations: operations list
1085 :param role_definitions: role definition to test
1086 :return: None if ok, raises ValidationError exception on error
1088 if not role_definitions
.get("permissions"):
1090 ignore_fields
= ["admin", "default"]
1091 for role_def
in role_definitions
["permissions"].keys():
1092 if role_def
in ignore_fields
:
1094 if role_def
[-1] == ":":
1095 raise ValidationError("Operation cannot end with ':'")
1097 match
= next((op
for op
in operations
if op
== role_def
or op
.startswith(role_def
+ ":")), None)
1100 raise ValidationError("Invalid permission '{}'".format(role_def
))
1102 def _validate_input_new(self
, input, force
=False):
1104 Validates input user content for a new entry.
1106 :param input: user input content for the new topic
1107 :param force: may be used for being more tolerant
1108 :return: The same input content, or a changed version of it.
1111 validate_input(input, self
.schema_new
)
1112 self
.validate_role_definition(self
.operations
, input)
1116 def _validate_input_edit(self
, input, content
, force
=False):
1118 Validates input user content for updating an entry.
1120 :param input: user input content for the new topic
1121 :param force: may be used for being more tolerant
1122 :return: The same input content, or a changed version of it.
1124 if self
.schema_edit
:
1125 validate_input(input, self
.schema_edit
)
1126 self
.validate_role_definition(self
.operations
, input)
1130 def check_conflict_on_new(self
, session
, indata
):
1132 Check that the data to be inserted is valid
1134 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1135 :param indata: data to be inserted
1136 :return: None or raises EngineException
1138 # check name is not uuid
1139 role_name
= indata
.get("name")
1140 if is_valid_uuid(role_name
):
1141 raise EngineException("role name '{}' cannot have an uuid format".format(role_name
),
1142 HTTPStatus
.UNPROCESSABLE_ENTITY
)
1143 # check name not exists
1144 name
= indata
["name"]
1145 # if self.db.get_one(self.topic, {"name": indata.get("name")}, fail_on_empty=False, fail_on_more=False):
1146 if self
.auth
.get_role_list({"name": name
}):
1147 raise EngineException("role name '{}' exists".format(name
), HTTPStatus
.CONFLICT
)
1149 def check_conflict_on_edit(self
, session
, final_content
, edit_content
, _id
):
1151 Check that the data to be edited/uploaded is valid
1153 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1154 :param final_content: data once modified
1155 :param edit_content: incremental data that contains the modifications to apply
1156 :param _id: internal _id
1157 :return: None or raises EngineException
1159 if "default" not in final_content
["permissions"]:
1160 final_content
["permissions"]["default"] = False
1161 if "admin" not in final_content
["permissions"]:
1162 final_content
["permissions"]["admin"] = False
1164 # check name is not uuid
1165 role_name
= edit_content
.get("name")
1166 if is_valid_uuid(role_name
):
1167 raise EngineException("role name '{}' cannot have an uuid format".format(role_name
),
1168 HTTPStatus
.UNPROCESSABLE_ENTITY
)
1170 # Check renaming of admin roles
1171 role
= self
.auth
.get_role(_id
)
1172 if role
["name"] in ["system_admin", "project_admin"]:
1173 raise EngineException("You cannot rename role '{}'".format(role
["name"]), http_code
=HTTPStatus
.FORBIDDEN
)
1175 # check name not exists
1176 if "name" in edit_content
:
1177 role_name
= edit_content
["name"]
1178 # if self.db.get_one(self.topic, {"name":role_name,"_id.ne":_id}, fail_on_empty=False, fail_on_more=False):
1179 roles
= self
.auth
.get_role_list({"name": role_name
})
1180 if roles
and roles
[0][BaseTopic
.id_field("roles", _id
)] != _id
:
1181 raise EngineException("role name '{}' exists".format(role_name
), HTTPStatus
.CONFLICT
)
1183 return final_content
1185 def check_conflict_on_del(self
, session
, _id
, db_content
):
1187 Check if deletion can be done because of dependencies if it is not force. To override
1189 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1190 :param _id: internal _id
1191 :param db_content: The database content of this item _id
1192 :return: None if ok or raises EngineException with the conflict
1194 role
= self
.auth
.get_role(_id
)
1195 if role
["name"] in ["system_admin", "project_admin"]:
1196 raise EngineException("You cannot delete role '{}'".format(role
["name"]), http_code
=HTTPStatus
.FORBIDDEN
)
1198 # If any user is using this role, raise CONFLICT exception
1199 if not session
["force"]:
1200 for user
in self
.auth
.get_user_list():
1201 for prm
in user
.get("project_role_mappings"):
1202 if prm
["role"] == _id
:
1203 raise EngineException("Role '{}' ({}) is being used by user '{}'"
1204 .format(role
["name"], _id
, user
["username"]), HTTPStatus
.CONFLICT
)
1207 def format_on_new(content
, project_id
=None, make_public
=False): # TO BE REMOVED ?
1209 Modifies content descriptor to include _admin
1211 :param content: descriptor to be modified
1212 :param project_id: if included, it add project read/write permissions
1213 :param make_public: if included it is generated as public for reading.
1214 :return: None, but content is modified
1217 if "_admin" not in content
:
1218 content
["_admin"] = {}
1219 if not content
["_admin"].get("created"):
1220 content
["_admin"]["created"] = now
1221 content
["_admin"]["modified"] = now
1223 if "permissions" not in content
:
1224 content
["permissions"] = {}
1226 if "default" not in content
["permissions"]:
1227 content
["permissions"]["default"] = False
1228 if "admin" not in content
["permissions"]:
1229 content
["permissions"]["admin"] = False
1232 def format_on_edit(final_content
, edit_content
):
1234 Modifies final_content descriptor to include the modified date.
1236 :param final_content: final descriptor generated
1237 :param edit_content: alterations to be include
1238 :return: None, but final_content is modified
1240 if "_admin" in final_content
:
1241 final_content
["_admin"]["modified"] = time()
1243 if "permissions" not in final_content
:
1244 final_content
["permissions"] = {}
1246 if "default" not in final_content
["permissions"]:
1247 final_content
["permissions"]["default"] = False
1248 if "admin" not in final_content
["permissions"]:
1249 final_content
["permissions"]["admin"] = False
1252 def show(self
, session
, _id
, api_req
=False):
1254 Get complete information on an topic
1256 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1257 :param _id: server internal id
1258 :param api_req: True if this call is serving an external API request. False if serving internal request.
1259 :return: dictionary, raise exception if not found.
1261 filter_q
= {BaseTopic
.id_field(self
.topic
, _id
): _id
}
1262 # roles = self.auth.get_role_list(filter_q)
1263 roles
= self
.list(session
, filter_q
) # To allow default filtering (Bug 853)
1265 raise AuthconnNotFoundException("Not found any role with filter {}".format(filter_q
))
1266 elif len(roles
) > 1:
1267 raise AuthconnConflictException("Found more than one role with filter {}".format(filter_q
))
1270 def list(self
, session
, filter_q
=None, api_req
=False):
1272 Get a list of the topic that matches a filter
1274 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1275 :param filter_q: filter of data to be applied
1276 :return: The list, it can be empty if no one match the filter.
1278 role_list
= self
.auth
.get_role_list(filter_q
)
1279 if not session
["allow_show_user_project_role"]:
1280 # Bug 853 - Default filtering
1281 user
= self
.auth
.get_user(session
["username"])
1282 roles
= [prm
["role"] for prm
in user
["project_role_mappings"]]
1283 role_list
= [role
for role
in role_list
if role
["_id"] in roles
]
1286 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
1288 Creates a new entry into database.
1290 :param rollback: list to append created items at database in case a rollback may to be done
1291 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1292 :param indata: data to be inserted
1293 :param kwargs: used to override the indata descriptor
1294 :param headers: http request headers
1295 :return: _id: identity of the inserted data, operation _id (None)
1298 content
= self
._remove
_envelop
(indata
)
1300 # Override descriptor with query string kwargs
1301 self
._update
_input
_with
_kwargs
(content
, kwargs
)
1302 content
= self
._validate
_input
_new
(content
, session
["force"])
1303 self
.check_conflict_on_new(session
, content
)
1304 self
.format_on_new(content
, project_id
=session
["project_id"], make_public
=session
["public"])
1305 # role_name = content["name"]
1306 rid
= self
.auth
.create_role(content
)
1307 content
["_id"] = rid
1308 # _id = self.db.create(self.topic, content)
1309 rollback
.append({"topic": self
.topic
, "_id": rid
})
1310 # self._send_msg("created", content, not_send_msg=not_send_msg)
1312 except ValidationError
as e
:
1313 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
1315 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
1317 Delete item by its internal _id
1319 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1320 :param _id: server internal id
1321 :param dry_run: make checking but do not delete
1322 :param not_send_msg: To not send message (False) or store content (list) instead
1323 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
1325 filter_q
= {BaseTopic
.id_field(self
.topic
, _id
): _id
}
1326 roles
= self
.auth
.get_role_list(filter_q
)
1328 raise AuthconnNotFoundException("Not found any role with filter {}".format(filter_q
))
1329 elif len(roles
) > 1:
1330 raise AuthconnConflictException("Found more than one role with filter {}".format(filter_q
))
1331 rid
= roles
[0]["_id"]
1332 self
.check_conflict_on_del(session
, rid
, None)
1333 # filter_q = {"_id": _id}
1334 # filter_q = {BaseTopic.id_field(self.topic, _id): _id} # To allow role addressing by name
1336 v
= self
.auth
.delete_role(rid
)
1337 # v = self.db.del_one(self.topic, filter_q)
1341 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1343 Updates a role entry.
1345 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1347 :param indata: data to be inserted
1348 :param kwargs: used to override the indata descriptor
1350 :return: _id: identity of the inserted data.
1353 self
._update
_input
_with
_kwargs
(indata
, kwargs
)
1356 content
= self
.show(session
, _id
)
1357 indata
= self
._validate
_input
_edit
(indata
, content
, force
=session
["force"])
1358 deep_update_rfc7396(content
, indata
)
1359 content
= self
.check_conflict_on_edit(session
, content
, indata
, _id
=_id
)
1360 self
.format_on_edit(content
, indata
)
1361 self
.auth
.update_role(content
)
1362 except ValidationError
as e
:
1363 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)