Search code examples
plonedexterity

How do I grant write permission to a field for anonymous users but not logged-in users?


In my dexterity form, I have a field "author" for anonymous to fill in, and without logged-in user.

I define a permission called "isAnonymous", and grant "isAnonymous" to Anonymous user,

I use dexterity.write_permission(author='isAnonymous'), like this:

dexterity.write_permission(author='isAnonymous')
author=schema.TextLine(
    title=_(u'Author'),
)

but, this method fails, even logged-in user can see this field.

In this page

http://docs.plone.org/develop/plone/security/standard_permissions.html

have a note:

if a permission is granted to Anonymous, it is effectively granted to everyone. It is not possible to grant permissions to non-logged in users without also granting them to logged in ones.

so, have any suggestion?


Solution

  • Afaik you cannot solve your problem with the security system. But you can customise the Dexterity add/edit form

    Then you have the full power :-) and you can implement a condition, which shows your field or not.

    Dexterity forms are based on z3c.forms and, so they features several methods, which you can override (super call and do your stuff).

    In your case the code may look like this.

    ...
    
    # I would recommend to use the `updateWidgets` method.
    
    def updateWidgets(self):
        super(CustomAddEditView, self).updateWidgets()
    
        from plone import api
        if not api.user.is_anonymous():
    
            from z3c.form.interfaces import HIDDEN_MODE
            self.widgets['author'].mode = HIDDEN_MODE
    
    
    ...
    

    More about hiding fields in the z3c.form Docu.