We start by deciding what we want to protect.  For example, the ability to add or edit articles, or delete them, or the ability to backup and restore the database.  Then we visualise different roles for these functions.  For example, an Administrator may be able to back up and restore, while an Editor may be able to add, edit or delete articles.

To make things simple, we might just say that an Editor has access to the editing feature, while the Administrator's function is administering. Viewers may have the viewing function.

It is more natural to imagine that the Administrator role might have access to the administering, editing and viewing capabilities, while an Editor has access to both editing and viewing features.  A Viewer would only be capable of viewing

We can tell Grok what we want in the file called permissions.py:

import grok
from zope.schema.vocabulary import SimpleVocabulary
from zope.schema.interfaces import IVocabularyFactory

#_________________________________________________________________________________________
# Permissions defined
class Administering(grok.Permission):
    grok.name('gfn.administering')

class Authenticated(grok.Permission):
    grok.name('gfn.authenticated')

class Editing(grok.Permission):
    grok.name('gfn.editing')

class Viewing(grok.Permission):
    grok.name('gfn.viewing')

#_________________________________________________________________________________________
# Roles defined
class Administrator(grok.Role):
    grok.name('gfn.Administrator')
    grok.title(u'Administrator')
    grok.permissions(Authenticated, Administering, Editing, Viewing)

class Editor(grok.Role):
    grok.name('gfn.Editor')
    grok.title(u'Editor')
    grok.permissions(Authenticated, Editing, Viewing)

class Visitor(grok.Role):
    grok.name('gfn.Visitor')
    grok.title(u'Visitor')
    grok.permissions(Authenticated, Viewing)

At the end of permissions.py, we define a vocabulary which makes it easy for us to list the available roles:

#_________________________________________________________________________________________
# A vocabulary for our defined roles
class Roles(grok.GlobalUtility):
    grok.name('gfn.AccountRoles')
    grok.implements(IVocabularyFactory)

    def __call__(self, context):
        terms = []
        for role in [Administrator, Editor, Visitor]:
            name  = role.__dict__['grokcore.component.directive.name']
            title = role.__dict__['grokcore.component.directive.title']
            terms.append(SimpleVocabulary.createTerm(name, name, title))
        return SimpleVocabulary(terms)

This vocabulary can also be used as the source for automatic forms components, as we will see later on.

 

Grok 4 Noobs

Defining Permissions