fix bugs 747 757: fix user-update interface for RBAC+keystone 63/7663/3
authortierno <alfonso.tiernosepulveda@telefonica.com>
Thu, 13 Jun 2019 09:06:40 +0000 (09:06 +0000)
committertierno <alfonso.tiernosepulveda@telefonica.com>
Thu, 13 Jun 2019 14:25:24 +0000 (14:25 +0000)
Change-Id: I2c3a754b7bd68fa801cc930f13762ca2585612a6
Signed-off-by: tierno <alfonso.tiernosepulveda@telefonica.com>
osm_nbi/admin_topics.py
osm_nbi/authconn.py
osm_nbi/authconn_keystone.py
osm_nbi/base_topic.py
osm_nbi/validation.py

index 9facd8b..cbe2f4c 100644 (file)
@@ -392,15 +392,18 @@ class UserTopicAuth(UserTopic):
         :return: None or raises EngineException
         """
         username = indata.get("username")
-        user_list = list(map(lambda x: x["username"], self.auth.get_user_list()))
+        if is_valid_uuid(username):
+            raise EngineException("username '{}' cannot be a uuid format".format(username),
+                                  HTTPStatus.UNPROCESSABLE_ENTITY)
+
+        # Check that username is not used, regardless keystone already checks this
+        if self.auth.get_user_list(filter_q={"name": username}):
+            raise EngineException("username '{}' is already used".format(username), HTTPStatus.CONFLICT)
 
         if "projects" in indata.keys():
-            raise EngineException("Format invalid: the keyword \"projects\" is not allowed for Keystone", 
+            raise EngineException("Format invalid: the keyword \"projects\" is not allowed for keystone authentication",
                                   HTTPStatus.BAD_REQUEST)
 
-        if username in user_list:
-            raise EngineException("username '{}' exists".format(username), HTTPStatus.CONFLICT)
-
     def check_conflict_on_edit(self, session, final_content, edit_content, _id):
         """
         Check that the data to be edited/uploaded is valid
@@ -411,17 +414,23 @@ class UserTopicAuth(UserTopic):
         :param _id: internal _id
         :return: None or raises EngineException
         """
-        users = self.auth.get_user_list()
-        admin_user = [user for user in users if user["username"] == "admin"][0]
 
-        if _id == admin_user["_id"] and "project_role_mappings" in edit_content.keys():
-            elem = {
-                "project": "admin",
-                "role": "system_admin"
-            }
-            if elem not in edit_content:
-                raise EngineException("You cannot remove system_admin role from admin user",
-                                      http_code=HTTPStatus.FORBIDDEN)
+        if "username" in edit_content:
+            username = edit_content.get("username")
+            if is_valid_uuid(username):
+                raise EngineException("username '{}' cannot be an uuid format".format(username),
+                                      HTTPStatus.UNPROCESSABLE_ENTITY)
+
+            # Check that username is not used, regardless keystone already checks this
+            if self.auth.get_user_list(filter_q={"name": username}):
+                raise EngineException("username '{}' is already used".format(username), HTTPStatus.CONFLICT)
+
+        if final_content["username"] == "admin":
+            for mapping in edit_content.get("remove_project_role_mappings", ()):
+                if mapping["project"] == "admin" and mapping.get("role") in (None, "system_admin"):
+                    # TODO make this also available for project id and role id
+                    raise EngineException("You cannot remove system_admin role from admin user",
+                                          http_code=HTTPStatus.FORBIDDEN)
 
     def check_conflict_on_del(self, session, _id, db_content):
         """
