Example #1
0
    def __init__(self, request):
        Resource = appenlight.models.resource.Resource

        self.__acl__ = []
        group_id = request.matchdict.get("group_id", request.params.get("group_id"))
        group_id = to_integer_safe(group_id)
        self.report_group = ReportGroupService.by_id(group_id) if group_id else None
        if not self.report_group:
            raise HTTPNotFound()

        self.public = self.report_group.public
        self.resource = (
            ResourceService.by_resource_id(self.report_group.resource_id)
            if self.report_group
            else None
        )

        if self.resource:
            self.__acl__ = self.resource.__acl__
        if request.user:
            permissions = ResourceService.perms_for_user(self.resource, request.user)
            for perm_user, perm_name in permission_to_04_acls(permissions):
                self.__acl__.append(rewrite_root_perm(perm_user, perm_name))
        if self.public:
            self.__acl__.append((Allow, Everyone, "view"))
        if not request.user:
            # unauthed users need to visit using both group and report pair
            report_id = request.params.get(
                "reportId", request.params.get("report_id", -1)
            )
            report = self.report_group.get_report(report_id, public=True)
            if not report:
                raise HTTPNotFound()
        add_root_superperm(request, self)
Example #2
0
    def __init__(self, request):
        self.__acl__ = []
        self.used_uuid = False
        # used_uuid is set to true if user who is normally not authorized to
        # view the resource gains access to it because owner set it to public
        # and user knows the uuid of object

        org_resource_id = request.matchdict.get("resource_id",
                                                request.GET.get("resource_id"))
        resource_id = to_integer_safe(org_resource_id)
        self.resource = (ResourceService.by_resource_id(resource_id)
                         if resource_id else None)
        if self.resource is None:
            self.resource = DashboardService.by_uuid(org_resource_id)

        if self.resource and request.user:
            self.__acl__ = self.resource.__acl__
            permissions = ResourceService.perms_for_user(
                self.resource, request.user)
            for perm_user, perm_name in permission_to_04_acls(permissions):
                self.__acl__.append(rewrite_root_perm(perm_user, perm_name))

        if self.resource and self.resource.public:
            if not request.has_permission("view", self):
                self.used_uuid = True
            self.__acl__.append((Allow, Everyone, "view"))

        add_root_superperm(request, self)
Example #3
0
 def send_alerts(self, request=None, resource=None, db_session=None):
     """" Sends alerts to applicable channels """
     db_session = get_db_session(db_session)
     db_session.flush()
     if not resource:
         resource = ResourceService.by_resource_id(self.resource_id)
     if not request:
         request = get_current_request()
     if not resource:
         return
     users = set(
         [p.user for p in ResourceService.users_for_perm(resource, "view")])
     for user in users:
         for channel in user.alert_channels:
             matches_resource = not channel.resources or resource in [
                 r.resource_id for r in channel.resources
             ]
             if (not channel.channel_validated or not channel.send_alerts
                     or not matches_resource):
                 continue
             else:
                 try:
                     channel.notify_alert(resource=resource,
                                          event=self,
                                          user=user,
                                          request=request)
                 except IntegrationException as e:
                     log.warning("%s" % e)
Example #4
0
    def __init__(self, request):
        self.__acl__ = []
        self.used_uuid = False
        # used_uuid is set to true if user who is normally not authorized to
        # view the resource gains access to it because owner set it to public
        # and user knows the uuid of object

        alert_id = request.matchdict.get("alert_id",
                                         request.GET.get("alert_id"))
        self.alert = AlertChannelActionService.by_pkey(alert_id)
        if not self.alert:
            raise HTTPNotFound()

        self.chart = DashboardChartService.by_uuid(self.alert.other_id)

        if not self.chart:
            raise HTTPNotFound()

        self.resource = ResourceService.by_resource_id(self.chart.resource_id)
        if self.resource and request.user:
            self.__acl__ = self.resource.__acl__
            permissions = ResourceService.perms_for_user(
                self.resource, request.user)
            for perm_user, perm_name in permission_to_04_acls(permissions):
                self.__acl__.append(rewrite_root_perm(perm_user, perm_name))

        if self.resource and self.resource.public:
            if not request.has_permission("view", self):
                self.used_uuid = True
            self.__acl__.append((Allow, Everyone, "view"))

        add_root_superperm(request, self)
Example #5
0
    def __init__(self, request):
        Resource = appenlight.models.resource.Resource

        self.__acl__ = []
        resource_id = request.unsafe_json_body().get("resource_id")
        resource_id = to_integer_safe(resource_id)
        self.resource = ResourceService.by_resource_id(resource_id)
        if self.resource and request.user:
            self.__acl__ = self.resource.__acl__
            permissions = ResourceService.perms_for_user(self.resource, request.user)
            for perm_user, perm_name in permission_to_04_acls(permissions):
                self.__acl__.append(rewrite_root_perm(perm_user, perm_name))
        add_root_superperm(request, self)
