Ejemplo n.º 1
0
 def test_permissions_are_checked(self):
     user_with_perm = factories.UserFactory()
     user_without_perm = factories.UserFactory()
     perm = Permission.objects.get(content_type__app_label='address',
                                   codename='add_country')
     user_with_perm.user_permissions.add(perm)
     self.assertTrue(
         check_permissions(user_with_perm, ['address.add_country']))
     self.assertFalse(
         check_permissions(user_without_perm, ['address.add_country']))
Ejemplo n.º 2
0
 def test_permissions_are_checked(self):
     user_with_perm = factories.UserFactory()
     user_without_perm = factories.UserFactory()
     perm = Permission.objects.get(
         content_type__app_label='address', codename='add_country')
     user_with_perm.user_permissions.add(perm)
     self.assertTrue(
         check_permissions(user_with_perm, ['address.add_country']))
     self.assertFalse(
         check_permissions(user_without_perm, ['address.add_country']))
Ejemplo n.º 3
0
def default_access_fn(user, url_name, url_args=None, url_kwargs=None):
    """
    Given a url_name and a user, this function tries to assess whether the
    user has the right to access the URL.
    The application instance of the view is fetched via dynamic imports,
    and those assumptions will only hold true if the standard Oscar layout
    is followed.
    Once the permissions for the view are known, the access logic used
    by the dashboard decorator is evaluated

    This function might seem costly, but a simple comparison with DTT
    did not show any change in response time
    """
    exception = ImproperlyConfigured(
        "Please follow Oscar's default dashboard app layout or set a "
        "custom access_fn")
    if url_name is None:  # it's a heading
        return True

    # get view module string.
    try:
        url = reverse(url_name, args=url_args, kwargs=url_kwargs)
    except NoReverseMatch:
        # In Oscar 1.5 this exception was silently ignored which made debugging
        # very difficult. Now it is being logged and in future the exception will
        # be propagated.
        logger.exception('Invalid URL name {}'.format(url_name))
        return False

    view_module = resolve(url).func.__module__

    # We can't assume that the view has the same parent module as the app,
    # as either the app or view can be customised. So we turn the module
    # string (e.g. 'oscar.apps.dashboard.catalogue.views') into an app
    # label that can be loaded by get_class (e.g.
    # 'dashboard.catalogue.app), which then essentially checks
    # INSTALLED_APPS for the right module to load
    match = re.search('(dashboard[\w\.]*)\.views$', view_module)
    if not match:
        raise exception
    app_label_str = match.groups()[0] + '.app'

    try:
        app_instance = get_class(app_label_str, 'application')
    except AppNotFoundError:
        raise exception

    # handle name-spaced view names
    if ':' in url_name:
        view_name = url_name.split(':')[1]
    else:
        view_name = url_name
    permissions = app_instance.get_permissions(view_name)
    return check_permissions(user, permissions)
Ejemplo n.º 4
0
def default_access_fn(user, url_name, url_args=None, url_kwargs=None):
    """
    Given a url_name and a user, this function tries to assess whether the
    user has the right to access the URL.
    The application instance of the view is fetched via dynamic imports,
    and those assumptions will only hold true if the standard Oscar layout
    is followed.
    Once the permissions for the view are known, the access logic used
    by the dashboard decorator is evaluated

    This function might seem costly, but a simple comparison with DTT
    did not show any change in response time
    """
    exception = ImproperlyConfigured(
        "Please follow Oscar's default dashboard app layout or set a "
        "custom access_fn")
    if url_name is None:  # it's a heading
        return True

    # get view module string.
    try:
        url = reverse(url_name, args=url_args, kwargs=url_kwargs)
    except NoReverseMatch:
        # In Oscar 1.5 this exception was silently ignored which made debugging
        # very difficult. Now it is being logged and in future the exception will
        # be propagated.
        logger.exception('Invalid URL name {}'.format(url_name))
        return False

    view_module = resolve(url).func.__module__

    # We can't assume that the view has the same parent module as the app,
    # as either the app or view can be customised. So we turn the module
    # string (e.g. 'oscar.apps.dashboard.catalogue.views') into an app
    # label that can be loaded by get_class (e.g.
    # 'dashboard.catalogue.app), which then essentially checks
    # INSTALLED_APPS for the right module to load
    match = re.search('(dashboard[\w\.]*)\.views$', view_module)
    if not match:
        raise exception
    app_label_str = match.groups()[0] + '.app'

    try:
        app_instance = get_class(app_label_str, 'application')
    except AppNotFoundError:
        raise exception

    # handle name-spaced view names
    if ':' in url_name:
        view_name = url_name.split(':')[1]
    else:
        view_name = url_name
    permissions = app_instance.get_permissions(view_name)
    return check_permissions(user, permissions)