@@ -431,42 +440,42 @@ class UserTopicAuth(UserTopic):
         :param db_content: The database content of this item _id
         :return: None if ok or raises EngineException with the conflict
         """
-        if _id == session["username"]:
-            raise EngineException("You cannot delete your own user", http_code=HTTPStatus.CONFLICT)
-
-    @staticmethod
-    def format_on_new(content, project_id=None, make_public=False):
-        """
-        Modifies content descriptor to include _id.
-
-        NOTE: No password salt required because the authentication backend
-        should handle these security concerns.
-
-        :param content: descriptor to be modified
-        :param make_public: if included it is generated as public for reading.
-        :return: None, but content is modified
-        """
-        BaseTopic.format_on_new(content, make_public=False)
-        content["_id"] = content["username"]
-        content["password"] = content["password"]
-
-    @staticmethod
-    def format_on_edit(final_content, edit_content):
-        """
-        Modifies final_content descriptor to include the modified date.
-
-        NOTE: No password salt required because the authentication backend
-        should handle these security concerns.
-
-        :param final_content: final descriptor generated
-        :param edit_content: alterations to be include
-        :return: None, but final_content is modified
-        """
-        BaseTopic.format_on_edit(final_content, edit_content)
-        if "password" in edit_content:
-            final_content["password"] = edit_content["password"]
-        else:
-            final_content["project_role_mappings"] = edit_content["project_role_mappings"]
+        if db_content["username"] == session["username"]:
+            raise EngineException("You cannot delete your own login user ", http_code=HTTPStatus.CONFLICT)
+
+    @staticmethod
+    def format_on_new(content, project_id=None, make_public=False):
+        """
+        Modifies content descriptor to include _id.
+    #
+        NOTE: No password salt required because the authentication backend
+        should handle these security concerns.
+    #
+        :param content: descriptor to be modified
+        :param make_public: if included it is generated as public for reading.
+        :return: None, but content is modified
+        """
+        BaseTopic.format_on_new(content, make_public=False)
+        content["_id"] = content["username"]
+        content["password"] = content["password"]
+
+    @staticmethod
+    def format_on_edit(final_content, edit_content):
+        """
+        Modifies final_content descriptor to include the modified date.
+    #
+        NOTE: No password salt required because the authentication backend
+        should handle these security concerns.
+    #
+        :param final_content: final descriptor generated
+        :param edit_content: alterations to be include
+        :return: None, but final_content is modified
+        """
+        BaseTopic.format_on_edit(final_content, edit_content)
+        if "password" in edit_content:
+            final_content["password"] = edit_content["password"]
+        else:
+            final_content["project_role_mappings"] = edit_content["project_role_mappings"]
 
     @staticmethod
     def format_on_show(content):
@@ -478,7 +487,10 @@ class UserTopicAuth(UserTopic):
 
         for project in content["projects"]:
             for role in project["roles"]:
-                project_role_mappings.append({"project": project["_id"], "role": role["_id"]})
+                project_role_mappings.append({"project": project["_id"],
+                                              "project_name": project["name"],
+                                              "role": role["_id"],
+                                              "role_name": role["name"]})
 
         del content["projects"]
         content["project_role_mappings"] = project_role_mappings
@@ -505,7 +517,7 @@ class UserTopicAuth(UserTopic):
             BaseTopic._update_input_with_kwargs(content, kwargs)
             content = self._validate_input_new(content, session["force"])
             self.check_conflict_on_new(session, content)
-            self.format_on_new(content, session["project_id"], make_public=session["public"])
+            self.format_on_new(content, session["project_id"], make_public=session["public"])
             _id = self.auth.create_user(content["username"], content["password"])["_id"]
 
             if "project_role_mappings" in content.keys():
@@ -513,7 +525,7 @@ class UserTopicAuth(UserTopic):
                     self.auth.assign_role_to_user(_id, mapping["project"], mapping["role"])
 
             rollback.append({"topic": self.topic, "_id": _id})
-            del content["password"]
+            del content["password"]
             # self._send_msg("create", content)
             return _id
         except ValidationError as e:
@@ -527,7 +539,9 @@ class UserTopicAuth(UserTopic):
         :param _id: server internal id
         :return: dictionary, raise exception if not found.
         """
-        users = [user for user in self.auth.get_user_list() if user["_id"] == _id]
+        # Allow _id to be a name or uuid
+        filter_q = {self.id_field(self.topic, _id): _id}
+        users = self.auth.get_user_list(filter_q)
 
         if len(users) == 1:
             return self.format_on_show(users[0])
@@ -558,36 +572,80 @@ class UserTopicAuth(UserTopic):
             if not content:
                 content = self.show(session, _id)
             self.check_conflict_on_edit(session, content, indata, _id=_id)
