Пример #1
0
def save(api, group):
    # type (ApiClient, Group) -> Dict
    """Save or update a group (= Feed in Lumapps wording)

    Args:
        api: the ApiClient instance to use for requests
        group: the group to save, requires at least a customer and name values

    Returns:
        Lumapps Feed resource
    """
    if not group.name and not group.uid:
        raise BadRequestException("Group requires a field name or field uid")

    if not group.type:
        raise BadRequestException("Group requires a type id")

    try:
        grp = group.to_lumapps()
        logging.info("saving group to remote %s ", grp)
        saved_grp = api.get_call("feed", "save", body=grp)

        return saved_grp

    except HttpError as e:
        raise BadRequestException(
            "Error {} Group {} has not been saved correctly.".format(
                str(e), group))
Пример #2
0
    def save(self, refresh_from_remote=False):

        try:
            result = save_or_update(self._api, self)
        except BadRequestException as e:
            return None, e

        if result is None:
            raise BadRequestException("User has not been saved correctly")

        else:
            self._set_representation(result)

        total_add = len(self._groups.get("to_add"))
        total_remove = len(self._groups.get("to_remove"))

        logging.info("updating user groups %s %s", total_add, total_remove)

        try:
            added, removed = self.update_remote_groups(
                self._groups.get("to_add"), self._groups.get("to_remove"))
        except BadRequestException as e:
            return None, e
        if len(added) != total_add or len(removed) != total_remove:
            raise BadRequestException(
                "Some groups have not been updated correctly")

        if refresh_from_remote:
            self._set_representation(result, True)

        return True, None
Пример #3
0
def update_users(group, users_to_add=[], users_to_remove=[]):
    # TODO: Iterables and not lists
    # type (Group, list[User], list[User]) -> bool
    """Update the users of a group

    Args:
        group: the group to update
        users_to_add: list of users to add to the group
        users_to_remove: list of users to remove from the group

    Returns:
        whether the operation succeeded
    """
    api = group.api

    body = {
        "feed": group.uid,
        "addedUsers": [user.email for user in users_to_add],
        "removedUsers": [user.uid for user in users_to_remove],
    }
    logging.info(
        "updating users add:%s, remove:%s to remote groups %s ",
        body["addedUsers"],
        body["removedUsers"],
        body["feed"],
    )

    try:
        result = api.get_call("feed", "subscribers", "save", body=body)
    except HttpError as e:
        raise BadRequestException(
            "Error {} User {} has not been saved correctly.".format(
                str(e), user))

    return result == ""
Пример #4
0
    def set_type_by_label(self, label):
        types = get_types_by_label(self._api, self, label)

        if not types:
            raise NotFoundException("No group type found with that name or id")
        if len(types) > 1:
            raise BadRequestException(
                "Multiple group types found with that name or id")

        self._type = types[0]

        return types[0]
Пример #5
0
def save_or_update(api, user):
    # type: (ApiClient, User) ->  dict[str]
    """
    Args:
        api: the ApiClient instance to use for requests
        user: the user to save

    Returns:
        Saved user as Lumapps Resource or raise Exception if it fails
    """
    if not user.get_attribute("email"):
        raise BadRequestException("User requires an email")

    try:
        usr = user.to_lumapps_dict()
        logging.info("saving user to remote %s ", usr)
        saved_user = api.get_call("user", "save", body=usr)
        return saved_user

    except HttpError as e:
        raise BadRequestException(
            "Error {} User {} has not been saved correctly.".format(
                str(e), user))
Пример #6
0
def delete(api, group):
    # type (ApiClient, Group) -> bool
    """Delete a group by uid

    Args:
        api (str): the ApiClient instance to use for requests
        group: the group to save, requires at least a customer and uuid values

    Returns:
        whether the operation succeeded
    """

    if group.uid == None or group.uid == "":
        raise BadRequestException("Group requires a field uid to delete")

    return api.get_call("feed", "delete", uid=group.uid) == ""
Пример #7
0
    def save(self, refresh_from_remote=False):

        try:
            result = save(self._api, self)

            if result:
                logging.info("saved group uid %s", result.get("uid"))
        except BadRequestException as e:
            return None, e

        if result is None:
            raise BadRequestException("Group has not been saved correctly")

        if result and refresh_from_remote:
            self._set_representation(result, True)

        return True, None
Пример #8
0
    def new(
        api,
        customer="",
        instance="",
        name="",
        uid="",
        representation=None,
        fetch_by_name=False,
        fetch_by_id=False,
    ):
        if fetch_by_name:
            if name.isdigit():
                grp = get_by_uid(api, uid)
                logging.info("fetching groups by uid %s: %s", name, grp)
            if not grp:
                grps = get_by_name(api, name, instance)
                logging.info("fetching groups by name %s: %s", name, grps)
                if len(grps) == 1:
                    grp = grps[0]
                else:
                    raise BadRequestException("MULTIPLE_GRP_SAME_NAME")

            if grp:
                logging.info("group representation %s", grp)
                return Group(api=api, representation=grp)

        elif fetch_by_id:
            grp = get_by_uid(api, uid)
            if grp:
                return Group(api=api, representation=grp)

        return Group(
            api=api,
            instance=instance,
            customer=customer,
            name=name,
            uid=uid,
            representation=representation,
        )
Пример #9
0
    def set_attribute(self, attr, value, force=False):
        # type: (str, str | int | object, boolean) -> None
        """

        Args:
            attr (str,str): feed attribute key to save
            value (int): feed attribute value to save
            force (bool): whether to force the storage of the attribute

        """
        if attr == "status":
            value = User.STATUS.get(value, value)

        if attr == "groups":
            if value and isinstance(value, str):
                return self.set_groups({"to_add": value.split(";")})

        label = "_{}".format(attr)

        authorized_update_fields = (
            "firstName",
            "properties",
            "lastName",
            "fullName",
            "status",
            "email",
            "subscriptions",
            "groups_label",
            "uid",
            "customProfile",
        )

        if force or attr in authorized_update_fields:
            setattr(self, label, value)
        else:
            BadRequestException("attribute {} is not writable", attr)
Пример #10
0
    def set_attribute(self, attr, value, force=False):
        # type: (str, str | int | object) -> None
        """

        Args:
            attr: feed attribute key to save
            value: feed attribute value to save
        """

        authorized_update_fields = (
            "customer",
            "status",
            "group",
            "synchronized",
            "instance",
            "name",
            "uid",
        )  # ("firstname","properties","lastname","fullname")
        label = "_{}".format(attr)

        if force or attr in authorized_update_fields:
            setattr(self, label, value)
        else:
            BadRequestException("attribute {} is not writable", attr)