Ejemplo n.º 5
0
    def _default_access_fn(self, user):
        """
        Given a url_name and a user, this function tries to assess whether the
        user has the right to access the URL.
        The application instance of the view is fetched via dynamic imports,
        and those assumptions will only hold true if the standard Oscar layout
        is followed.
        Once the permissions for the view are known, the access logic used
        by the dashboard decorator is evaluated

        This function might seem costly, but a simple comparison with DTT
        did not show any change in response time
        """
        exception = ImproperlyConfigured(
            "Please follow Oscar's default dashboard app layout or set a "
            "custom access_fn")
        if self.is_heading:
            return True
        # get view module string
        try:
            url = reverse(self.url_name,
                          args=self.url_args,
                          kwargs=self.url_kwargs)
            view_module = resolve(url).func.__module__
        except (NoReverseMatch, Http404):
            # if there's no match, no need to display it
            return False

        # We can't assume that the view has the same parent module as the app,
        # as either the app or view can be customised. So we turn the module
        # string (e.g. 'oscar.apps.dashboard.catalogue.views') into an app
        # label that can be loaded by get_class (e.g.
        # 'dashboard.catalogue.app), which then essentially checks
        # INSTALLED_APPS for the right module to load
        match = re.search('(dashboard[\w\.]*)\.views$', view_module)
        if not match:
            raise exception
        app_label_str = match.groups()[0] + '.app'

        try:
            app_instance = get_class(app_label_str, 'application')
        except AppNotFoundError:
            raise exception

        # handle name-spaced view names
        if ':' in self.url_name:
            view_name = self.url_name.split(':')[1]
        else:
            view_name = self.url_name
        permissions = app_instance.get_permissions(view_name)
        return check_permissions(user, permissions)
Ejemplo n.º 6
0
    def _default_access_fn(self, user):
        """
        Given a url_name and a user, this function tries to assess whether the
        user has the right to access the URL.
        The application instance of the view is fetched via dynamic imports,
        and those assumptions will only hold true if the standard Oscar layout
        is followed.
        Once the permissions for the view are known, the access logic used
        by the dashboard decorator is evaluated

        This function might seem costly, but a simple comparison with DTT
        did not show any change in response time
        """
        exception = ImproperlyConfigured(
            "Please follow Oscar's default dashboard app layout or set a "
            "custom access_fn")
        if self.is_heading:
            return True
        # get view module string
        try:
            url = reverse(self.url_name, args=self.url_args,
                          kwargs=self.url_kwargs)
            view_module = resolve(url).func.__module__
        except (NoReverseMatch, Http404):
            # if there's no match, no need to display it
            return False

        # We can't assume that the view has the same parent module as the app,
        # as either the app or view can be customised. So we turn the module
        # string (e.g. 'oscar.apps.dashboard.catalogue.views') into an app
        # label that can be loaded by get_class (e.g.
        # 'dashboard.catalogue.app), which then essentially checks
        # INSTALLED_APPS for the right module to load
        match = re.search('(dashboard[\w\.]*)\.views$', view_module)
        if not match:
            raise exception
        app_label_str = match.groups()[0] + '.app'

        try:
            app_instance = get_class(app_label_str, 'application')
        except AppNotFoundError:
            raise exception

        # handle name-spaced view names
        if ':' in self.url_name:
            view_name = self.url_name.split(':')[1]
        else:
            view_name = self.url_name
        permissions = app_instance.get_permissions(view_name)
        return check_permissions(user, permissions)