-            self.format_on_edit(content, indata)
-
-            if "password" in content:
-                self.auth.change_password(content["username"], content["password"])
-            else:
-                user = self.show(session, _id)
-                original_mapping = user["project_role_mappings"]
-                edit_mapping = content["project_role_mappings"]
-
-                mappings_to_remove = [mapping for mapping in original_mapping
-                                      if mapping not in edit_mapping]
-
-                mappings_to_add = [mapping for mapping in edit_mapping
-                                   if mapping not in original_mapping]
-
-                for mapping in mappings_to_remove:
-                    self.auth.remove_role_from_user(
-                        _id,
-                        mapping["project"],
-                        mapping["role"]
-                    )
-
-                for mapping in mappings_to_add:
-                    self.auth.assign_role_to_user(
-                        _id,
-                        mapping["project"],
-                        mapping["role"]
-                    )
-
-            return content["_id"]
+            # self.format_on_edit(content, indata)
+
+            if "password" in indata or "username" in indata:
+                self.auth.update_user(_id, new_name=indata.get("username"), new_password=indata.get("password"))
+            if not indata.get("remove_project_role_mappings") and not indata.get("add_project_role_mappings") and \
+                    not indata.get("project_role_mappings"):
+                return _id
+            if indata.get("project_role_mappings") and \
+                    (indata.get("remove_project_role_mappings") or indata.get("add_project_role_mappings")):
+                raise EngineException("Option 'project_role_mappings' is incompatible with 'add_project_role_mappings"
+                                      "' or 'remove_project_role_mappings'", http_code=HTTPStatus.BAD_REQUEST)
+
+            user = self.show(session, _id)
+            original_mapping = user["project_role_mappings"]
+
+            mappings_to_add = []
+            mappings_to_remove = []
+
+            # remove
+            for to_remove in indata.get("remove_project_role_mappings", ()):
+                for mapping in original_mapping:
+                    if to_remove["project"] in (mapping["project"], mapping["project_name"]):
+                        if not to_remove.get("role") or to_remove["role"] in (mapping["role"], mapping["role_name"]):
+                            mappings_to_remove.append(mapping)
+
+            # add
+            for to_add in indata.get("add_project_role_mappings", ()):
+                for mapping in original_mapping:
+                    if to_add["project"] in (mapping["project"], mapping["project_name"]) and \
+                            to_add["role"] in (mapping["role"], mapping["role_name"]):
+
+                        if mapping in mappings_to_remove:   # do not remove
+                            mappings_to_remove.remove(mapping)
+                        break  # do not add, it is already at user
+                else:
+                    mappings_to_add.append(to_add)
+
+            # set
+            if indata.get("project_role_mappings"):
+                for to_set in indata["project_role_mappings"]:
+                    for mapping in original_mapping:
+                        if to_set["project"] in (mapping["project"], mapping["project_name"]) and \
+                                to_set["role"] in (mapping["role"], mapping["role_name"]):
+
+                            if mapping in mappings_to_remove:   # do not remove
+                                mappings_to_remove.remove(mapping)
+                            break  # do not add, it is already at user
+                    else:
+                        mappings_to_add.append(to_set)
+                for mapping in original_mapping:
+                    for to_set in indata["project_role_mappings"]:
+                        if to_set["project"] in (mapping["project"], mapping["project_name"]) and \
+                                to_set["role"] in (mapping["role"], mapping["role_name"]):
+                            break
+                    else:
+                        # delete
+                        if mapping not in mappings_to_remove:   # do not remove
+                            mappings_to_remove.append(mapping)
+
+            for mapping in mappings_to_remove:
+                self.auth.remove_role_from_user(
+                    _id,
+                    mapping["project"],
+                    mapping["role"]
+                )
+
+            for mapping in mappings_to_add:
+                self.auth.assign_role_to_user(
+                    _id,
+                    mapping["project"],
+                    mapping["role"]
+                )
+
+            return "_id"
         except ValidationError as e:
             raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
 