Example #6
0
def get_user_service_permissions(user, service, request,
                                 inherit_groups_permissions=True, resolve_groups_permissions=False):
    # type: (models.User, models.Service, Request, bool, bool) -> List[PermissionSet]
    if service.owner_user_id == user.id:
        perm_type = PermissionType.OWNED
        usr_svc_perms = service_factory(service, request).permissions
    else:
        if inherit_groups_permissions or resolve_groups_permissions:
            perm_type = PermissionType.INHERITED
            usr_svc_perms = ResourceService.perms_for_user(service, user, db_session=request.db)
        else:
            perm_type = PermissionType.DIRECT
            usr_svc_perms = ResourceService.direct_perms_for_user(service, user, db_session=request.db)
    return [PermissionSet(p, typ=perm_type) for p in usr_svc_perms]
    def delete_branch(cls, resource_id=None, db_session=None, *args, **kwargs):
        """
        This deletes whole branch with children starting from resource_id

        :param resource_id:
        :param db_session:
        :return:
        """
        tablename = cls.model.__table__.name

        # lets lock rows to prevent bad tree states
        resource = ResourceService.lock_resource_for_update(
            resource_id=resource_id,
            db_session=db_session)
        parent_id = resource.parent_id
        ordering = resource.ordering
        raw_q = """
            WITH RECURSIVE subtree AS (
                    SELECT res.resource_id
                    FROM {tablename} AS res WHERE res.resource_id = :resource_id
                  UNION ALL
                    SELECT res_u.resource_id
                    FROM {tablename} res_u, subtree st
                    WHERE res_u.parent_id = st.resource_id
            )
            DELETE FROM resources where resource_id in (select * from subtree);
        """.format(tablename=tablename)
        db_session = get_db_session(db_session)
        text_obj = sa.text(raw_q)
        db_session.execute(text_obj, params={'resource_id': resource_id})
        cls.shift_ordering_down(parent_id, ordering, db_session=db_session)
        return True
Example #8
0
def user_resource_permission_create(request):
    """
    Set new permissions for user for a resource
    """
    resource = request.context.resource
    user_name = request.unsafe_json_body.get("user_name")
    user = UserService.by_user_name(user_name)
    if not user:
        user = UserService.by_email(user_name)
    if not user:
        return False

    for perm_name in request.unsafe_json_body.get("permissions", []):
        permission = UserResourcePermissionService.by_resource_user_and_perm(
            user.id, perm_name, resource.resource_id
        )
        if not permission:
            permission = UserResourcePermission(perm_name=perm_name, user_id=user.id)
            resource.user_permissions.append(permission)
    DBSession.flush()
    perms = [
        p.perm_name
        for p in ResourceService.perms_for_user(resource, user)
        if p.type == "user"
    ]
    result = {"user_name": user.user_name, "permissions": list(set(perms))}
    return result
Example #9
0
    def set_position(cls,
                     resource_id,
                     to_position,
                     db_session=None,
                     *args,
                     **kwargs):
        """
        Sets node position for new node in the tree

        :param resource_id: resource to move
        :param to_position: new position
        :param db_session:
        :return:def count_children(cls, resource_id, db_session=None):
        """
        db_session = get_db_session(db_session)
        # lets lock rows to prevent bad tree states
        resource = ResourceService.lock_resource_for_update(
            resource_id=resource_id, db_session=db_session)
        cls.check_node_position(resource.parent_id,
                                to_position,
                                on_same_branch=True,
                                db_session=db_session)
        cls.shift_ordering_up(resource.parent_id,
                              to_position,
                              db_session=db_session)
        db_session.flush()
        db_session.expire(resource)
        resource.ordering = to_position
        return True
    def test_resource_users_for_any_perm_excluding_group_perms(self, db_session):
        self.maxDiff = 99999
        self.set_up_user_group_and_perms(db_session)
        user6 = add_user(db_session, 6, "user 6")
        user7 = add_user(db_session, 7, "user 7")
        perm2 = GroupResourcePermission(
            perm_name="group_perm2", resource_id=self.resource.resource_id
        )
        self.group.resource_permissions.append(perm2)
        self.group.users.append(user6)
        self.group.users.append(user7)
        perms = ResourceService.users_for_perm(
            self.resource,
            "__any_permission__",
            limit_group_permissions=True,
            skip_group_perms=True,
            db_session=db_session,
        )
        second = [
            PermissionTuple(
                self.user, "test_perm2", "user", None, self.resource, False, True
            ),
            PermissionTuple(
                self.user, "foo_perm", "user", None, self.resource, False, True
            ),
        ]

        check_one_in_other(perms, second)