Ejemplo n.º 7
0
def default_access_fn(user, url_name, url_args=None, url_kwargs=None):
    """
    Given a user and a url_name, this function assesses whether the
    user has the right to access the URL.
    Once the permissions for the view are known, the access logic used
    by the dashboard decorator is evaluated
    """
    if url_name is None:  # it's a heading
        return True

    url = reverse(url_name, args=url_args, kwargs=url_kwargs)
    url_match = resolve(url)
    url_name = url_match.url_name
    app_config_instance = _dashboard_url_names_to_config()[url_name]

    permissions = app_config_instance.get_permissions(url_name)

    return check_permissions(user, permissions)
Ejemplo n.º 8
0
    def _default_access_fn(self, user):
        """
        Given a url_name and a user, this function tries to assess whether the
        user has the right to access the URL.
        The application instance of the view is fetched via dynamic imports,
        and those assumptions will only hold true if the standard Oscar layout
        is followed.
        Once the permissions for the view are known, the access logic used
        by the dashboard decorator is evaluated

        This function might seem costly, but a simple comparison with DTT
        did not show any change in response time
        """
        if self.is_heading:
            return True
        try:
            url = reverse(self.url_name, args=self.url_args,
                          kwargs=self.url_kwargs)
        except NoReverseMatch:
            # if there's no match, no need to display it
            return False
        try:
            view_module = resolve(url).func.__module__
        except Http404:
            # unlikely, but again it doesn't make sense to display it
            return False
        if not view_module.endswith('.views'):
            raise ImproperlyConfigured("Please follow Oscar's default dashboard layout or replace access_fn")
        app_module_str = view_module.replace('.views', '.app')
        try:
            app_module = __import__(app_module_str, fromlist=['application'])
            app_instance = app_module.application
        except (ImportError, AttributeError):
            raise ImproperlyConfigured("Please follow Oscar's default dashboard layout or replace access_fn")

        if ':' in self.url_name:
            view_name = self.url_name.split(':')[1]
        else:
            view_name = self.url_name
        permissions = app_instance.get_permissions(view_name)
        return check_permissions(user, permissions)
Ejemplo n.º 9
0
def default_access_fn(user, url_name, url_args=None, url_kwargs=None):
    """
    Given a user and a url_name, this function assesses whether the
    user has the right to access the URL.
    Once the permissions for the view are known, the access logic used
    by the dashboard decorator is evaluated
    """
    if url_name is None:  # it's a heading
        return True

    try:
        url = reverse(url_name, args=url_args, kwargs=url_kwargs)
    except NoReverseMatch:
        logger.exception('Invalid URL name {}'.format(url_name))
        warnings.warn(
            'Invalid URL names supplied to oscar.dashboard.nav.default_access_fn'
            'will throw an exception in Oscar 2.1',
            RemovedInOscar21Warning,
            stacklevel=2
        )
        return False

    url_match = resolve(url)
    url_name = url_match.url_name
    try:
        app_config_instance = _dashboard_url_names_to_config()[url_name]
    except KeyError:
        logger.error(
            "{} is not a valid dashboard URL".format(url_match.view_name)
        )
        warnings.warn(
            'Invalid URL names supplied to oscar.dashboard.nav.default_access_fn'
            'will throw an exception in Oscar 2.1',
            RemovedInOscar21Warning,
            stacklevel=2
        )
        return False

    permissions = app_config_instance.get_permissions(url_name)

    return check_permissions(user, permissions)
Ejemplo n.º 10
0
 def test_methods_are_checked(self):
     anonymous_user = AnonymousUser()
     known_user = factories.UserFactory.build()
     self.assertTrue(check_permissions(anonymous_user, ['is_anonymous']))
     self.assertFalse(check_permissions(known_user, ['is_anonymous']))
Ejemplo n.º 11
0
 def test_methods_are_checked(self):
     anonymous_user = AnonymousUser()
     known_user = factories.UserFactory.build()
     self.assertTrue(check_permissions(anonymous_user, ['is_anonymous']))
     self.assertFalse(check_permissions(known_user, ['is_anonymous']))
Ejemplo n.º 12
0
 def test_empty_permissions_passes(self):
     user = factories.UserFactory.build()
     self.assertTrue(check_permissions(user, []))