@@ -598,9 +656,6 @@ class UserTopicAuth(UserTopic):
         :param filter_q: filter of data to be applied
         :return: The list, it can be empty if no one match the filter.
         """
-        if not filter_q:
-            filter_q = {}
-
         users = [self.format_on_show(user) for user in self.auth.get_user_list(filter_q)]
 
         return users
@@ -615,7 +670,13 @@ class UserTopicAuth(UserTopic):
         :param dry_run: make checking but do not delete
         :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
         """
-        self.check_conflict_on_del(session, _id, None)
+        # Allow _id to be a name or uuid
+        filter_q = {self.id_field(self.topic, _id): _id}
+        user_list = self.auth.get_user_list(filter_q)
+        if not user_list:
+            raise EngineException("User '{}' not found".format(_id), http_code=HTTPStatus.NOT_FOUND)
+        _id = user_list[0]["_id"]
+        self.check_conflict_on_del(session, _id, user_list[0])
         if not dry_run:
             v = self.auth.delete_user(_id)
             return v
@@ -640,11 +701,36 @@ class ProjectTopicAuth(ProjectTopic):
         :param indata: data to be inserted
         :return: None or raises EngineException
         """
-        project = indata.get("name")
-        project_list = list(map(lambda x: x["name"], self.auth.get_project_list()))
+        project_name = indata.get("name")
+        if is_valid_uuid(project_name):
+            raise EngineException("project name '{}' cannot be an uuid format".format(project_name),
+                                  HTTPStatus.UNPROCESSABLE_ENTITY)
+
+        project_list = self.auth.get_project_list(filter_q={"name": project_name})
 
-        if project in project_list:
-            raise EngineException("project '{}' exists".format(project), HTTPStatus.CONFLICT)
+        if project_list:
+            raise EngineException("project '{}' exists".format(project_name), HTTPStatus.CONFLICT)
+
+    def check_conflict_on_edit(self, session, final_content, edit_content, _id):
+        """
+        Check that the data to be edited/uploaded is valid
+
+        :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
+        :param final_content: data once modified
+        :param edit_content: incremental data that contains the modifications to apply
+        :param _id: internal _id
+        :return: None or raises EngineException
+        """
+
+        project_name = edit_content.get("name")
+        if project_name:
+            if is_valid_uuid(project_name):
+                raise EngineException("project name  '{}' cannot be an uuid format".format(project_name),
+                                      HTTPStatus.UNPROCESSABLE_ENTITY)
+
+            # Check that project name is not used, regardless keystone already checks this
+            if self.auth.get_project_list(filter_q={"name": project_name}):
+                raise EngineException("project '{}' is already used".format(project_name), HTTPStatus.CONFLICT)
 
     def check_conflict_on_del(self, session, _id, db_content):
         """
@@ -658,7 +744,7 @@ class ProjectTopicAuth(ProjectTopic):
         # projects = self.auth.get_project_list()
         # current_project = [project for project in projects
         #                    if project["name"] in session["project_id"]][0]
-
+        # TODO check that any user is using this project, raise CONFLICT exception
         if _id == session["project_id"]:
             raise EngineException("You cannot delete your own project", http_code=HTTPStatus.CONFLICT)
 
@@ -698,7 +784,9 @@ class ProjectTopicAuth(ProjectTopic):
         :param _id: server internal id
         :return: dictionary, raise exception if not found.
         """
-        projects = [project for project in self.auth.get_project_list() if project["_id"] == _id]
+        # Allow _id to be a name or uuid
+        filter_q = {self.id_field(self.topic, _id): _id}
+        projects = self.auth.get_project_list(filter_q=filter_q)
 
         if len(projects) == 1:
             return projects[0]
@@ -715,9 +803,6 @@ class ProjectTopicAuth(ProjectTopic):
         :param filter_q: filter of data to be applied
         :return: The list, it can be empty if no one match the filter.
         """
-        if not filter_q:
-            filter_q = {}
-
         return self.auth.get_project_list(filter_q)
 
     def delete(self, session, _id, dry_run=False):