Example #11
0
    def check_node_parent(cls,
                          resource_id,
                          new_parent_id,
                          db_session=None,
                          *args,
                          **kwargs):
        """
        Checks if parent destination is valid for node

        :param resource_id:
        :param new_parent_id:
        :param db_session:
        :return:
        """
        db_session = get_db_session(db_session)
        new_parent = ResourceService.lock_resource_for_update(
            resource_id=new_parent_id, db_session=db_session)
        # we are not moving to "root" so parent should be found
        if not new_parent and new_parent_id is not None:
            raise ZigguratResourceTreeMissingException(
                'New parent node not found')
        else:
            result = cls.path_upper(new_parent_id, db_session=db_session)
            path_ids = [r.resource_id for r in result]
            if resource_id in path_ids:
                raise ZigguratResourceTreePathException(
                    'Trying to insert node into itself')
Example #12
0
    def delete_branch(cls, resource_id=None, db_session=None, *args, **kwargs):
        """
        This deletes whole branch with children starting from resource_id

        :param resource_id:
        :param db_session:
        :return:
        """
        tablename = cls.model.__table__.name

        # lets lock rows to prevent bad tree states
        resource = ResourceService.lock_resource_for_update(
            resource_id=resource_id, db_session=db_session)
        parent_id = resource.parent_id
        ordering = resource.ordering
        raw_q = """
            WITH RECURSIVE subtree AS (
                    SELECT res.resource_id
                    FROM {tablename} AS res WHERE res.resource_id = :resource_id
                  UNION ALL
                    SELECT res_u.resource_id
                    FROM {tablename} res_u, subtree st
                    WHERE res_u.parent_id = st.resource_id
            )
            DELETE FROM resources where resource_id in (select * from subtree);
        """.format(tablename=tablename)
        db_session = get_db_session(db_session)
        text_obj = sa.text(raw_q)
        db_session.execute(text_obj, params={'resource_id': resource_id})
        cls.shift_ordering_down(parent_id, ordering, db_session=db_session)
        return True
Example #13
0
 def build_json_user_resource_tree(usr):
     json_res = {}
     perm_type = PermissionType.INHERITED if inherit_groups_perms else PermissionType.DIRECT
     services = ResourceService.all(models.Service, db_session=db)
     # add service-types so they are ordered and listed if no service of that type was defined
     for svc_type in sorted(SERVICE_TYPE_DICT):
         json_res[svc_type] = {}
     for svc in services:
         svc_perms = uu.get_user_service_permissions(
             user=usr,
             service=svc,
             request=request,
             inherit_groups_permissions=inherit_groups_perms,
             resolve_groups_permissions=resolve_groups_perms)
         res_perms_dict = uu.get_user_service_resources_permissions_dict(
             user=usr,
             service=svc,
             request=request,
             inherit_groups_permissions=inherit_groups_perms,
             resolve_groups_permissions=resolve_groups_perms)
         # always allow admin to view full resource tree, unless explicitly requested to be filtered
         # otherwise (non-admin), only add details if there is at least one resource permission (any level)
         if (is_admin and not filtered_perms) or (svc_perms
                                                  or res_perms_dict):
             json_res[svc.type][
                 svc.resource_name] = format_service_resources(
                     svc,
                     db_session=db,
                     service_perms=svc_perms,
                     resources_perms_dict=res_perms_dict,
                     permission_type=perm_type,
                     show_all_children=False,
                     show_private_url=False,
                 )
     return json_res
    def test_resource_users_for_any_perm(self, db_session):
        self.maxDiff = 99999
        self.set_up_user_group_and_perms(db_session)
        perms = ResourceService.users_for_perm(
            self.resource, "__any_permission__", db_session=db_session
        )
        second = [
            PermissionTuple(
                self.user, "group_perm", "group", self.group, self.resource, False, True
            ),
            PermissionTuple(
                self.user, "test_perm2", "user", None, self.resource, False, True
            ),
            PermissionTuple(
                self.user, "foo_perm", "user", None, self.resource, False, True
            ),
            PermissionTuple(
                self.user4,
                "group_perm",
                "group",
                self.group2,
                self.resource,
                False,
                True,
            ),
        ]

        check_one_in_other(perms, second)
Example #15
0
 def resource_get(self, resource_id):
     request = self.request
     resource = ResourceService.get(safe_integer(resource_id),
                                    db_session=request.dbsession)
     if not resource:
         raise pyramid.httpexceptions.HTTPNotFound()
     return resource
Example #16
0
    def test_resource_users_for_any_perm(self, db_session):
        self.maxDiff = 99999
        self.set_up_user_group_and_perms(db_session)
        perms = ResourceService.users_for_perm(self.resource,
                                               "__any_permission__",
                                               db_session=db_session)
        second = [
            PermissionTuple(self.user, "group_perm", "group", self.group,
                            self.resource, False, True),
            PermissionTuple(self.user, "test_perm2", "user", None,
                            self.resource, False, True),
            PermissionTuple(self.user, "foo_perm", "user", None, self.resource,
                            False, True),
            PermissionTuple(
                self.user4,
                "group_perm",
                "group",
                self.group2,
                self.resource,
                False,
                True,
            ),
        ]

        check_one_in_other(perms, second)