Ejemplo n.º 13
0
 def test_properties_are_checked(self):
     staff_user = factories.UserFactory.build(is_staff=True)
     non_staff_user = factories.UserFactory.build(is_staff=False)
     self.assertTrue(check_permissions(staff_user, ['is_staff']))
     self.assertFalse(check_permissions(non_staff_user, ['is_staff']))
Ejemplo n.º 14
0
def default_access_fn(user, url_name, url_args=None, url_kwargs=None):  # noqa C901 too complex
    """
    Given a url_name and a user, this function tries to assess whether the
    user has the right to access the URL.
    The application instance of the view is fetched via the Django app
    registry.
    Once the permissions for the view are known, the access logic used
    by the dashboard decorator is evaluated

    This function might seem costly, but a simple comparison with DTT
    did not show any change in response time
    """
    if url_name is None:  # it's a heading
        return True

    # get view module string.
    try:
        url = reverse(url_name, args=url_args, kwargs=url_kwargs)
    except NoReverseMatch:
        # In Oscar 1.5 this exception was silently ignored which made debugging
        # very difficult. Now it is being logged and in future the exception will
        # be propagated.
        logger.exception('Invalid URL name {}'.format(url_name))
        return False

    view_module = resolve(url).func.__module__

    # We can't assume that the view has the same parent module as the app
    # config, as either the app config or view can be customised. So we first
    # look it up in the app registry using "get_containing_app_config", and if
    # it isn't found, then we walk up the package tree, looking for an
    # OscarDashboardConfig class, from which we get an app label, and use that
    # to look it up again in the app registry using "get_app_config".
    app_config_instance = apps.get_containing_app_config(view_module)
    if app_config_instance is None:
        try:
            app_config_class = get_app_config_class(view_module)
        except AppNotFoundError:
            raise ImproperlyConfigured(
                "Please provide an OscarDashboardConfig subclass in the apps "
                "module or set a custom access_fn")
        if hasattr(app_config_class, 'label'):
            app_label = app_config_class.label
        else:
            app_label = app_config_class.name.rpartition('.')[2]
        try:
            app_config_instance = apps.get_app_config(app_label)
        except LookupError:
            raise AppNotFoundError(
                "Couldn't find an app with the label %s" % app_label)
        if not isinstance(app_config_instance, OscarDashboardConfig):
            raise AppNotFoundError(
                "Couldn't find an Oscar Dashboard app with the label %s" % app_label)

    # handle name-spaced view names
    if ':' in url_name:
        view_name = url_name.split(':')[1]
    else:
        view_name = url_name
    permissions = app_config_instance.get_permissions(view_name)
    return check_permissions(user, permissions)
Ejemplo n.º 15
0
def default_access_fn(user, url_name, url_args=None, url_kwargs=None):
    """
    Given a url_name and a user, this function tries to assess whether the
    user has the right to access the URL.
    The application instance of the view is fetched via dynamic imports,
    and those assumptions will only hold true if the standard Oscar layout
    is followed.
    Once the permissions for the view are known, the access logic used
    by the dashboard decorator is evaluated

    This function might seem costly, but a simple comparison with DTT
    did not show any change in response time

    给定url_name和用户,此函数尝试评估用户是否有权访问URL。

    视图的应用程序实例是通过动态导入获取的,只有遵循标准的Oscar布局,这些假设才会成立。

    一旦知道了视图的权限,就会评估仪表板装饰器使用的访问逻辑

    此功能可能看起来很昂贵,但与DTT的简单比较并未显示响应时间的任何变化
    """
    exception = ImproperlyConfigured(
        "Please follow Oscar's default dashboard app layout or set a "
        "custom access_fn")
    # 请遵循Oscar的默认仪表板应用布局或设置自定义access_fn
    if url_name is None:  # it's a heading  这是一个标题
        return True

    # get view module string. 获取视图模块字符串。
    try:
        url = reverse(url_name, args=url_args, kwargs=url_kwargs)
    except NoReverseMatch:
        # In Oscar 1.5 this exception was silently ignored which made debugging
        # very difficult. Now it is being logged and in future the exception will
        # be propagated.
        # 在Oscar 1.5中,这个异常被忽略了,这使调试变得非常困难。 现在它正在被记录,将来会传播异常。
        logger.exception('Invalid URL name {}'.format(url_name))
        return False

    view_module = resolve(url).func.__module__

    # We can't assume that the view has the same parent module as the app,
    # as either the app or view can be customised. So we turn the module
    # string (e.g. 'oscar.apps.dashboard.catalogue.views') into an app
    # label that can be loaded by get_class (e.g.
    # 'dashboard.catalogue.app), which then essentially checks
    # INSTALLED_APPS for the right module to load
    # 我们不能假设视图与应用程序具有相同的父模块,因为可以自定义应用程序或视图。
    #  因此,我们将模块字符串(例如'oscar.apps.dashboard.catalogue.views')转换为可
    # 由get_class(eg'dashboard.catalogue.app)加载的应用程序标签,然后基本上
    # 将INSTALLED_APPS检查为正确的模块 加载
    match = re.search('(dashboard[\w\.]*)\.views$', view_module)
    if not match:
        raise exception
    app_label_str = match.groups()[0] + '.app'

    try:
        app_instance = get_class(app_label_str, 'application')
    except AppNotFoundError:
        raise exception

    # handle name-spaced view names 处理名称间隔的视图名称
    if ':' in url_name:
        view_name = url_name.split(':')[1]
    else:
        view_name = url_name
    permissions = app_instance.get_permissions(view_name)
    return check_permissions(user, permissions)