@@ -729,7 +814,13 @@ class ProjectTopicAuth(ProjectTopic):
         :param dry_run: make checking but do not delete
         :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
         """
-        self.check_conflict_on_del(session, _id, None)
+        # Allow _id to be a name or uuid
+        filter_q = {self.id_field(self.topic, _id): _id}
+        project_list = self.auth.get_project_list(filter_q)
+        if not project_list:
+            raise EngineException("Project '{}' not found".format(_id), http_code=HTTPStatus.NOT_FOUND)
+        _id = project_list[0]["_id"]
+        self.check_conflict_on_del(session, _id, project_list[0])
         if not dry_run:
             v = self.auth.delete_project(_id)
             return v
@@ -757,7 +848,7 @@ class ProjectTopicAuth(ProjectTopic):
             if not content:
                 content = self.show(session, _id)
             self.check_conflict_on_edit(session, content, indata, _id=_id)
-            self.format_on_edit(content, indata)
+            self.format_on_edit(content, indata)
 
             if "name" in indata:
                 self.auth.update_project(content["_id"], indata["name"])
index 2780d59..42707fe 100644 (file)
@@ -79,6 +79,14 @@ class AuthconnOperationException(AuthconnException):
         super(AuthconnOperationException, self).__init__(message, http_code)
 
 
+class AuthconnNotFoundException(AuthconnException):
+    """
+    The operation executed failed because element not found.
+    """
+    def __init__(self, message, http_code=HTTPStatus.NOT_FOUND):
+        super().__init__(message, http_code)
+
+
 class Authconn:
     """
     Abstract base class for all the Auth backend connector plugins.
@@ -172,13 +180,14 @@ class Authconn:
         """
         raise AuthconnNotImplementedException("Should have implemented this")
 
-    def change_password(self, user, new_password):
+    def update_user(self, user, new_name=None, new_password=None):
         """
-        Change the user password.
+        Change the user name and/or password.
 
-        :param user: username.
+        :param user: username or user_id
+        :param new_name: new name
         :param new_password: new password.
-        :raises AuthconnOperationException: if user password change failed.
+        :raises AuthconnOperationException: if change failed.
         """
         raise AuthconnNotImplementedException("Should have implemented this")
 
@@ -191,11 +200,11 @@ class Authconn:
         """
         raise AuthconnNotImplementedException("Should have implemented this")
 
-    def get_user_list(self, filter_q={}):
+    def get_user_list(self, filter_q=None):
         """
         Get user list.
 
-        :param filter_q: dictionary to filter user list.
+        :param filter_q: dictionary to filter user list by name (username is also admited) and/or _id
         :return: returns a list of users.
         """
 
index ff54130..bb69381 100644 (file)
@@ -28,7 +28,7 @@ it for OSM.
 __author__ = "Eduardo Sousa <esousa@whitestack.com>"
 __date__ = "$27-jul-2018 23:59:59$"
 
-from authconn import Authconn, AuthException, AuthconnOperationException
+from authconn import Authconn, AuthException, AuthconnOperationException, AuthconnNotFoundException
 
 import logging
 import requests
@@ -268,24 +268,35 @@ class AuthconnKeystone(Authconn):
         try:
             new_user = self.keystone.users.create(user, password=password, domain=self.user_domain_name)
             return {"username": new_user.name, "_id": new_user.id}
+        except Conflict as e:
+            # self.logger.exception("Error during user creation using keystone: {}".format(e))
+            raise AuthconnOperationException(e, http_code=HTTPStatus.CONFLICT)
         except ClientException as e:
             self.logger.exception("Error during user creation using keystone: {}".format(e))
             raise AuthconnOperationException("Error during user creation using Keystone: {}".format(e))
 
-    def change_password(self, user, new_password):
+    def update_user(self, user, new_name=None, new_password=None):
         """
-        Change the user password.
+        Change the user name and/or password.
 
-        :param user: username.
+        :param user: username or user_id
+        :param new_name: new name
         :param new_password: new password.
-        :raises AuthconnOperationException: if user password change failed.
+        :raises AuthconnOperationException: if change failed.
         """
         try:
-            user_obj = list(filter(lambda x: x.name == user, self.keystone.users.list()))[0]
-            self.keystone.users.update(user_obj, password=new_password)
+            if is_valid_uuid(user):
+                user_id = user
+            else:
+                user_obj_list = self.keystone.users.list(name=user)
+                if not user_obj_list:
+                    raise AuthconnNotFoundException("User '{}' not found".format(user))
+                user_id = user_obj_list[0].id
+
+            self.keystone.users.update(user_id, password=new_password, name=new_name)
         except ClientException as e:
-            self.logger.exception("Error during user password update using keystone: {}".format(e))
-            raise AuthconnOperationException("Error during user password update using Keystone: {}".format(e))
+            self.logger.exception("Error during user password/name update using keystone: {}".format(e))
+            raise AuthconnOperationException("Error during user password/name update using Keystone: {}".format(e))
 
     def delete_user(self, user_id):
         """
@@ -308,28 +319,26 @@ class AuthconnKeystone(Authconn):
             self.logger.exception("Error during user deletion using keystone: {}".format(e))
             raise AuthconnOperationException("Error during user deletion using Keystone: {}".format(e))
 
-    def get_user_list(self, filter_q={}):
+    def get_user_list(self, filter_q=None):
         """
         Get user list.
 
-        :param filter_q: dictionary to filter user list.
+        :param filter_q: dictionary to filter user list by name (username is also admited) and/or _id
         :return: returns a list of users.
         """
         try:
-            users = self.keystone.users.list()
+            filter_name = None
+            if filter_q:
+                filter_name = filter_q.get("name") or filter_q.get("username")
+            users = self.keystone.users.list(name=filter_name)
             users = [{
                 "username": user.name,
                 "_id": user.id,
                 "id": user.id
             } for user in users if user.name != self.admin_username]
 
-            allowed_fields = ["_id", "id", "username"]
-            for key in filter_q.keys():
-                if key not in allowed_fields:
-                    continue
-
-                users = [user for user in users 
-                         if filter_q[key] == user[key]]
+            if filter_q and filter_q.get("_id"):
+                users = [user for user in users if filter_q["_id"] == user["_id"]]
 
             for user in users:
                 projects = self.keystone.projects.list(user=user["_id"])
@@ -501,38 +510,70 @@ class AuthconnKeystone(Authconn):
             if is_valid_uuid(user):
                 user_obj = self.keystone.users.get(user)
             else:
-                user_obj = self.keystone.users.list(name=user)[0]
+                user_obj_list = self.keystone.users.list(name=user)
+                if not user_obj_list:
+                    raise AuthconnNotFoundException("User '{}' not found".format(user))
+                user_obj = user_obj_list[0]
 
             if is_valid_uuid(project):
                 project_obj = self.keystone.projects.get(project)
             else:
-                project_obj = self.keystone.projects.list(name=project)[0]
+                project_obj_list = self.keystone.projects.list(name=project)
+                if not project_obj_list:
+                    raise AuthconnNotFoundException("Project '{}' not found".format(project))
+                project_obj = project_obj_list[0]
 
             if is_valid_uuid(role):
                 role_obj = self.keystone.roles.get(role)
             else:
-                role_obj = self.keystone.roles.list(name=role)[0]
+                role_obj_list = self.keystone.roles.list(name=role)
+                if not role_obj_list:
+                    raise AuthconnNotFoundException("Role '{}' not found".format(role))
+                role_obj = role_obj_list[0]
 
             self.keystone.roles.grant(role_obj, user=user_obj, project=project_obj)
         except ClientException as e:
             self.logger.exception("Error during user role assignment using keystone: {}".format(e))
-            raise AuthconnOperationException("Error during user role assignment using Keystone: {}".format(e))
+            raise AuthconnOperationException("Error during role '{}' assignment to user '{}' and project '{}' using "
+                                             "Keystone: {}".format(role, user, project, e))
 
     def remove_role_from_user(self, user, project, role):
         """
         Remove a role from a user in a project.
 
         :param user: username.
