If a user doesn't have permission to render a View (configured on configure.zcml), how do I raise Forbidden instead of redirecting to login_form?

亡梦爱人 提交于 2020-01-05 07:25:48

问题


I have a browser view, with some utilities. Is mainly an "utility view" that I traverse using old-style pt templates (that are inside skins folder). My browser/configure.zcml:

  <browser:page
      for="*"
      name="my_view"
      class=".myview.MyView"
      allowed_interface=".myview.IMyView"
      permission="my.permission"
      />

As you can see, it has a custom permission: this is needed because anonymous users can't render this view and this permission is really specific to a certain situation in my portal.

I thought: I'm going to try to render the view in my template.pt: since I've already set a permission in browser/configure.zcml, when trying to render Plone itself is going to handle this for me. So I did in my template

    <span tal:define="my_view here/@@myview">
    </span>

So far, so good. A user without my.permission trying to get into /Plone/template.pt will fail. But Plone redirects to the login form, and I would prefer to raise a Forbidden exception instead. Something like:

    <span tal:define="my_view here/@@myview | here/raiseForbidden">
    </span>

...but, of course, this doesn't work since the view rendering didn't throw an error. (I know here/raiseForbidden doesn't exist, it's here/raiseUnauthorized that is usually used but the concept is the same)

My question is: is it possible to do it? Configuring my permission somewhere, or configuring some method in my view (like render or __call__), that when a user doesn't have permission to render it, an exception like Forbidden is raised?


回答1:


Plone redirects to the login form because you raise Unauthorized. If you want different behaviour you'll need to do something different.

In this case, you could directly redirect the user to a new page with an error message tailored to the situation.




回答2:


actually you don't need to do this:

"tal:define="my_view here/@@myview>"

because for browser views there's a default variable named "view" that already contain your class.

For raising an exception you should remove permission check from the zml directive and modify your class as below:

from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from AccessControl import getSecurityManager
from AccessControl import Unauthorized

class YourBrowserView(BrowserView):
    """ .. """
    index = ViewPageTemplateFile("templates/yourtemplate.pt")

    ...

    def __call__(self):
        if not getSecurityManager().checkPermission(your.permission, self.context):
            raise Unauthorized("You are not authorized! Go away!")
        else: return index()

Bye Giacomo



来源:https://stackoverflow.com/questions/6948507/if-a-user-doesnt-have-permission-to-render-a-view-configured-on-configure-zcml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!