Example #17
0
    def test_resource_users_limited_group_ownage(self, db_session):
        self.maxDiff = 9999
        self.set_up_user_group_and_perms(db_session)
        resource = ResourceTestobjB(resource_id=99,
                                    resource_name="other",
                                    owner_user_id=self.user2.id)
        group3 = add_group(db_session, "group 3")
        user2_permission = UserResourcePermission(perm_name="foo_perm",
                                                  user_id=self.user2.id)
        group3_permission = GroupResourcePermission(perm_name="group_perm",
                                                    group_id=group3.id)
        resource.group_permissions.append(group3_permission)
        resource.user_permissions.append(user2_permission)
        group3.users.append(self.user3)
        self.user.resources.append(resource)
        self.group2.resources.append(resource)
        db_session.flush()
        perms = ResourceService.users_for_perm(resource,
                                               "__any_permission__",
                                               db_session=db_session)
        second = [
            PermissionTuple(self.user2, "foo_perm", "user", None, resource,
                            False, True),
            PermissionTuple(self.user, ALL_PERMISSIONS, "user", None, resource,
                            True, True),
            PermissionTuple(self.user4, ALL_PERMISSIONS, "group", self.group2,
                            resource, True, True),
            PermissionTuple(self.user3, "group_perm", "group", group3,
                            resource, False, True),
        ]

        check_one_in_other(perms, second)
    def check_node_parent(cls, resource_id, new_parent_id, db_session=None,
                          *args, **kwargs):
        """
        Checks if parent destination is valid for node

        :param resource_id:
        :param new_parent_id:
        :param db_session:
        :return:
        """
        db_session = get_db_session(db_session)
        new_parent = ResourceService.lock_resource_for_update(
            resource_id=new_parent_id,
            db_session=db_session)
        # we are not moving to "root" so parent should be found
        if not new_parent and new_parent_id is not None:
            raise ZigguratResourceTreeMissingException(
                'New parent node not found')
        else:
            result = cls.path_upper(new_parent_id,
                                    db_session=db_session)
            path_ids = [r.resource_id for r in result]
            if resource_id in path_ids:
                raise ZigguratResourceTreePathException(
                    'Trying to insert node into itself')
Example #19
0
def get_group_resources(group, db_session):
    # type: (models.Group, Session) -> JSON
    """
    Get formatted JSON body describing all service resources the ``group`` as permissions on.
    """
    json_response = {}
    for svc in list(ResourceService.all(models.Service,
                                        db_session=db_session)):
        svc_perms = get_group_service_permissions(group=group,
                                                  service=svc,
                                                  db_session=db_session)
        svc_name = str(svc.resource_name)
        svc_type = str(svc.type)
        if svc_type not in json_response:
            json_response[svc_type] = {}
        res_perm_dict = get_group_service_resources_permissions_dict(
            group=group, service=svc, db_session=db_session)
        json_response[svc_type][svc_name] = format_service_resources(
            svc,
            db_session=db_session,
            service_perms=svc_perms,
            resources_perms_dict=res_perm_dict,
            permission_type=PermissionType.APPLIED,
            show_all_children=False,
            show_private_url=False,
        )
    return json_response
 def resource_name(self, db_session=None):
     db_session = get_db_session(db_session)
     if self.resource_id:
         return ResourceService.by_resource_id(
             self.resource_id, db_session=db_session).resource_name
     else:
         return "any resource"
Example #21
0
    def test_resource_groups_for_any_perm_just_group_perms_limited_empty_group(
            self, db_session):
        self.maxDiff = 99999
        self.set_up_user_group_and_perms(db_session)
        user6 = add_user(db_session, 6, "user 6")
        user7 = add_user(db_session, 7, "user 7")
        perm2 = GroupResourcePermission(perm_name="group_perm2",
                                        resource_id=self.resource.resource_id)
        self.group.resource_permissions.append(perm2)
        self.group.users.append(user6)
        self.group.users.append(user7)

        group3 = add_group(db_session, "Empty group")
        perm3 = GroupResourcePermission(perm_name="group_permx",
                                        resource_id=self.resource.resource_id)
        group3.resource_permissions.append(perm3)
        perms = ResourceService.groups_for_perm(
            self.resource,
            "__any_permission__",
            limit_group_permissions=True,
            db_session=db_session,
        )

        second = [
            PermissionTuple(None, "group_perm", "group", self.group,
                            self.resource, False, True),
            PermissionTuple(None, "group_perm2", "group", self.group,
                            self.resource, False, True),
            PermissionTuple(None, "group_perm", "group", self.group2,
                            self.resource, False, True),
            PermissionTuple(None, "group_permx", "group", group3,
                            self.resource, False, True),
        ]

        check_one_in_other(perms, second)
