Exemplo n.º 1
0
    def grant_privilege(
        self, privilege: Union[Union["Privilege", int, str],
                               List[Union["Privilege", int, str]]]
    ) -> None:
        """Grant new project-level privileges to the Security Role.

        Args:
            privilege: list of privilege objects, ids or names
        """
        # get all project level privileges
        from mstrio.access_and_security.privilege import Privilege
        project_level = [
            priv['id'] for priv in Privilege.list_privileges(
                self.connection,
                to_dictionary=True,
                is_project_level_privilege='True')
        ]

        # validate and filter passed privileges
        privileges = Privilege._validate_privileges(self.connection, privilege)
        server_level = list({priv['id']
                             for priv in privileges} - set(project_level))
        privileges = helper.filter_list_of_dicts(privileges, id=project_level)

        # create lists for print purposes
        privilege_ids = [priv['id'] for priv in privileges]
        existing_ids = [obj['id'] for obj in self.privileges]
        succeeded = list(set(privilege_ids) - set(existing_ids))
        failed = list(set(existing_ids).intersection(set(privilege_ids)))

        if server_level:
            msg = (
                "Privileges {} are server-level and will be omitted. Only project-level "
                "privileges can be granted by this method.").format(
                    sorted(server_level))
            helper.exception_handler(msg, exception_type=Warning)

        self._update_nested_properties(
            objects=privileges,
            path="privileges",
            op="addElement",
        )
        if succeeded:
            self.fetch(
            )  # fetch the object properties and set object attributes
            if config.verbose:
                logger.info(
                    f"Granted privilege(s) {succeeded} to '{self.name}'")
        if failed and config.verbose:
            logger.warning(
                f"Security Role '{self.name}' already has privilege(s) {failed}"
            )
Exemplo n.º 2
0
    def create(cls,
               connection: Connection,
               name: str,
               privileges: Union[Union["Privilege", int, str],
                                 List[Union["Privilege", int, str]]],
               description: str = ""):
        """Create a new Security Role.

        Args:
            connection(object): MicroStrategy connection object returned
                by 'connection.Connection()'.
            name(string): Name of the Security Role
            privileges: List of privileges which will be assigned to this
                security role. Use privilege IDs or Privilege objects.
            description(string, optional): Description of the Security Role

        Returns:
            Newly created Security Role if the HTTP server has successfully
                created the Security Role.
        """
        # get all project level privileges
        from mstrio.access_and_security.privilege import Privilege
        project_level = [
            priv['id'] for priv in Privilege.list_privileges(
                connection,
                to_dictionary=True,
                is_project_level_privilege='True')
        ]

        # validate and filter passed privileges
        privileges = Privilege._validate_privileges(connection, privileges)
        server_level = list({priv['id']
                             for priv in privileges} - set(project_level))
        privileges = helper.filter_list_of_dicts(privileges, id=project_level)

        body = {
            "name": name,
            "description": description,
            "privileges": privileges
        }

        response = security.create_security_role(connection, body)
        if response.ok:
            if server_level:
                msg = (
                    "Privileges {} are server-level and will be omitted. Only project-level "
                    "privileges can be granted by this method.").format(
                        sorted(server_level))
                helper.exception_handler(msg, exception_type=Warning)
            return cls(connection=connection, id=response.json()['id'])