Ejemplo n.º 16
0
def default_access_fn(user,
                      url_name,
                      url_args=None,
                      url_kwargs=None):  # noqa C901 too complex
    """
    Given a url_name and a user, this function tries to assess whether the
    user has the right to access the URL.
    The application instance of the view is fetched via the Django app
    registry.
    Once the permissions for the view are known, the access logic used
    by the dashboard decorator is evaluated

    This function might seem costly, but a simple comparison with DTT
    did not show any change in response time
    """
    if url_name is None:  # it's a heading
        return True

    # get view module string.
    try:
        url = reverse(url_name, args=url_args, kwargs=url_kwargs)
    except NoReverseMatch:
        # In Oscar 1.5 this exception was silently ignored which made debugging
        # very difficult. Now it is being logged and in future the exception will
        # be propagated.
        logger.exception('Invalid URL name {}'.format(url_name))
        return False

    view_module = resolve(url).func.__module__

    # We can't assume that the view has the same parent module as the app
    # config, as either the app config or view can be customised. So we first
    # look it up in the app registry using "get_containing_app_config", and if
    # it isn't found, then we walk up the package tree, looking for an
    # OscarDashboardConfig class, from which we get an app label, and use that
    # to look it up again in the app registry using "get_app_config".
    app_config_instance = apps.get_containing_app_config(view_module)
    if app_config_instance is None:
        try:
            app_config_class = get_app_config_class(view_module)
        except AppNotFoundError:
            raise ImproperlyConfigured(
                "Please provide an OscarDashboardConfig subclass in the apps "
                "module or set a custom access_fn")
        if hasattr(app_config_class, 'label'):
            app_label = app_config_class.label
        else:
            app_label = app_config_class.name.rpartition('.')[2]
        try:
            app_config_instance = apps.get_app_config(app_label)
        except LookupError:
            raise AppNotFoundError("Couldn't find an app with the label %s" %
                                   app_label)
        if not isinstance(app_config_instance, OscarDashboardConfig):
            raise AppNotFoundError(
                "Couldn't find an Oscar Dashboard app with the label %s" %
                app_label)

    # handle name-spaced view names
    if ':' in url_name:
        view_name = url_name.split(':')[1]
    else:
        view_name = url_name
    permissions = app_config_instance.get_permissions(view_name)
    return check_permissions(user, permissions)
Ejemplo n.º 17
0
 def test_empty_permissions_passes(self):
     user = factories.UserFactory.build()
     self.assertTrue(check_permissions(user, []))
Ejemplo n.º 18
0
 def test_properties_are_checked(self):
     staff_user = factories.UserFactory.build(is_staff=True)
     non_staff_user = factories.UserFactory.build(is_staff=False)
     self.assertTrue(check_permissions(staff_user, ['is_staff']))
     self.assertFalse(check_permissions(non_staff_user, ['is_staff']))