Example #22
0
    def test_resource_users_for_any_perm_excluding_group_perms(
            self, db_session):
        self.maxDiff = 99999
        self.set_up_user_group_and_perms(db_session)
        user6 = add_user(db_session, 6, "user 6")
        user7 = add_user(db_session, 7, "user 7")
        perm2 = GroupResourcePermission(perm_name="group_perm2",
                                        resource_id=self.resource.resource_id)
        self.group.resource_permissions.append(perm2)
        self.group.users.append(user6)
        self.group.users.append(user7)
        perms = ResourceService.users_for_perm(
            self.resource,
            "__any_permission__",
            limit_group_permissions=True,
            skip_group_perms=True,
            db_session=db_session,
        )
        second = [
            PermissionTuple(self.user, "test_perm2", "user", None,
                            self.resource, False, True),
            PermissionTuple(self.user, "foo_perm", "user", None, self.resource,
                            False, True),
        ]

        check_one_in_other(perms, second)
Example #23
0
    def __init__(self, request):
        Resource = appenlight.models.resource.Resource
        self.__acl__ = []
        self.resource = None
        plugin_id = to_integer_safe(request.matchdict.get("id"))
        self.plugin = PluginConfigService.by_id(plugin_id)
        if not self.plugin:
            raise HTTPNotFound()
        if self.plugin.resource_id:
            self.resource = ResourceService.by_resource_id(self.plugin.resource_id)
        if self.resource:
            self.__acl__ = self.resource.__acl__
        if request.user and self.resource:
            permissions = ResourceService.perms_for_user(self.resource, request.user)
            for perm_user, perm_name in permission_to_04_acls(permissions):
                self.__acl__.append(rewrite_root_perm(perm_user, perm_name))

        add_root_superperm(request, self)
Example #24
0
def check_user_report_notifications(resource_id):
    since_when = datetime.utcnow()
    try:
        request = get_current_request()
        application = ApplicationService.by_id(resource_id)
        if not application:
            return
        error_key = REDIS_KEYS["reports_to_notify_per_type_per_app"].format(
            ReportType.error, resource_id)
        slow_key = REDIS_KEYS["reports_to_notify_per_type_per_app"].format(
            ReportType.slow, resource_id)
        error_group_ids = Datastores.redis.smembers(error_key)
        slow_group_ids = Datastores.redis.smembers(slow_key)
        Datastores.redis.delete(error_key)
        Datastores.redis.delete(slow_key)
        err_gids = [int(g_id) for g_id in error_group_ids]
        slow_gids = [int(g_id) for g_id in list(slow_group_ids)]
        group_ids = err_gids + slow_gids
        occurence_dict = {}
        for g_id in group_ids:
            key = REDIS_KEYS["counters"]["report_group_occurences"].format(
                g_id)
            val = Datastores.redis.get(key)
            Datastores.redis.delete(key)
            if val:
                occurence_dict[g_id] = int(val)
            else:
                occurence_dict[g_id] = 1
        report_groups = ReportGroupService.by_ids(group_ids)
        report_groups.options(sa.orm.joinedload(ReportGroup.last_report_ref))

        ApplicationService.check_for_groups_alert(
            application,
            "alert",
            report_groups=report_groups,
            occurence_dict=occurence_dict,
        )
        users = set([
            p.user
            for p in ResourceService.users_for_perm(application, "view")
        ])
        report_groups = report_groups.all()
        for user in users:
            UserService.report_notify(
                user,
                request,
                application,
                report_groups=report_groups,
                occurence_dict=occurence_dict,
            )
        for group in report_groups:
            # marks report_groups as notified
            if not group.notified:
                group.notified = True
    except Exception as exc:
        print_traceback(log)
        raise
Example #25
0
 def test_group_resource_permission_wrong(self, db_session):
     self.set_up_user_group_and_perms(db_session)
     perm_name = 'group_permX'
     perm = ResourceService.perm_by_group_and_perm_name(
         resource_id=self.resource.resource_id,
         group_id=self.group.id,
         perm_name=perm_name,
         db_session=db_session)
     assert perm is None
Example #26
0
 def by_resource_name(name,db_session=None):
     db_session = get_db_session(db_session)
     try:
         resource = db_session.query(Resource).filter(Resource.resource_name==name).one()
         log.debug(resource)
         return ResourceService.by_resource_id(resource_id=resource.resource_id,
                                               db_session=db_session)
     except Exception as e:
         log.debug('Error retrieving resource by name, {0}'.format(e))
         raise
 def test_group_resource_permission_wrong(self, db_session):
     self.set_up_user_group_and_perms(db_session)
     perm_name = 'group_permX'
     perm = ResourceService.perm_by_group_and_perm_name(
         resource_id=self.resource.resource_id,
         group_id=self.group.id,
         perm_name=perm_name,
         db_session=db_session
     )
     assert perm is None