Exemplo n.º 3
0
    def revoke_privilege(
        self, privilege: Union[str, List[str], "Privilege",
                               List["Privilege"]]) -> None:
        """Revoke project-level privileges from the Security Role.

        Args:
            privilege: list of privilege objects, ids or names
        """
        # get all project level privileges
        from mstrio.access_and_security.privilege import Privilege
        project_level = [
            priv['id'] for priv in Privilege.list_privileges(
                self.connection,
                to_dictionary=True,
                is_project_level_privilege='True')
        ]

        # validate and filter passed privileges
        privileges = Privilege._validate_privileges(self.connection, privilege)
        server_level = list(
            set([priv['id'] for priv in privileges]) - set(project_level))
        privileges = helper.filter_list_of_dicts(privileges, id=project_level)

        # create lists for print purposes
        privilege_ids = [priv['id'] for priv in privileges]
        existing_ids = [obj['id'] for obj in self.privileges]
        succeeded = list(set(privilege_ids).intersection(set(existing_ids)))
        failed = list(set(privilege_ids) - set(succeeded))

        if server_level:
            msg = (
                "Privilege(s) {} are server-level and will be ommited. Only project-level "
                "privileges can be granted by this method.").format(
                    sorted(server_level))
            helper.exception_handler(msg, exception_type=Warning)

        self._update_nested_properties(objects=privileges,
                                       path="privileges",
                                       op="removeElement")
        if succeeded:
            self.fetch(
            )  # fetch the object properties and set object attributes
            if config.verbose:
                print("Revoked privilege(s) {} from '{}'".format(
                    succeeded, self.name))
        elif failed and config.verbose:
            print("Security Role '{}' does not have privilege(s) {}".format(
                self.name, failed))
Exemplo n.º 4
0
    def grant_privilege(
        self, privilege: Union[str, List[str], "Privilege",
                               List["Privilege"]]) -> None:
        """Grant privileges directly to the user.

        Args:
            privilege: list of privilege objects, ids or names
        """
        from mstrio.access_and_security.privilege import Privilege
        privileges = [
            priv['id'] for priv in Privilege._validate_privileges(
                self.connection, privilege)
        ]
        existing_ids = [
            privilege['privilege']['id']
            for privilege in self.list_privileges(mode='GRANTED')
        ]
        succeeded, failed = self._update_nested_properties(
            privileges, "privileges", "add", existing_ids)

        if succeeded:
            self.fetch(
                'privileges'
            )  # fetch the object properties and set object attributes
            if config.verbose:
                print("Granted privilege(s) {} to '{}'".format(
                    succeeded, self.name))
        if failed and config.verbose:
            print("User '{}' already has privilege(s) {}".format(
                self.name, failed))
Exemplo n.º 5
0
    def revoke_all_privileges(self, force: bool = False) -> None:
        """Revoke all granted project-level privileges.

        Args:
            force(bool, optional): If true, overrides the prompt.
        """
        user_input = 'N'
        if not force:
            user_input = input(
                "Are you sure you want to revoke all privileges from Security Role '{}'? [Y/N]: "
                .format(self.name))
        if force or user_input == 'Y':
            from mstrio.access_and_security.privilege import Privilege
            project_level = [
                priv['id'] for priv in Privilege.list_privileges(
                    self.connection,
                    to_dictionary=True,
                    is_project_level_privilege='True')
            ]
            existing_ids = [obj['id'] for obj in self.privileges]
            to_revoke = list(
                set(project_level).intersection(set(existing_ids)))
            if to_revoke:
                self.revoke_privilege(privilege=to_revoke)
            else:
                print(
                    "Security Role '{}' does not have any privilege(s)".format(
                        self.name))
Exemplo n.º 6
0
    def grant_privilege(
        self, privilege: Union[str, List[str], "Privilege",
                               List["Privilege"]]) -> None:
        """Grant privileges directly to the User Group.

        Args:
            privilege: List of privilege objects, ids or names
        """
        from mstrio.access_and_security.privilege import Privilege
        privileges = [
            priv['id'] for priv in Privilege._validate_privileges(
                self.connection, privilege)
        ]
        existing_ids = [
            privilege['privilege']['id']
            for privilege in self.list_privileges(mode='GRANTED')
        ]
        succeeded, failed = self._update_nested_properties(
            privileges, "privileges", "add", existing_ids)

        if succeeded:
            self.fetch('privileges')  # fetch the object privileges
            if config.verbose:
                logger.info(
                    f"Granted privilege(s) {succeeded} to '{self.name}'")
        if failed and config.verbose:
            logger.warning(
                f"User Group '{self.name}' already has privilege(s) {failed}")
