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 vca_new_schema
, vca_edit_schema
, \
26 osmrepo_new_schema
, osmrepo_edit_schema
, \
27 validate_input
, ValidationError
, is_valid_uuid
# To check that User/Project Names don't look like UUIDs
28 from osm_nbi
.base_topic
import BaseTopic
, EngineException
29 from osm_nbi
.authconn
import AuthconnNotFoundException
, AuthconnConflictException
30 from osm_common
.dbbase
import deep_update_rfc7396
33 __author__
= "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
36 class UserTopic(BaseTopic
):
39 schema_new
= user_new_schema
40 schema_edit
= user_edit_schema
43 def __init__(self
, db
, fs
, msg
, auth
):
44 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
47 def _get_project_filter(session
):
49 Generates a filter dictionary for querying database users.
50 Current policy is admin can show all, non admin, only its own user.
51 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
54 if session
["admin"]: # allows all
57 return {"username": session
["username"]}
59 def check_conflict_on_new(self
, session
, indata
):
60 # check username not exists
61 if self
.db
.get_one(self
.topic
, {"username": indata
.get("username")}, fail_on_empty
=False, fail_on_more
=False):
62 raise EngineException("username '{}' exists".format(indata
["username"]), HTTPStatus
.CONFLICT
)
64 if not session
["force"]:
65 for p
in indata
.get("projects") or []:
66 # To allow project addressing by Name as well as ID
67 if not self
.db
.get_one("projects", {BaseTopic
.id_field("projects", p
): p
}, fail_on_empty
=False,
69 raise EngineException("project '{}' does not exist".format(p
), HTTPStatus
.CONFLICT
)
71 def check_conflict_on_del(self
, session
, _id
, db_content
):
73 Check if deletion can be done because of dependencies if it is not force. To override
74 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
75 :param _id: internal _id
76 :param db_content: The database content of this item _id
77 :return: None if ok or raises EngineException with the conflict
79 if _id
== session
["username"]:
80 raise EngineException("You cannot delete your own user", http_code
=HTTPStatus
.CONFLICT
)
83 def format_on_new(content
, project_id
=None, make_public
=False):
84 BaseTopic
.format_on_new(content
, make_public
=False)
85 # Removed so that the UUID is kept, to allow User Name modification
86 # content["_id"] = content["username"]
88 content
["_admin"]["salt"] = salt
89 if content
.get("password"):
90 content
["password"] = sha256(content
["password"].encode('utf-8') + salt
.encode('utf-8')).hexdigest()
91 if content
.get("project_role_mappings"):
92 projects
= [mapping
["project"] for mapping
in content
["project_role_mappings"]]
94 if content
.get("projects"):
95 content
["projects"] += projects
97 content
["projects"] = projects
100 def format_on_edit(final_content
, edit_content
):
101 BaseTopic
.format_on_edit(final_content
, edit_content
)
102 if edit_content
.get("password"):
104 final_content
["_admin"]["salt"] = salt
105 final_content
["password"] = sha256(edit_content
["password"].encode('utf-8') +
106 salt
.encode('utf-8')).hexdigest()
109 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
110 if not session
["admin"]:
111 raise EngineException("needed admin privileges", http_code
=HTTPStatus
.UNAUTHORIZED
)
112 # Names that look like UUIDs are not allowed
113 name
= (indata
if indata
else kwargs
).get("username")
114 if is_valid_uuid(name
):
115 raise EngineException("Usernames that look like UUIDs are not allowed",
116 http_code
=HTTPStatus
.UNPROCESSABLE_ENTITY
)
117 return BaseTopic
.edit(self
, session
, _id
, indata
=indata
, kwargs
=kwargs
, content
=content
)
119 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
120 if not session
["admin"]:
121 raise EngineException("needed admin privileges", http_code
=HTTPStatus
.UNAUTHORIZED
)
122 # Names that look like UUIDs are not allowed
123 name
= indata
["username"] if indata
else kwargs
["username"]
124 if is_valid_uuid(name
):
125 raise EngineException("Usernames that look like UUIDs are not allowed",
126 http_code
=HTTPStatus
.UNPROCESSABLE_ENTITY
)
127 return BaseTopic
.new(self
, rollback
, session
, indata
=indata
, kwargs
=kwargs
, headers
=headers
)
130 class ProjectTopic(BaseTopic
):
132 topic_msg
= "projects"
133 schema_new
= project_new_schema
134 schema_edit
= project_edit_schema
137 def __init__(self
, db
, fs
, msg
, auth
):
138 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
141 def _get_project_filter(session
):
143 Generates a filter dictionary for querying database users.
144 Current policy is admin can show all, non admin, only its own user.
145 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
148 if session
["admin"]: # allows all
151 return {"_id.cont": session
["project_id"]}
153 def check_conflict_on_new(self
, session
, indata
):
154 if not indata
.get("name"):
155 raise EngineException("missing 'name'")
156 # check name not exists
157 if self
.db
.get_one(self
.topic
, {"name": indata
.get("name")}, fail_on_empty
=False, fail_on_more
=False):
158 raise EngineException("name '{}' exists".format(indata
["name"]), HTTPStatus
.CONFLICT
)
161 def format_on_new(content
, project_id
=None, make_public
=False):
162 BaseTopic
.format_on_new(content
, None)
163 # Removed so that the UUID is kept, to allow Project Name modification
164 # content["_id"] = content["name"]
166 def check_conflict_on_del(self
, session
, _id
, db_content
):
168 Check if deletion can be done because of dependencies if it is not force. To override
169 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
170 :param _id: internal _id
171 :param db_content: The database content of this item _id
172 :return: None if ok or raises EngineException with the conflict
174 if _id
in session
["project_id"]:
175 raise EngineException("You cannot delete your own project", http_code
=HTTPStatus
.CONFLICT
)
178 _filter
= {"projects": _id
}
179 if self
.db
.get_list("users", _filter
):
180 raise EngineException("There is some USER that contains this project", http_code
=HTTPStatus
.CONFLICT
)
182 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
183 if not session
["admin"]:
184 raise EngineException("needed admin privileges", http_code
=HTTPStatus
.UNAUTHORIZED
)
185 # Names that look like UUIDs are not allowed
186 name
= (indata
if indata
else kwargs
).get("name")
187 if is_valid_uuid(name
):
188 raise EngineException("Project names that look like UUIDs are not allowed",
189 http_code
=HTTPStatus
.UNPROCESSABLE_ENTITY
)
190 return BaseTopic
.edit(self
, session
, _id
, indata
=indata
, kwargs
=kwargs
, content
=content
)
192 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
193 if not session
["admin"]:
194 raise EngineException("needed admin privileges", http_code
=HTTPStatus
.UNAUTHORIZED
)
195 # Names that look like UUIDs are not allowed
196 name
= indata
["name"] if indata
else kwargs
["name"]
197 if is_valid_uuid(name
):
198 raise EngineException("Project names that look like UUIDs are not allowed",
199 http_code
=HTTPStatus
.UNPROCESSABLE_ENTITY
)
200 return BaseTopic
.new(self
, rollback
, session
, indata
=indata
, kwargs
=kwargs
, headers
=headers
)
203 class CommonVimWimSdn(BaseTopic
):
204 """Common class for VIM, WIM SDN just to unify methods that are equal to all of them"""
205 config_to_encrypt
= {} # what keys at config must be encrypted because contains passwords
206 password_to_encrypt
= "" # key that contains a password
209 def _create_operation(op_type
, params
=None):
211 Creates a dictionary with the information to an operation, similar to ns-lcm-op
212 :param op_type: can be create, edit, delete
213 :param params: operation input parameters
214 :return: new dictionary with
218 "lcmOperationType": op_type
,
219 "operationState": "PROCESSING",
221 "statusEnteredTime": now
,
222 "detailed-status": "",
223 "operationParams": params
,
226 def check_conflict_on_new(self
, session
, indata
):
228 Check that the data to be inserted is valid. It is checked that name is unique
229 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
230 :param indata: data to be inserted
231 :return: None or raises EngineException
233 self
.check_unique_name(session
, indata
["name"], _id
=None)
235 def check_conflict_on_edit(self
, session
, final_content
, edit_content
, _id
):
237 Check that the data to be edited/uploaded is valid. It is checked that name is unique
238 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
239 :param final_content: data once modified. This method may change it.
240 :param edit_content: incremental data that contains the modifications to apply
241 :param _id: internal _id
242 :return: None or raises EngineException
244 if not session
["force"] and edit_content
.get("name"):
245 self
.check_unique_name(session
, edit_content
["name"], _id
=_id
)
249 def format_on_edit(self
, final_content
, edit_content
):
251 Modifies final_content inserting admin information upon edition
252 :param final_content: final content to be stored at database
253 :param edit_content: user requested update content
254 :return: operation id
256 super().format_on_edit(final_content
, edit_content
)
259 schema_version
= final_content
.get("schema_version")
261 if edit_content
.get(self
.password_to_encrypt
):
262 final_content
[self
.password_to_encrypt
] = self
.db
.encrypt(edit_content
[self
.password_to_encrypt
],
263 schema_version
=schema_version
,
264 salt
=final_content
["_id"])
265 config_to_encrypt_keys
= self
.config_to_encrypt
.get(schema_version
) or self
.config_to_encrypt
.get("default")
266 if edit_content
.get("config") and config_to_encrypt_keys
:
268 for p
in config_to_encrypt_keys
:
269 if edit_content
["config"].get(p
):
270 final_content
["config"][p
] = self
.db
.encrypt(edit_content
["config"][p
],
271 schema_version
=schema_version
,
272 salt
=final_content
["_id"])
274 # create edit operation
275 final_content
["_admin"]["operations"].append(self
._create
_operation
("edit"))
276 return "{}:{}".format(final_content
["_id"], len(final_content
["_admin"]["operations"]) - 1)
278 def format_on_new(self
, content
, project_id
=None, make_public
=False):
280 Modifies content descriptor to include _admin and insert create operation
281 :param content: descriptor to be modified
282 :param project_id: if included, it add project read/write permissions. Can be None or a list
283 :param make_public: if included it is generated as public for reading.
284 :return: op_id: operation id on asynchronous operation, None otherwise. In addition content is modified
286 super().format_on_new(content
, project_id
=project_id
, make_public
=make_public
)
287 content
["schema_version"] = schema_version
= "1.11"
290 if content
.get(self
.password_to_encrypt
):
291 content
[self
.password_to_encrypt
] = self
.db
.encrypt(content
[self
.password_to_encrypt
],
292 schema_version
=schema_version
,
294 config_to_encrypt_keys
= self
.config_to_encrypt
.get(schema_version
) or self
.config_to_encrypt
.get("default")
295 if content
.get("config") and config_to_encrypt_keys
:
296 for p
in config_to_encrypt_keys
:
297 if content
["config"].get(p
):
298 content
["config"][p
] = self
.db
.encrypt(content
["config"][p
],
299 schema_version
=schema_version
,
302 content
["_admin"]["operationalState"] = "PROCESSING"
305 content
["_admin"]["operations"] = [self
._create
_operation
("create")]
306 content
["_admin"]["current_operation"] = None
308 return "{}:0".format(content
["_id"])
310 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
312 Delete item by its internal _id
313 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
314 :param _id: server internal id
315 :param dry_run: make checking but do not delete
316 :param not_send_msg: To not send message (False) or store content (list) instead
317 :return: operation id if it is ordered to delete. None otherwise
320 filter_q
= self
._get
_project
_filter
(session
)
321 filter_q
["_id"] = _id
322 db_content
= self
.db
.get_one(self
.topic
, filter_q
)
324 self
.check_conflict_on_del(session
, _id
, db_content
)
328 # remove reference from project_read if there are more projects referencing it. If it last one,
329 # do not remove reference, but order via kafka to delete it
330 if session
["project_id"] and session
["project_id"]:
331 other_projects_referencing
= next((p
for p
in db_content
["_admin"]["projects_read"]
332 if p
not in session
["project_id"] and p
!= "ANY"), None)
334 # check if there are projects referencing it (apart from ANY, that means, public)....
335 if other_projects_referencing
:
336 # remove references but not delete
337 update_dict_pull
= {"_admin.projects_read": session
["project_id"],
338 "_admin.projects_write": session
["project_id"]}
339 self
.db
.set_one(self
.topic
, filter_q
, update_dict
=None, pull_list
=update_dict_pull
)
342 can_write
= next((p
for p
in db_content
["_admin"]["projects_write"] if p
== "ANY" or
343 p
in session
["project_id"]), None)
345 raise EngineException("You have not write permission to delete it",
346 http_code
=HTTPStatus
.UNAUTHORIZED
)
350 self
.db
.del_one(self
.topic
, {"_id": _id
})
352 self
._send
_msg
("deleted", {"_id": _id
, "op_id": op_id
}, not_send_msg
=not_send_msg
)
354 update_dict
= {"_admin.to_delete": True}
355 self
.db
.set_one(self
.topic
, {"_id": _id
},
356 update_dict
=update_dict
,
357 push
={"_admin.operations": self
._create
_operation
("delete")}
359 # the number of operations is the operation_id. db_content does not contains the new operation inserted,
360 # so the -1 is not needed
361 op_id
= "{}:{}".format(db_content
["_id"], len(db_content
["_admin"]["operations"]))
362 self
._send
_msg
("delete", {"_id": _id
, "op_id": op_id
}, not_send_msg
=not_send_msg
)
366 class VimAccountTopic(CommonVimWimSdn
):
367 topic
= "vim_accounts"
368 topic_msg
= "vim_account"
369 schema_new
= vim_account_new_schema
370 schema_edit
= vim_account_edit_schema
372 password_to_encrypt
= "vim_password"
373 config_to_encrypt
= {"1.1": ("admin_password", "nsx_password", "vcenter_password"),
374 "default": ("admin_password", "nsx_password", "vcenter_password", "vrops_password")}
376 def check_conflict_on_del(self
, session
, _id
, db_content
):
378 Check if deletion can be done because of dependencies if it is not force. To override
379 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
380 :param _id: internal _id
381 :param db_content: The database content of this item _id
382 :return: None if ok or raises EngineException with the conflict
386 # check if used by VNF
387 if self
.db
.get_list("vnfrs", {"vim-account-id": _id
}):
388 raise EngineException("There is at least one VNF using this VIM account", http_code
=HTTPStatus
.CONFLICT
)
389 super().check_conflict_on_del(session
, _id
, db_content
)
392 class WimAccountTopic(CommonVimWimSdn
):
393 topic
= "wim_accounts"
394 topic_msg
= "wim_account"
395 schema_new
= wim_account_new_schema
396 schema_edit
= wim_account_edit_schema
398 password_to_encrypt
= "wim_password"
399 config_to_encrypt
= {}
402 class SdnTopic(CommonVimWimSdn
):
405 quota_name
= "sdn_controllers"
406 schema_new
= sdn_new_schema
407 schema_edit
= sdn_edit_schema
409 password_to_encrypt
= "password"
410 config_to_encrypt
= {}
412 def _obtain_url(self
, input, create
):
413 if input.get("ip") or input.get("port"):
414 if not input.get("ip") or not input.get("port") or input.get('url'):
415 raise ValidationError("You must provide both 'ip' and 'port' (deprecated); or just 'url' (prefered)")
416 input['url'] = "http://{}:{}/".format(input["ip"], input["port"])
419 elif create
and not input.get('url'):
420 raise ValidationError("You must provide 'url'")
423 def _validate_input_new(self
, input, force
=False):
424 input = super()._validate
_input
_new
(input, force
)
425 return self
._obtain
_url
(input, True)
427 def _validate_input_edit(self
, input, content
, force
=False):
428 input = super()._validate
_input
_edit
(input, content
, force
)
429 return self
._obtain
_url
(input, False)
432 class K8sClusterTopic(CommonVimWimSdn
):
433 topic
= "k8sclusters"
434 topic_msg
= "k8scluster"
435 schema_new
= k8scluster_new_schema
436 schema_edit
= k8scluster_edit_schema
438 password_to_encrypt
= None
439 config_to_encrypt
= {}
441 def format_on_new(self
, content
, project_id
=None, make_public
=False):
442 oid
= super().format_on_new(content
, project_id
, make_public
)
443 self
.db
.encrypt_decrypt_fields(content
["credentials"], 'encrypt', ['password', 'secret'],
444 schema_version
=content
["schema_version"], salt
=content
["_id"])
445 # Add Helm/Juju Repo lists
446 repos
= {"helm-chart": [], "juju-bundle": []}
447 for proj
in content
["_admin"]["projects_read"]:
449 for repo
in self
.db
.get_list("k8srepos", {"_admin.projects_read": proj
}):
450 if repo
["_id"] not in repos
[repo
["type"]]:
451 repos
[repo
["type"]].append(repo
["_id"])
453 content
["_admin"][k
.replace('-', '_')+"_repos"] = repos
[k
]
456 def format_on_edit(self
, final_content
, edit_content
):
457 if final_content
.get("schema_version") and edit_content
.get("credentials"):
458 self
.db
.encrypt_decrypt_fields(edit_content
["credentials"], 'encrypt', ['password', 'secret'],
459 schema_version
=final_content
["schema_version"], salt
=final_content
["_id"])
460 deep_update_rfc7396(final_content
["credentials"], edit_content
["credentials"])
461 oid
= super().format_on_edit(final_content
, edit_content
)
464 def check_conflict_on_edit(self
, session
, final_content
, edit_content
, _id
):
465 final_content
= super(CommonVimWimSdn
, self
).check_conflict_on_edit(session
, final_content
, edit_content
, _id
)
466 final_content
= super().check_conflict_on_edit(session
, final_content
, edit_content
, _id
)
467 # Update Helm/Juju Repo lists
468 repos
= {"helm-chart": [], "juju-bundle": []}
469 for proj
in session
.get("set_project", []):
471 for repo
in self
.db
.get_list("k8srepos", {"_admin.projects_read": proj
}):
472 if repo
["_id"] not in repos
[repo
["type"]]:
473 repos
[repo
["type"]].append(repo
["_id"])
475 rlist
= k
.replace('-', '_') + "_repos"
476 if rlist
not in final_content
["_admin"]:
477 final_content
["_admin"][rlist
] = []
478 final_content
["_admin"][rlist
] += repos
[k
]
481 def check_conflict_on_del(self
, session
, _id
, db_content
):
483 Check if deletion can be done because of dependencies if it is not force. To override
484 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
485 :param _id: internal _id
486 :param db_content: The database content of this item _id
487 :return: None if ok or raises EngineException with the conflict
491 # check if used by VNF
492 filter_q
= {"kdur.k8s-cluster.id": _id
}
493 if session
["project_id"]:
494 filter_q
["_admin.projects_read.cont"] = session
["project_id"]
495 if self
.db
.get_list("vnfrs", filter_q
):
496 raise EngineException("There is at least one VNF using this k8scluster", http_code
=HTTPStatus
.CONFLICT
)
497 super().check_conflict_on_del(session
, _id
, db_content
)
500 class VcaTopic(CommonVimWimSdn
):
503 schema_new
= vca_new_schema
504 schema_edit
= vca_edit_schema
506 password_to_encrypt
= None
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 content
["schema_version"] = schema_version
= "1.11"
511 for key
in ["secret", "cacert"]:
512 content
[key
] = self
.db
.encrypt(
514 schema_version
=schema_version
,
519 def format_on_edit(self
, final_content
, edit_content
):
520 oid
= super().format_on_edit(final_content
, edit_content
)
521 schema_version
= final_content
.get("schema_version")
522 for key
in ["secret", "cacert"]:
523 if key
in edit_content
:
524 final_content
[key
] = self
.db
.encrypt(
526 schema_version
=schema_version
,
527 salt
=final_content
["_id"]
531 def check_conflict_on_del(self
, session
, _id
, db_content
):
533 Check if deletion can be done because of dependencies if it is not force. To override
534 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
535 :param _id: internal _id
536 :param db_content: The database content of this item _id
537 :return: None if ok or raises EngineException with the conflict
541 # check if used by VNF
542 filter_q
= {"vca": _id
}
543 if session
["project_id"]:
544 filter_q
["_admin.projects_read.cont"] = session
["project_id"]
545 if self
.db
.get_list("vim_accounts", filter_q
):
546 raise EngineException("There is at least one VIM account using this vca", http_code
=HTTPStatus
.CONFLICT
)
547 super().check_conflict_on_del(session
, _id
, db_content
)
550 class K8sRepoTopic(CommonVimWimSdn
):
552 topic_msg
= "k8srepo"
553 schema_new
= k8srepo_new_schema
554 schema_edit
= k8srepo_edit_schema
556 password_to_encrypt
= None
557 config_to_encrypt
= {}
559 def format_on_new(self
, content
, project_id
=None, make_public
=False):
560 oid
= super().format_on_new(content
, project_id
, make_public
)
561 # Update Helm/Juju Repo lists
562 repo_list
= content
["type"].replace('-', '_')+"_repos"
563 for proj
in content
["_admin"]["projects_read"]:
565 self
.db
.set_list("k8sclusters",
566 {"_admin.projects_read": proj
, "_admin."+repo_list
+".ne": content
["_id"]}, {},
567 push
={"_admin."+repo_list
: content
["_id"]})
570 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
571 type = self
.db
.get_one("k8srepos", {"_id": _id
})["type"]
572 oid
= super().delete(session
, _id
, dry_run
, not_send_msg
)
574 # Remove from Helm/Juju Repo lists
575 repo_list
= type.replace('-', '_') + "_repos"
576 self
.db
.set_list("k8sclusters", {"_admin."+repo_list
: _id
}, {}, pull
={"_admin."+repo_list
: _id
})
580 class OsmRepoTopic(BaseTopic
):
582 topic_msg
= "osmrepos"
583 schema_new
= osmrepo_new_schema
584 schema_edit
= osmrepo_edit_schema
586 # TODO: Implement user/password
589 class UserTopicAuth(UserTopic
):
592 schema_new
= user_new_schema
593 schema_edit
= user_edit_schema
595 def __init__(self
, db
, fs
, msg
, auth
):
596 UserTopic
.__init
__(self
, db
, fs
, msg
, auth
)
599 def check_conflict_on_new(self
, session
, indata
):
601 Check that the data to be inserted is valid
603 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
604 :param indata: data to be inserted
605 :return: None or raises EngineException
607 username
= indata
.get("username")
608 if is_valid_uuid(username
):
609 raise EngineException("username '{}' cannot have a uuid format".format(username
),
610 HTTPStatus
.UNPROCESSABLE_ENTITY
)
612 # Check that username is not used, regardless keystone already checks this
613 if self
.auth
.get_user_list(filter_q
={"name": username
}):
614 raise EngineException("username '{}' is already used".format(username
), HTTPStatus
.CONFLICT
)
616 if "projects" in indata
.keys():
617 # convert to new format project_role_mappings
618 role
= self
.auth
.get_role_list({"name": "project_admin"})
620 role
= self
.auth
.get_role_list()
622 raise AuthconnNotFoundException("Can't find default role for user '{}'".format(username
))
624 if not indata
.get("project_role_mappings"):
625 indata
["project_role_mappings"] = []
626 for project
in indata
["projects"]:
627 pid
= self
.auth
.get_project(project
)["_id"]
628 prm
= {"project": pid
, "role": rid
}
629 if prm
not in indata
["project_role_mappings"]:
630 indata
["project_role_mappings"].append(prm
)
631 # raise EngineException("Format invalid: the keyword 'projects' is not allowed for keystone authentication",
632 # HTTPStatus.BAD_REQUEST)
634 def check_conflict_on_edit(self
, session
, final_content
, edit_content
, _id
):
636 Check that the data to be edited/uploaded is valid
638 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
639 :param final_content: data once modified
640 :param edit_content: incremental data that contains the modifications to apply
641 :param _id: internal _id
642 :return: None or raises EngineException
645 if "username" in edit_content
:
646 username
= edit_content
.get("username")
647 if is_valid_uuid(username
):
648 raise EngineException("username '{}' cannot have an uuid format".format(username
),
649 HTTPStatus
.UNPROCESSABLE_ENTITY
)
651 # Check that username is not used, regardless keystone already checks this
652 if self
.auth
.get_user_list(filter_q
={"name": username
}):
653 raise EngineException("username '{}' is already used".format(username
), HTTPStatus
.CONFLICT
)
655 if final_content
["username"] == "admin":
656 for mapping
in edit_content
.get("remove_project_role_mappings", ()):
657 if mapping
["project"] == "admin" and mapping
.get("role") in (None, "system_admin"):
658 # TODO make this also available for project id and role id
659 raise EngineException("You cannot remove system_admin role from admin user",
660 http_code
=HTTPStatus
.FORBIDDEN
)
664 def check_conflict_on_del(self
, session
, _id
, db_content
):
666 Check if deletion can be done because of dependencies if it is not force. To override
667 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
668 :param _id: internal _id
669 :param db_content: The database content of this item _id
670 :return: None if ok or raises EngineException with the conflict
672 if db_content
["username"] == session
["username"]:
673 raise EngineException("You cannot delete your own login user ", http_code
=HTTPStatus
.CONFLICT
)
674 # TODO: Check that user is not logged in ? How? (Would require listing current tokens)
677 def format_on_show(content
):
679 Modifies the content of the role information to separate the role
680 metadata from the role definition.
682 project_role_mappings
= []
684 if "projects" in content
:
685 for project
in content
["projects"]:
686 for role
in project
["roles"]:
687 project_role_mappings
.append({"project": project
["_id"],
688 "project_name": project
["name"],
690 "role_name": role
["name"]})
691 del content
["projects"]
692 content
["project_role_mappings"] = project_role_mappings
696 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
698 Creates a new entry into the authentication backend.
700 NOTE: Overrides BaseTopic functionality because it doesn't require access to database.
702 :param rollback: list to append created items at database in case a rollback may to be done
703 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
704 :param indata: data to be inserted
705 :param kwargs: used to override the indata descriptor
706 :param headers: http request headers
707 :return: _id: identity of the inserted data, operation _id (None)
710 content
= BaseTopic
._remove
_envelop
(indata
)
712 # Override descriptor with query string kwargs
713 BaseTopic
._update
_input
_with
_kwargs
(content
, kwargs
)
714 content
= self
._validate
_input
_new
(content
, session
["force"])
715 self
.check_conflict_on_new(session
, content
)
716 # self.format_on_new(content, session["project_id"], make_public=session["public"])
718 content
["_admin"] = {"created": now
, "modified": now
}
720 for prm
in content
.get("project_role_mappings", []):
721 proj
= self
.auth
.get_project(prm
["project"], not session
["force"])
722 role
= self
.auth
.get_role(prm
["role"], not session
["force"])
723 pid
= proj
["_id"] if proj
else None
724 rid
= role
["_id"] if role
else None
725 prl
= {"project": pid
, "role": rid
}
728 content
["project_role_mappings"] = prms
729 # _id = self.auth.create_user(content["username"], content["password"])["_id"]
730 _id
= self
.auth
.create_user(content
)["_id"]
732 rollback
.append({"topic": self
.topic
, "_id": _id
})
733 # del content["password"]
734 self
._send
_msg
("created", content
, not_send_msg
=None)
736 except ValidationError
as e
:
737 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
739 def show(self
, session
, _id
, api_req
=False):
741 Get complete information on an topic
743 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
744 :param _id: server internal id or username
745 :param api_req: True if this call is serving an external API request. False if serving internal request.
746 :return: dictionary, raise exception if not found.
748 # Allow _id to be a name or uuid
749 filter_q
= {"username": _id
}
750 # users = self.auth.get_user_list(filter_q)
751 users
= self
.list(session
, filter_q
) # To allow default filtering (Bug 853)
755 raise EngineException("Too many users found for '{}'".format(_id
), HTTPStatus
.CONFLICT
)
757 raise EngineException("User '{}' not found".format(_id
), HTTPStatus
.NOT_FOUND
)
759 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
761 Updates an user entry.
763 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
765 :param indata: data to be inserted
766 :param kwargs: used to override the indata descriptor
768 :return: _id: identity of the inserted data.
770 indata
= self
._remove
_envelop
(indata
)
772 # Override descriptor with query string kwargs
774 BaseTopic
._update
_input
_with
_kwargs
(indata
, kwargs
)
777 content
= self
.show(session
, _id
)
778 indata
= self
._validate
_input
_edit
(indata
, content
, force
=session
["force"])
779 content
= self
.check_conflict_on_edit(session
, content
, indata
, _id
=_id
)
780 # self.format_on_edit(content, indata)
782 if not ("password" in indata
or "username" in indata
or indata
.get("remove_project_role_mappings") or
783 indata
.get("add_project_role_mappings") or indata
.get("project_role_mappings") or
784 indata
.get("projects") or indata
.get("add_projects")):
786 if indata
.get("project_role_mappings") \
787 and (indata
.get("remove_project_role_mappings") or indata
.get("add_project_role_mappings")):
788 raise EngineException("Option 'project_role_mappings' is incompatible with 'add_project_role_mappings"
789 "' or 'remove_project_role_mappings'", http_code
=HTTPStatus
.BAD_REQUEST
)
791 if indata
.get("projects") or indata
.get("add_projects"):
792 role
= self
.auth
.get_role_list({"name": "project_admin"})
794 role
= self
.auth
.get_role_list()
796 raise AuthconnNotFoundException("Can't find a default role for user '{}'"
797 .format(content
["username"]))
799 if "add_project_role_mappings" not in indata
:
800 indata
["add_project_role_mappings"] = []
801 if "remove_project_role_mappings" not in indata
:
802 indata
["remove_project_role_mappings"] = []
803 if isinstance(indata
.get("projects"), dict):
804 # backward compatible
805 for k
, v
in indata
["projects"].items():
806 if k
.startswith("$") and v
is None:
807 indata
["remove_project_role_mappings"].append({"project": k
[1:]})
808 elif k
.startswith("$+"):
809 indata
["add_project_role_mappings"].append({"project": v
, "role": rid
})
810 del indata
["projects"]
811 for proj
in indata
.get("projects", []) + indata
.get("add_projects", []):
812 indata
["add_project_role_mappings"].append({"project": proj
, "role": rid
})
814 # user = self.show(session, _id) # Already in 'content'
815 original_mapping
= content
["project_role_mappings"]
818 mappings_to_remove
= []
821 for to_remove
in indata
.get("remove_project_role_mappings", ()):
822 for mapping
in original_mapping
:
823 if to_remove
["project"] in (mapping
["project"], mapping
["project_name"]):
824 if not to_remove
.get("role") or to_remove
["role"] in (mapping
["role"], mapping
["role_name"]):
825 mappings_to_remove
.append(mapping
)
828 for to_add
in indata
.get("add_project_role_mappings", ()):
829 for mapping
in original_mapping
:
830 if to_add
["project"] in (mapping
["project"], mapping
["project_name"]) and \
831 to_add
["role"] in (mapping
["role"], mapping
["role_name"]):
833 if mapping
in mappings_to_remove
: # do not remove
834 mappings_to_remove
.remove(mapping
)
835 break # do not add, it is already at user
837 pid
= self
.auth
.get_project(to_add
["project"])["_id"]
838 rid
= self
.auth
.get_role(to_add
["role"])["_id"]
839 mappings_to_add
.append({"project": pid
, "role": rid
})
842 if indata
.get("project_role_mappings"):
843 for to_set
in indata
["project_role_mappings"]:
844 for mapping
in original_mapping
:
845 if to_set
["project"] in (mapping
["project"], mapping
["project_name"]) and \
846 to_set
["role"] in (mapping
["role"], mapping
["role_name"]):
847 if mapping
in mappings_to_remove
: # do not remove
848 mappings_to_remove
.remove(mapping
)
849 break # do not add, it is already at user
851 pid
= self
.auth
.get_project(to_set
["project"])["_id"]
852 rid
= self
.auth
.get_role(to_set
["role"])["_id"]
853 mappings_to_add
.append({"project": pid
, "role": rid
})
854 for mapping
in original_mapping
:
855 for to_set
in indata
["project_role_mappings"]:
856 if to_set
["project"] in (mapping
["project"], mapping
["project_name"]) and \
857 to_set
["role"] in (mapping
["role"], mapping
["role_name"]):
861 if mapping
not in mappings_to_remove
: # do not remove
862 mappings_to_remove
.append(mapping
)
864 self
.auth
.update_user({"_id": _id
, "username": indata
.get("username"), "password": indata
.get("password"),
865 "add_project_role_mappings": mappings_to_add
,
866 "remove_project_role_mappings": mappings_to_remove
868 data_to_send
= {'_id': _id
, "changes": indata
}
869 self
._send
_msg
("edited", data_to_send
, not_send_msg
=None)
872 except ValidationError
as e
:
873 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
875 def list(self
, session
, filter_q
=None, api_req
=False):
877 Get a list of the topic that matches a filter
878 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
879 :param filter_q: filter of data to be applied
880 :param api_req: True if this call is serving an external API request. False if serving internal request.
881 :return: The list, it can be empty if no one match the filter.
883 user_list
= self
.auth
.get_user_list(filter_q
)
884 if not session
["allow_show_user_project_role"]:
885 # Bug 853 - Default filtering
886 user_list
= [usr
for usr
in user_list
if usr
["username"] == session
["username"]]
889 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
891 Delete item by its internal _id
893 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
894 :param _id: server internal id
895 :param force: indicates if deletion must be forced in case of conflict
896 :param dry_run: make checking but do not delete
897 :param not_send_msg: To not send message (False) or store content (list) instead
898 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
900 # Allow _id to be a name or uuid
901 user
= self
.auth
.get_user(_id
)
903 self
.check_conflict_on_del(session
, uid
, user
)
905 v
= self
.auth
.delete_user(uid
)
906 self
._send
_msg
("deleted", user
, not_send_msg
=not_send_msg
)
911 class ProjectTopicAuth(ProjectTopic
):
913 topic_msg
= "project"
914 schema_new
= project_new_schema
915 schema_edit
= project_edit_schema
917 def __init__(self
, db
, fs
, msg
, auth
):
918 ProjectTopic
.__init
__(self
, db
, fs
, msg
, auth
)
921 def check_conflict_on_new(self
, session
, indata
):
923 Check that the data to be inserted is valid
925 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
926 :param indata: data to be inserted
927 :return: None or raises EngineException
929 project_name
= indata
.get("name")
930 if is_valid_uuid(project_name
):
931 raise EngineException("project name '{}' cannot have an uuid format".format(project_name
),
932 HTTPStatus
.UNPROCESSABLE_ENTITY
)
934 project_list
= self
.auth
.get_project_list(filter_q
={"name": project_name
})
937 raise EngineException("project '{}' exists".format(project_name
), HTTPStatus
.CONFLICT
)
939 def check_conflict_on_edit(self
, session
, final_content
, edit_content
, _id
):
941 Check that the data to be edited/uploaded is valid
943 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
944 :param final_content: data once modified
945 :param edit_content: incremental data that contains the modifications to apply
946 :param _id: internal _id
947 :return: None or raises EngineException
950 project_name
= edit_content
.get("name")
951 if project_name
!= final_content
["name"]: # It is a true renaming
952 if is_valid_uuid(project_name
):
953 raise EngineException("project name '{}' cannot have an uuid format".format(project_name
),
954 HTTPStatus
.UNPROCESSABLE_ENTITY
)
956 if final_content
["name"] == "admin":
957 raise EngineException("You cannot rename project 'admin'", http_code
=HTTPStatus
.CONFLICT
)
959 # Check that project name is not used, regardless keystone already checks this
960 if project_name
and self
.auth
.get_project_list(filter_q
={"name": project_name
}):
961 raise EngineException("project '{}' is already used".format(project_name
), HTTPStatus
.CONFLICT
)
964 def check_conflict_on_del(self
, session
, _id
, db_content
):
966 Check if deletion can be done because of dependencies if it is not force. To override
968 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
969 :param _id: internal _id
970 :param db_content: The database content of this item _id
971 :return: None if ok or raises EngineException with the conflict
974 def check_rw_projects(topic
, title
, id_field
):
975 for desc
in self
.db
.get_list(topic
):
976 if _id
in desc
["_admin"]["projects_read"] + desc
["_admin"]["projects_write"]:
977 raise EngineException("Project '{}' ({}) is being used by {} '{}'"
978 .format(db_content
["name"], _id
, title
, desc
[id_field
]), HTTPStatus
.CONFLICT
)
980 if _id
in session
["project_id"]:
981 raise EngineException("You cannot delete your own project", http_code
=HTTPStatus
.CONFLICT
)
983 if db_content
["name"] == "admin":
984 raise EngineException("You cannot delete project 'admin'", http_code
=HTTPStatus
.CONFLICT
)
986 # If any user is using this project, raise CONFLICT exception
987 if not session
["force"]:
988 for user
in self
.auth
.get_user_list():
989 for prm
in user
.get("project_role_mappings"):
990 if prm
["project"] == _id
:
991 raise EngineException("Project '{}' ({}) is being used by user '{}'"
992 .format(db_content
["name"], _id
, user
["username"]), HTTPStatus
.CONFLICT
)
994 # If any VNFD, NSD, NST, PDU, etc. is using this project, raise CONFLICT exception
995 if not session
["force"]:
996 check_rw_projects("vnfds", "VNF Descriptor", "id")
997 check_rw_projects("nsds", "NS Descriptor", "id")
998 check_rw_projects("nsts", "NS Template", "id")
999 check_rw_projects("pdus", "PDU Descriptor", "name")
1001 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
1003 Creates a new entry into the authentication backend.
1005 NOTE: Overrides BaseTopic functionality because it doesn't require access to database.
1007 :param rollback: list to append created items at database in case a rollback may to be done
1008 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1009 :param indata: data to be inserted
1010 :param kwargs: used to override the indata descriptor
1011 :param headers: http request headers
1012 :return: _id: identity of the inserted data, operation _id (None)
1015 content
= BaseTopic
._remove
_envelop
(indata
)
1017 # Override descriptor with query string kwargs
1018 BaseTopic
._update
_input
_with
_kwargs
(content
, kwargs
)
1019 content
= self
._validate
_input
_new
(content
, session
["force"])
1020 self
.check_conflict_on_new(session
, content
)
1021 self
.format_on_new(content
, project_id
=session
["project_id"], make_public
=session
["public"])
1022 _id
= self
.auth
.create_project(content
)
1023 rollback
.append({"topic": self
.topic
, "_id": _id
})
1024 self
._send
_msg
("created", content
, not_send_msg
=None)
1026 except ValidationError
as e
:
1027 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
1029 def show(self
, session
, _id
, api_req
=False):
1031 Get complete information on an topic
1033 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1034 :param _id: server internal id
1035 :param api_req: True if this call is serving an external API request. False if serving internal request.
1036 :return: dictionary, raise exception if not found.
1038 # Allow _id to be a name or uuid
1039 filter_q
= {self
.id_field(self
.topic
, _id
): _id
}
1040 # projects = self.auth.get_project_list(filter_q=filter_q)
1041 projects
= self
.list(session
, filter_q
) # To allow default filtering (Bug 853)
1042 if len(projects
) == 1:
1044 elif len(projects
) > 1:
1045 raise EngineException("Too many projects found", HTTPStatus
.CONFLICT
)
1047 raise EngineException("Project not found", HTTPStatus
.NOT_FOUND
)
1049 def list(self
, session
, filter_q
=None, api_req
=False):
1051 Get a list of the topic that matches a filter
1053 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1054 :param filter_q: filter of data to be applied
1055 :return: The list, it can be empty if no one match the filter.
1057 project_list
= self
.auth
.get_project_list(filter_q
)
1058 if not session
["allow_show_user_project_role"]:
1059 # Bug 853 - Default filtering
1060 user
= self
.auth
.get_user(session
["username"])
1061 projects
= [prm
["project"] for prm
in user
["project_role_mappings"]]
1062 project_list
= [proj
for proj
in project_list
if proj
["_id"] in projects
]
1065 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
1067 Delete item by its internal _id
1069 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1070 :param _id: server internal id
1071 :param dry_run: make checking but do not delete
1072 :param not_send_msg: To not send message (False) or store content (list) instead
1073 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
1075 # Allow _id to be a name or uuid
1076 proj
= self
.auth
.get_project(_id
)
1078 self
.check_conflict_on_del(session
, pid
, proj
)
1080 v
= self
.auth
.delete_project(pid
)
1081 self
._send
_msg
("deleted", proj
, not_send_msg
=None)
1085 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1087 Updates a project entry.
1089 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1091 :param indata: data to be inserted
1092 :param kwargs: used to override the indata descriptor
1094 :return: _id: identity of the inserted data.
1096 indata
= self
._remove
_envelop
(indata
)
1098 # Override descriptor with query string kwargs
1100 BaseTopic
._update
_input
_with
_kwargs
(indata
, kwargs
)
1103 content
= self
.show(session
, _id
)
1104 indata
= self
._validate
_input
_edit
(indata
, content
, force
=session
["force"])
1105 content
= self
.check_conflict_on_edit(session
, content
, indata
, _id
=_id
)
1106 self
.format_on_edit(content
, indata
)
1107 content_original
= copy
.deepcopy(content
)
1108 deep_update_rfc7396(content
, indata
)
1109 self
.auth
.update_project(content
["_id"], content
)
1110 proj_data
= {"_id": _id
, "changes": indata
, "original": content_original
}
1111 self
._send
_msg
("edited", proj_data
, not_send_msg
=None)
1112 except ValidationError
as e
:
1113 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
1116 class RoleTopicAuth(BaseTopic
):
1118 topic_msg
= None # "roles"
1119 schema_new
= roles_new_schema
1120 schema_edit
= roles_edit_schema
1121 multiproject
= False
1123 def __init__(self
, db
, fs
, msg
, auth
):
1124 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
1126 self
.operations
= auth
.role_permissions
1127 # self.topic = "roles_operations" if isinstance(auth, AuthconnKeystone) else "roles"
1130 def validate_role_definition(operations
, role_definitions
):
1132 Validates the role definition against the operations defined in
1133 the resources to operations files.
1135 :param operations: operations list
1136 :param role_definitions: role definition to test
1137 :return: None if ok, raises ValidationError exception on error
1139 if not role_definitions
.get("permissions"):
1141 ignore_fields
= ["admin", "default"]
1142 for role_def
in role_definitions
["permissions"].keys():
1143 if role_def
in ignore_fields
:
1145 if role_def
[-1] == ":":
1146 raise ValidationError("Operation cannot end with ':'")
1148 match
= next((op
for op
in operations
if op
== role_def
or op
.startswith(role_def
+ ":")), None)
1151 raise ValidationError("Invalid permission '{}'".format(role_def
))
1153 def _validate_input_new(self
, input, force
=False):
1155 Validates input user content for a new entry.
1157 :param input: user input content for the new topic
1158 :param force: may be used for being more tolerant
1159 :return: The same input content, or a changed version of it.
1162 validate_input(input, self
.schema_new
)
1163 self
.validate_role_definition(self
.operations
, input)
1167 def _validate_input_edit(self
, input, content
, force
=False):
1169 Validates input user content for updating an entry.
1171 :param input: user input content for the new topic
1172 :param force: may be used for being more tolerant
1173 :return: The same input content, or a changed version of it.
1175 if self
.schema_edit
:
1176 validate_input(input, self
.schema_edit
)
1177 self
.validate_role_definition(self
.operations
, input)
1181 def check_conflict_on_new(self
, session
, indata
):
1183 Check that the data to be inserted is valid
1185 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1186 :param indata: data to be inserted
1187 :return: None or raises EngineException
1189 # check name is not uuid
1190 role_name
= indata
.get("name")
1191 if is_valid_uuid(role_name
):
1192 raise EngineException("role name '{}' cannot have an uuid format".format(role_name
),
1193 HTTPStatus
.UNPROCESSABLE_ENTITY
)
1194 # check name not exists
1195 name
= indata
["name"]
1196 # if self.db.get_one(self.topic, {"name": indata.get("name")}, fail_on_empty=False, fail_on_more=False):
1197 if self
.auth
.get_role_list({"name": name
}):
1198 raise EngineException("role name '{}' exists".format(name
), HTTPStatus
.CONFLICT
)
1200 def check_conflict_on_edit(self
, session
, final_content
, edit_content
, _id
):
1202 Check that the data to be edited/uploaded is valid
1204 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1205 :param final_content: data once modified
1206 :param edit_content: incremental data that contains the modifications to apply
1207 :param _id: internal _id
1208 :return: None or raises EngineException
1210 if "default" not in final_content
["permissions"]:
1211 final_content
["permissions"]["default"] = False
1212 if "admin" not in final_content
["permissions"]:
1213 final_content
["permissions"]["admin"] = False
1215 # check name is not uuid
1216 role_name
= edit_content
.get("name")
1217 if is_valid_uuid(role_name
):
1218 raise EngineException("role name '{}' cannot have an uuid format".format(role_name
),
1219 HTTPStatus
.UNPROCESSABLE_ENTITY
)
1221 # Check renaming of admin roles
1222 role
= self
.auth
.get_role(_id
)
1223 if role
["name"] in ["system_admin", "project_admin"]:
1224 raise EngineException("You cannot rename role '{}'".format(role
["name"]), http_code
=HTTPStatus
.FORBIDDEN
)
1226 # check name not exists
1227 if "name" in edit_content
:
1228 role_name
= edit_content
["name"]
1229 # if self.db.get_one(self.topic, {"name":role_name,"_id.ne":_id}, fail_on_empty=False, fail_on_more=False):
1230 roles
= self
.auth
.get_role_list({"name": role_name
})
1231 if roles
and roles
[0][BaseTopic
.id_field("roles", _id
)] != _id
:
1232 raise EngineException("role name '{}' exists".format(role_name
), HTTPStatus
.CONFLICT
)
1234 return final_content
1236 def check_conflict_on_del(self
, session
, _id
, db_content
):
1238 Check if deletion can be done because of dependencies if it is not force. To override
1240 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1241 :param _id: internal _id
1242 :param db_content: The database content of this item _id
1243 :return: None if ok or raises EngineException with the conflict
1245 role
= self
.auth
.get_role(_id
)
1246 if role
["name"] in ["system_admin", "project_admin"]:
1247 raise EngineException("You cannot delete role '{}'".format(role
["name"]), http_code
=HTTPStatus
.FORBIDDEN
)
1249 # If any user is using this role, raise CONFLICT exception
1250 if not session
["force"]:
1251 for user
in self
.auth
.get_user_list():
1252 for prm
in user
.get("project_role_mappings"):
1253 if prm
["role"] == _id
:
1254 raise EngineException("Role '{}' ({}) is being used by user '{}'"
1255 .format(role
["name"], _id
, user
["username"]), HTTPStatus
.CONFLICT
)
1258 def format_on_new(content
, project_id
=None, make_public
=False): # TO BE REMOVED ?
1260 Modifies content descriptor to include _admin
1262 :param content: descriptor to be modified
1263 :param project_id: if included, it add project read/write permissions
1264 :param make_public: if included it is generated as public for reading.
1265 :return: None, but content is modified
1268 if "_admin" not in content
:
1269 content
["_admin"] = {}
1270 if not content
["_admin"].get("created"):
1271 content
["_admin"]["created"] = now
1272 content
["_admin"]["modified"] = now
1274 if "permissions" not in content
:
1275 content
["permissions"] = {}
1277 if "default" not in content
["permissions"]:
1278 content
["permissions"]["default"] = False
1279 if "admin" not in content
["permissions"]:
1280 content
["permissions"]["admin"] = False
1283 def format_on_edit(final_content
, edit_content
):
1285 Modifies final_content descriptor to include the modified date.
1287 :param final_content: final descriptor generated
1288 :param edit_content: alterations to be include
1289 :return: None, but final_content is modified
1291 if "_admin" in final_content
:
1292 final_content
["_admin"]["modified"] = time()
1294 if "permissions" not in final_content
:
1295 final_content
["permissions"] = {}
1297 if "default" not in final_content
["permissions"]:
1298 final_content
["permissions"]["default"] = False
1299 if "admin" not in final_content
["permissions"]:
1300 final_content
["permissions"]["admin"] = False
1303 def show(self
, session
, _id
, api_req
=False):
1305 Get complete information on an topic
1307 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1308 :param _id: server internal id
1309 :param api_req: True if this call is serving an external API request. False if serving internal request.
1310 :return: dictionary, raise exception if not found.
1312 filter_q
= {BaseTopic
.id_field(self
.topic
, _id
): _id
}
1313 # roles = self.auth.get_role_list(filter_q)
1314 roles
= self
.list(session
, filter_q
) # To allow default filtering (Bug 853)
1316 raise AuthconnNotFoundException("Not found any role with filter {}".format(filter_q
))
1317 elif len(roles
) > 1:
1318 raise AuthconnConflictException("Found more than one role with filter {}".format(filter_q
))
1321 def list(self
, session
, filter_q
=None, api_req
=False):
1323 Get a list of the topic that matches a filter
1325 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1326 :param filter_q: filter of data to be applied
1327 :return: The list, it can be empty if no one match the filter.
1329 role_list
= self
.auth
.get_role_list(filter_q
)
1330 if not session
["allow_show_user_project_role"]:
1331 # Bug 853 - Default filtering
1332 user
= self
.auth
.get_user(session
["username"])
1333 roles
= [prm
["role"] for prm
in user
["project_role_mappings"]]
1334 role_list
= [role
for role
in role_list
if role
["_id"] in roles
]
1337 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
1339 Creates a new entry into database.
1341 :param rollback: list to append created items at database in case a rollback may to be done
1342 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1343 :param indata: data to be inserted
1344 :param kwargs: used to override the indata descriptor
1345 :param headers: http request headers
1346 :return: _id: identity of the inserted data, operation _id (None)
1349 content
= self
._remove
_envelop
(indata
)
1351 # Override descriptor with query string kwargs
1352 self
._update
_input
_with
_kwargs
(content
, kwargs
)
1353 content
= self
._validate
_input
_new
(content
, session
["force"])
1354 self
.check_conflict_on_new(session
, content
)
1355 self
.format_on_new(content
, project_id
=session
["project_id"], make_public
=session
["public"])
1356 # role_name = content["name"]
1357 rid
= self
.auth
.create_role(content
)
1358 content
["_id"] = rid
1359 # _id = self.db.create(self.topic, content)
1360 rollback
.append({"topic": self
.topic
, "_id": rid
})
1361 # self._send_msg("created", content, not_send_msg=not_send_msg)
1363 except ValidationError
as e
:
1364 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
1366 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
1368 Delete item by its internal _id
1370 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1371 :param _id: server internal id
1372 :param dry_run: make checking but do not delete
1373 :param not_send_msg: To not send message (False) or store content (list) instead
1374 :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
1376 filter_q
= {BaseTopic
.id_field(self
.topic
, _id
): _id
}
1377 roles
= self
.auth
.get_role_list(filter_q
)
1379 raise AuthconnNotFoundException("Not found any role with filter {}".format(filter_q
))
1380 elif len(roles
) > 1:
1381 raise AuthconnConflictException("Found more than one role with filter {}".format(filter_q
))
1382 rid
= roles
[0]["_id"]
1383 self
.check_conflict_on_del(session
, rid
, None)
1384 # filter_q = {"_id": _id}
1385 # filter_q = {BaseTopic.id_field(self.topic, _id): _id} # To allow role addressing by name
1387 v
= self
.auth
.delete_role(rid
)
1388 # v = self.db.del_one(self.topic, filter_q)
1392 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1394 Updates a role entry.
1396 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1398 :param indata: data to be inserted
1399 :param kwargs: used to override the indata descriptor
1401 :return: _id: identity of the inserted data.
1404 self
._update
_input
_with
_kwargs
(indata
, kwargs
)
1407 content
= self
.show(session
, _id
)
1408 indata
= self
._validate
_input
_edit
(indata
, content
, force
=session
["force"])
1409 deep_update_rfc7396(content
, indata
)
1410 content
= self
.check_conflict_on_edit(session
, content
, indata
, _id
=_id
)
1411 self
.format_on_edit(content
, indata
)
1412 self
.auth
.update_role(content
)
1413 except ValidationError
as e
:
1414 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)