Example #28
0
    def test_resource_users_for_perm(self, db_session):
        self.set_up_user_group_and_perms(db_session)
        perms = ResourceService.users_for_perm(self.resource,
                                               "foo_perm",
                                               db_session=db_session)
        second = [
            PermissionTuple(self.user, "foo_perm", "user", None, self.resource,
                            False, True)
        ]

        check_one_in_other(perms, second)
Example #29
0
 def by_resource_name(name, db_session=None):
     db_session = get_db_session(db_session)
     try:
         resource = db_session.query(Resource).filter(
             Resource.resource_name == name).one()
         log.debug(resource)
         return ResourceService.by_resource_id(
             resource_id=resource.resource_id, db_session=db_session)
     except Exception as e:
         log.debug('Error retrieving resource by name, {0}'.format(e))
         raise
    def by_resource_id(cls, resource_id, db_session=None):
        """

        .. deprecated:: 0.8

        :param resource_id:
        :param db_session:
        :return:
        """
        db_session = get_db_session(db_session)
        return ResourceService.by_resource_id(resource_id=resource_id,
                                              db_session=db_session)
Example #31
0
def add_service_getcapabilities_perms(service, db_session, group_name=None):
    if service.type in SERVICES_PHOENIX_ALLOWED and \
            Permission.GET_CAPABILITIES in SERVICE_TYPE_DICT[service.type].permissions:
        if group_name is None:
            group_name = get_constant("MAGPIE_ANONYMOUS_USER")
        group = GroupService.by_group_name(group_name, db_session=db_session)
        perm = ResourceService.perm_by_group_and_perm_name(
            service.resource_id, group.id, Permission.GET_CAPABILITIES.value,
            db_session)
        if perm is None:  # not set, create it
            create_group_resource_permission_response(
                group, service, Permission.GET_CAPABILITIES, db_session)
 def test_group_resource_permission2(self, db_session):
     self.set_up_user_group_and_perms(db_session)
     perm_name = "group_perm"
     perm = ResourceService.perm_by_group_and_perm_name(
         resource_id=self.resource.resource_id,
         group_id=self.group.id,
         perm_name=perm_name,
         db_session=db_session,
     )
     assert perm.group_id == self.group.id
     assert perm.resource_id == self.resource.resource_id
     assert perm.perm_name == perm_name
Example #33
0
    def test_resources_with_direct_group_perms(self, db_session):
        self.set_up_user_group_and_perms(db_session)
        # test_perm1 from group perms should be ignored
        perms = ResourceService.group_perms_for_user(self.resource,
                                                     self.user,
                                                     db_session=db_session)
        second = [
            PermissionTuple(self.user, "group_perm", "group", self.group,
                            self.resource, False, True)
        ]

        check_one_in_other(perms, second)
    def group_perms_for_user(self, user, db_session=None):
        """

        .. deprecated:: 0.8

        :param user:
        :param db_session:
        :return:
        """
        db_session = get_db_session(db_session, self)
        return ResourceService.group_perms_for_user(
            self, user=user, db_session=db_session)
    def test_resource_users_for_perm(self, db_session):
        self.set_up_user_group_and_perms(db_session)
        perms = ResourceService.users_for_perm(
            self.resource, "foo_perm", db_session=db_session
        )
        second = [
            PermissionTuple(
                self.user, "foo_perm", "user", None, self.resource, False, True
            )
        ]

        check_one_in_other(perms, second)
Example #36
0
 def test_group_resource_permission2(self, db_session):
     self.set_up_user_group_and_perms(db_session)
     perm_name = "group_perm"
     perm = ResourceService.perm_by_group_and_perm_name(
         resource_id=self.resource.resource_id,
         group_id=self.group.id,
         perm_name=perm_name,
         db_session=db_session,
     )
     assert perm.group_id == self.group.id
     assert perm.resource_id == self.resource.resource_id
     assert perm.perm_name == perm_name
Example #37
0
def get_resource_root_service_by_id(resource_id, db_session):
    # type: (ServiceOrResourceType, Session) -> Optional[models.Service]
    """
    Retrieves the service-specialized resource corresponding to the top-level resource in the tree hierarchy.

    .. seealso::
        - :func:`get_resource_root_service` for same operation but directly using the resource
    """
    resource = ResourceService.by_resource_id(resource_id,
                                              db_session=db_session)
    if resource is None:
        return None
    return get_resource_root_service(resource, db_session=db_session)