Exemplo n.º 7
0
    def revoke_privilege(self, privilege: Union[str, List[str], "Privilege",
                                                List["Privilege"]]) -> None:
        """Revoke directly granted User Group privileges.

        Args:
            privilege: List of privilege objects, ids or names
        """
        from mstrio.access_and_security.privilege import Privilege
        privileges = set(
            [priv['id'] for priv in Privilege._validate_privileges(self.connection, privilege)])
        existing_ids = [
            privilege['privilege']['id'] for privilege in self.list_privileges(mode='ALL')
        ]
        directly_granted = set(
            [privilege['privilege']['id'] for privilege in self.list_privileges(mode='GRANTED')])
        to_revoke = list(privileges.intersection(directly_granted))
        not_directly_granted = list(
            (set(existing_ids) - directly_granted).intersection(privileges))

        if not_directly_granted:
            msg = (f"Privileges {sorted(not_directly_granted)} are inherited and will be "
                   "ommited. Only directly granted privileges can be revoked by this method.")
            helper.exception_handler(msg, exception_type=Warning)

        succeeded, failed = self._update_nested_properties(to_revoke, "privileges", "remove",
                                                           existing_ids)
        if succeeded:
            self.fetch('privileges')  # fetch the object privileges
            if config.verbose:
                print("Revoked privilege(s) {} from '{}'".format(succeeded, self.name))
        if failed and config.verbose:
            print("User group '{}' does not have privilege(s) {}".format(self.name, failed))
Exemplo n.º 8
0
    def revoke_privilege(
        self, privilege: Union[str, List[str], "Privilege",
                               List["Privilege"]]) -> None:
        """Revoke directly granted user privileges.

        Args:
            privilege: list of privilege objects, ids or names
        """
        from mstrio.access_and_security.privilege import Privilege
        privileges = {
            priv['id']
            for priv in Privilege._validate_privileges(self.connection,
                                                       privilege)
        }
        existing_ids = [
            privilege['privilege']['id']
            for privilege in self.list_privileges(mode='ALL')
        ]
        directly_granted = {
            privilege['privilege']['id']
            for privilege in self.list_privileges(mode='GRANTED')
        }
        to_revoke = list(privileges.intersection(directly_granted))
        not_directly_granted = list(
            (set(existing_ids) - directly_granted).intersection(privileges))

        if not_directly_granted:
            msg = (
                f"Privileges {sorted(not_directly_granted)} are inherited and will be omitted. "
                "Only directly granted privileges can be revoked by this method."
            )
            helper.exception_handler(msg, exception_type=Warning)

        succeeded, failed = self._update_nested_properties(
            to_revoke, "privileges", "remove", existing_ids)
        if succeeded:
            self.fetch(
                'privileges'
            )  # fetch the object properties and set object attributes
            if config.verbose:
                logger.info(
                    f"Revoked privilege(s) {succeeded} from '{self.name}'")
        if failed and config.verbose:
            logger.warning(
                f"User '{self.name}' does not have privilege(s) {failed}")
Exemplo n.º 9
0
# Create connection to the target environment
target_base_url = "https://<>/MicroStrategyLibrary/api"
target_username = "******"
target_password = "******"
target_conn = Connection(target_base_url,
                         target_username,
                         target_password,
                         project_name="MicroStrategy Tutorial",
                         login_mode=1)

# Make sure the current user have the following privileges:
#   'Create package', id: 295
#   'Apply package',  id: 296
# They can be granted by admin with the following commands:
user = User(source_conn, username='******')
Privilege(source_conn, id=295).add_to_user(user)
Privilege(source_conn, id=296).add_to_user(user)

# Or by name:
user2 = User(target_conn, username='******')
Privilege(target_conn, name='Create package').add_to_user(user2)
Privilege(target_conn, name='Apply package').add_to_user(user2)

# Create PackageConfig with information what object should be migrated and how.
# The options are of type Enum with all possible values listed.
dossier_id = 'some dossier id'
report_id = 'some report id'

package_settings = PackageSettings(
    PackageSettings.DefaultAction.USE_EXISTING,
    PackageSettings.UpdateSchema.RECAL_TABLE_LOGICAL_SIZE,