-        :param project: project name.
-        :param role: role name.
+        :param project: project name or id.
+        :param role: role name or id.
+
         :raises AuthconnOperationException: if role assignment revocation failed.
         """
         try:
-            user_obj = list(filter(lambda x: x.name == user, self.keystone.users.list()))[0]
-            project_obj = list(filter(lambda x: x.name == project, self.keystone.projects.list()))[0]
-            role_obj = list(filter(lambda x: x.name == role, self.keystone.roles.list()))[0]
+            if is_valid_uuid(user):
+                user_obj = self.keystone.users.get(user)
+            else:
+                user_obj_list = self.keystone.users.list(name=user)
+                if not user_obj_list:
+                    raise AuthconnNotFoundException("User '{}' not found".format(user))
+                user_obj = user_obj_list[0]
+
+            if is_valid_uuid(project):
+                project_obj = self.keystone.projects.get(project)
+            else:
+                project_obj_list = self.keystone.projects.list(name=project)
+                if not project_obj_list:
+                    raise AuthconnNotFoundException("Project '{}' not found".format(project))
+                project_obj = project_obj_list[0]
+
+            if is_valid_uuid(role):
+                role_obj = self.keystone.roles.get(role)
+            else:
+                role_obj_list = self.keystone.roles.list(name=role)
+                if not role_obj_list:
+                    raise AuthconnNotFoundException("Role '{}' not found".format(role))
+                role_obj = role_obj_list[0]
 
             self.keystone.roles.revoke(role_obj, user=user_obj, project=project_obj)
         except ClientException as e:
             self.logger.exception("Error during user role revocation using keystone: {}".format(e))
-            raise AuthconnOperationException("Error during user role revocation using Keystone: {}".format(e))
+            raise AuthconnOperationException("Error during role '{}' revocation to user '{}' and project '{}' using "
+                                             "Keystone: {}".format(role, user, project, e))
index c953a05..7c6c990 100644 (file)
@@ -60,7 +60,8 @@ class BaseTopic:
     # Alternative ID Fields for some Topics
     alt_id_field = {
         "projects": "name",
-        "users": "username"
+        "users": "username",
+        "roles": "name"
     }
 
     def __init__(self, db, fs, msg):
index a244ac1..a081ffa 100644 (file)
@@ -566,16 +566,35 @@ pdu_edit_schema = {
 }
 
 # USERS
-project_role_mapping = {
-    "title": "",
+project_role_mappings = {
+    "title": "list pf projects/roles",
     "$schema": "http://json-schema.org/draft-04/schema#",
-    "type": "object",
-    "properties": {
-        "project": shortname_schema,
-        "role": shortname_schema
+    "type": "array",
+    "items": {
+        "type": "object",
+        "properties": {
+            "project": shortname_schema,
+            "role": shortname_schema
+        },
+        "required": ["project", "role"],
+        "additionalProperties": False
     },
-    "required": ["project", "role"],
-    "additionalProperties": False
+    "minItems": 1
+}
+project_role_mappings_optional = {
+    "title": "list of projects/roles or projects only",
+    "$schema": "http://json-schema.org/draft-04/schema#",
+    "type": "array",
+    "items": {
+        "type": "object",
+        "properties": {
+            "project": shortname_schema,
+            "role": shortname_schema
+        },
+        "required": ["project"],
+        "additionalProperties": False
+    },
+    "minItems": 1
 }
 user_new_schema = {
     "$schema": "http://json-schema.org/draft-04/schema#",
@@ -585,11 +604,7 @@ user_new_schema = {
         "username": shortname_schema,
         "password": passwd_schema,
         "projects": nameshort_list_schema,
-        "project_role_mappings": {
-            "type": "array",
-            "items": project_role_mapping,
-            "minItems": 1
-        },
+        "project_role_mappings": project_role_mappings,
     },
     "required": ["username", "password"],
     "additionalProperties": False
@@ -607,11 +622,9 @@ user_edit_schema = {
                 array_edition_schema
             ]
         },
-        "project_role_mappings": {
-            "type": "array",
-            "items": project_role_mapping,
-            "minItems": 1
-        },
+        "project_role_mappings": project_role_mappings,
+        "add_project_role_mappings": project_role_mappings,
+        "remove_project_role_mappings": project_role_mappings_optional,
     },
     "minProperties": 1,
     "additionalProperties": False