Example #38
0
 def test_owned_permissions(self, db_session):
     created_user = add_user(db_session)
     resource = add_resource(db_session, 1, "test_resource")
     created_user.resources.append(resource)
     db_session.flush()
     resources = UserService.resources_with_perms(
         created_user, ["test_perm"], db_session=db_session).all()
     assert resources[0] == resource
     permission = ResourceService.direct_perms_for_user(
         resource, created_user)[0]
     assert permission.owner is True
     assert permission.allowed is True
     assert permission.user.id == created_user.id
    def test_resources_with_direct_group_perms(self, db_session):
        self.set_up_user_group_and_perms(db_session)
        # test_perm1 from group perms should be ignored
        perms = ResourceService.group_perms_for_user(
            self.resource, self.user, db_session=db_session
        )
        second = [
            PermissionTuple(
                self.user, "group_perm", "group", self.group, self.resource, False, True
            )
        ]

        check_one_in_other(perms, second)
    def test_resource_groups_for_any_perm_additional_users(self, db_session):
        self.maxDiff = 99999
        self.set_up_user_group_and_perms(db_session)
        user6 = add_user(db_session, 6, "user 6")
        user7 = add_user(db_session, 7, "user 7")
        perm2 = GroupResourcePermission(
            perm_name="group_perm2", resource_id=self.resource.resource_id
        )
        self.group.resource_permissions.append(perm2)
        self.group.users.append(user6)
        self.group.users.append(user7)
        perms = ResourceService.groups_for_perm(
            self.resource, "__any_permission__", db_session=db_session
        )
        second = [
            PermissionTuple(
                self.user, "group_perm", "group", self.group, self.resource, False, True
            ),
            PermissionTuple(
                user6, "group_perm", "group", self.group, self.resource, False, True
            ),
            PermissionTuple(
                user7, "group_perm", "group", self.group, self.resource, False, True
            ),
            PermissionTuple(
                self.user,
                "group_perm2",
                "group",
                self.group,
                self.resource,
                False,
                True,
            ),
            PermissionTuple(
                user6, "group_perm2", "group", self.group, self.resource, False, True
            ),
            PermissionTuple(
                user7, "group_perm2", "group", self.group, self.resource, False, True
            ),
            PermissionTuple(
                self.user4,
                "group_perm",
                "group",
                self.group2,
                self.resource,
                False,
                True,
            ),
        ]

        check_one_in_other(perms, second)
    def test_resource_users_limited_group_other_user_3(self, db_session):
        self.maxDiff = 9999
        self.set_up_user_group_and_perms(db_session)
        perms = ResourceService.users_for_perm(
            self.resource2,
            "__any_permission__",
            user_ids=[self.user3.id],
            db_session=db_session,
        )
        second = [
            PermissionTuple(
                self.user3, "test_perm", "user", None, self.resource2, False, True
            )
        ]

        check_one_in_other(perms, second)
    def perm_by_group_and_perm_name(cls, res_id, group_id, perm_name,
                                    db_session=None):
        """

        .. deprecated:: 0.8

        :param res_id:
        :param group_id:
        :param perm_name:
        :param db_session:
        :return:
        """
        db_session = get_db_session(db_session)
        return ResourceService.perm_by_group_and_perm_name(
            resource_id=res_id, group_id=group_id, perm_name=perm_name,
            db_session=db_session)
    def groups_for_perm(self, perm_name, group_ids=None,
                        limit_group_permissions=False,
                        db_session=None):
        """

        .. deprecated:: 0.8

        :param perm_name:
        :param group_ids:
        :param limit_group_permissions:
        :param db_session:
        :return:
        """
        db_session = get_db_session(db_session, self)
        return ResourceService.groups_for_perm(
            self, perm_name=perm_name, group_ids=group_ids,
            limit_group_permissions=limit_group_permissions,
            db_session=db_session)
    def test_resource_groups_for_any_perm_just_group_perms_limited_empty_group(
        self, db_session
    ):
        self.maxDiff = 99999
        self.set_up_user_group_and_perms(db_session)
        user6 = add_user(db_session, 6, "user 6")
        user7 = add_user(db_session, 7, "user 7")
        perm2 = GroupResourcePermission(
            perm_name="group_perm2", resource_id=self.resource.resource_id
        )
        self.group.resource_permissions.append(perm2)
        self.group.users.append(user6)
        self.group.users.append(user7)

        group3 = add_group(db_session, "Empty group")
        perm3 = GroupResourcePermission(
            perm_name="group_permx", resource_id=self.resource.resource_id
        )
        group3.resource_permissions.append(perm3)
        perms = ResourceService.groups_for_perm(
            self.resource,
            "__any_permission__",
            limit_group_permissions=True,
            db_session=db_session,
        )

        second = [
            PermissionTuple(
                None, "group_perm", "group", self.group, self.resource, False, True
            ),
            PermissionTuple(
                None, "group_perm2", "group", self.group, self.resource, False, True
            ),
            PermissionTuple(
                None, "group_perm", "group", self.group2, self.resource, False, True
            ),
            PermissionTuple(
                None, "group_permx", "group", group3, self.resource, False, True
            ),
        ]

        check_one_in_other(perms, second)
    def test_resource_users_limited_group_ownage(self, db_session):
        self.maxDiff = 9999
        self.set_up_user_group_and_perms(db_session)
        resource = TestResourceB(
            resource_id=99, resource_name="other", owner_user_id=self.user2.id
        )
        group3 = add_group(db_session, "group 3")
        user2_permission = UserResourcePermission(
            perm_name="foo_perm", user_id=self.user2.id
        )
        group3_permission = GroupResourcePermission(
            perm_name="group_perm", group_id=group3.id
        )
        resource.group_permissions.append(group3_permission)
        resource.user_permissions.append(user2_permission)
        group3.users.append(self.user3)
        self.user.resources.append(resource)
        self.group2.resources.append(resource)
        db_session.flush()
        perms = ResourceService.users_for_perm(
            resource, "__any_permission__", db_session=db_session
        )
        second = [
            PermissionTuple(
                self.user2, "foo_perm", "user", None, resource, False, True
            ),
            PermissionTuple(
                self.user, ALL_PERMISSIONS, "user", None, resource, True, True
            ),
            PermissionTuple(
                self.user4, ALL_PERMISSIONS, "group", self.group2, resource, True, True
            ),
            PermissionTuple(
                self.user3, "group_perm", "group", group3, resource, False, True
            ),
        ]

        check_one_in_other(perms, second)
    def test_resource_users_limited_group_other_user_4(self, db_session):
        self.maxDiff = 9999
        self.set_up_user_group_and_perms(db_session)
        perms = ResourceService.users_for_perm(
            self.resource,
            "__any_permission__",
            user_ids=[self.user4.id],
            group_ids=[self.group2.id],
            db_session=db_session,
        )
        second = [
            PermissionTuple(
                self.user4,
                "group_perm",
                "group",
                self.group2,
                self.resource,
                False,
                True,
            )
        ]

        check_one_in_other(perms, second)
    def set_position(cls, resource_id, to_position, db_session=None, *args,
                     **kwargs):
        """
        Sets node position for new node in the tree

        :param resource_id: resource to move
        :param to_position: new position
        :param db_session:
        :return:def count_children(cls, resource_id, db_session=None):
        """
        db_session = get_db_session(db_session)
        # lets lock rows to prevent bad tree states
        resource = ResourceService.lock_resource_for_update(
            resource_id=resource_id,
            db_session=db_session)
        cls.check_node_position(
            resource.parent_id, to_position, on_same_branch=True,
            db_session=db_session)
        cls.shift_ordering_up(resource.parent_id, to_position,
                              db_session=db_session)
        db_session.flush()
        db_session.expire(resource)
        resource.ordering = to_position
        return True
 def test_get(self, db_session):
     add_resource(db_session, 1, 'root')
     resource = ResourceService.get(resource_id=1, db_session=db_session)
     assert resource.resource_id == 1
     assert resource.resource_name == 'root'
    def move_to_position(cls, resource_id, to_position,
                         new_parent_id=noop, db_session=None, *args,
                         **kwargs):
        """
        Moves node to new location in the tree

        :param resource_id: resource to move
        :param to_position: new position
        :param new_parent_id: new parent id
        :param db_session:
        :return:
        """
        db_session = get_db_session(db_session)
        # lets lock rows to prevent bad tree states
        resource = ResourceService.lock_resource_for_update(
            resource_id=resource_id,
            db_session=db_session)
        parent = ResourceService.lock_resource_for_update(
            resource_id=resource.parent_id,
            db_session=db_session)
        same_branch = False

        # reset if parent is same as old
        if new_parent_id == resource.parent_id:
            new_parent_id = noop

        if new_parent_id is not noop:
            cls.check_node_parent(resource_id, new_parent_id,
                                  db_session=db_session)
        else:
            same_branch = True

        if new_parent_id is noop:
            # it is not guaranteed that parent exists
            parent_id = resource.parent_id if resource else None
        else:
            parent_id = new_parent_id

        cls.check_node_position(
            parent_id, to_position, on_same_branch=same_branch,
            db_session=db_session)
        # move on same branch
        if new_parent_id is noop:
            order_range = list(sorted((resource.ordering, to_position)))
            move_down = resource.ordering > to_position

            query = db_session.query(cls.model)
            query = query.filter(cls.model.parent_id == parent_id)
            query = query.filter(cls.model.ordering.between(*order_range))
            if move_down:
                query.update({cls.model.ordering: cls.model.ordering + 1},
                             synchronize_session=False)
            else:
                query.update({cls.model.ordering: cls.model.ordering - 1},
                             synchronize_session=False)
            db_session.flush()
            db_session.expire(resource)
            resource.ordering = to_position
        # move between branches
        else:
            cls.shift_ordering_down(resource.parent_id, resource.ordering,
                                    db_session=db_session)
            cls.shift_ordering_up(new_parent_id, to_position,
                                  db_session=db_session)
            db_session.expire(resource)
            resource.parent_id = new_parent_id
            resource.ordering = to_position
            db_session.flush()
        return True