source: main/waeup.sirp/trunk/src/waeup/sirp/permissions.py @ 7176

Last change on this file since 7176 was 7176, checked in by Henrik Bettermann, 14 years ago

Move getGlobalRolesForAccount and getLocalRolesForAccount to permissions.py (work in progress!)

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 7.5 KB
RevLine 
[3521]1import grok
[6157]2from zope.component import getUtilitiesFor
[6144]3from zope.interface import Interface
[6163]4from zope.securitypolicy.interfaces import IRole, IPrincipalRoleMap
[6144]5from waeup.sirp.interfaces import ILocalRolesAssignable
[7176]6from waeup.sirp.utils.helpers import get_user_account
[3521]7
[4789]8class Public(grok.Permission):
9    """Everyone-can-do-this-permission.
10
11    This permission is meant to be applied to objects/views/pages
12    etc., that should be usable/readable by everyone.
13
14    We need this to be able to tune default permissions more
15    restrictive and open up some dedicated objects like the front
16    page.
17    """
18    grok.name('waeup.Public')
[6142]19
[5433]20class Anonymous(grok.Permission):
21    """Only-anonymous-can-do-this-permission.
22    """
[6142]23    grok.name('waeup.Anonymous')
[4789]24
25class ViewPermission(grok.Permission):
26    grok.name('waeup.View')
27
28class ManageUniversity(grok.Permission):
29    grok.name('waeup.manageUniversity')
30
31class ManageUsers(grok.Permission):
32    grok.name('waeup.manageUsers')
[6142]33
[7163]34class EditUser(grok.Permission):
35    grok.name('waeup.editUser')
36
[6127]37class ManageDataCenter(grok.Permission):
38    grok.name('waeup.manageDataCenter')
[6142]39
[6907]40class ManagePortalConfiguration(grok.Permission):
41    grok.name('waeup.managePortalConfiguration')
[6155]42
[6125]43# Local Roles
44class DepartmentOfficer(grok.Role):
[6127]45    grok.name('waeup.local.DepartmentOfficer')
[6159]46    grok.title(u'Department Officer')
[7168]47    grok.permissions('waeup.manageUniversity')
[6142]48
[7168]49
[6655]50class ClearanceOfficer(grok.Role):
[7168]51    """The clearance officer role is meant for the
52    assignment of dynamic roles only.
53    """
[6655]54    grok.name('waeup.local.ClearanceOfficer')
55    grok.title(u'Clearance Officer')
56
57class CourseAdviser(grok.Role):
[7168]58    """The course adviser role is meant for the
59    assignment of dynamic roles only.
60    """
[6655]61    grok.name('waeup.local.CourseAdviser')
62    grok.title(u'Course Adviser')
63
[7163]64class Owner(grok.Role):
65    grok.name('waeup.local.Owner')
66    grok.title(u'Owner')
67    grok.permissions('waeup.editUser')
68
[6125]69# Global Roles
[4789]70class PortalUser(grok.Role):
71    grok.name('waeup.PortalUser')
[6159]72    grok.title(u'Portal User')
[6125]73    grok.permissions('waeup.View', 'waeup.Public')
[3521]74
[4789]75class PortalManager(grok.Role):
76    grok.name('waeup.PortalManager')
[6159]77    grok.title(u'Portal Manager')
[4789]78    grok.permissions('waeup.manageUniversity', 'waeup.manageUsers',
[6127]79                     'waeup.View', 'waeup.Public','waeup.manageACBatches',
[6198]80                     'waeup.manageDataCenter','waeup.managePortalSettings',
[6907]81                     'waeup.managePortalConfiguration',
[6622]82                     'waeup.manageApplications', 'waeup.handleApplication',
[7148]83                     'waeup.viewStudent', 'waeup.manageStudent', 'clearStudent',
84                     'waeup.uploadStudentFile',
[7122]85                     'waeup.viewHostels', 'waeup.manageHostels')
[4789]86
87def getRoles():
[6157]88    """Return a list of tuples ``<ROLE-NAME>, <ROLE>``.
89    """
90    return getUtilitiesFor(IRole)
91
92def getWAeUPRoles(also_local=False):
93    """Get all WAeUP roles.
94
95    WAeUP roles are ordinary roles whose id by convention starts with
96    a ``waeup.`` prefix.
97
98    If `also_local` is ``True`` (``False`` by default), also local
99    roles are returned. Local WAeUP roles are such whose id starts
100    with ``waeup.local.`` prefix (this is also a convention).
101
102    Returns a generator of the found roles.
103    """
104    for name, item in getRoles():
105        if not name.startswith('waeup.'):
[4789]106            # Ignore non-WAeUP roles...
107            continue
[6157]108        if not also_local and name.startswith('waeup.local.'):
109            # Ignore local roles...
[6045]110            continue
[6157]111        yield item
[4789]112
[6157]113def getWAeUPRoleNames():
114    """Get the ids of all WAeUP roles.
115
116    See :func:`getWAeUPRoles` for what a 'WAeUPRole' is.
117
118    This function returns a sorted list of WAeUP role names.
119    """
120    return sorted([x.id for x in getWAeUPRoles()])
121
[7176]122def getLocalRolesForAccount(view, account):
123    """Return HTML tagged string with all local roles of a user account.
124    """
125    local_roles = account.getLocalRoles()
126    local_roles_string = ''
127    site_url = view.url(grok.getSite())
128    for local_role in local_roles.keys():
129        role_title = dict(getRoles())[local_role].title
130        objects_string = ''
131        for object in local_roles[local_role]:
132            objects_string += '<a href="%s">%s</a>, ' %(view.url(object),
133                view.url(object).replace(site_url,''))
134        local_roles_string += '%s: <br />%s <br />' %(role_title,
135            objects_string.rstrip(', '))
136    return local_roles_string
[6157]137
[7176]138def getGlobalRolesForAccount(account):
139    """Return HTML tagged string with all global roles of a user account.
140    """
141    global_roles = account.roles
142    global_roles_string = ''
143    for global_role in global_roles:
144        role_title = dict(getRoles())[global_role].title
145        global_roles_string += '%s <br />' % role_title
146    return global_roles_string
147
148def getMyRoles(view):
149    account = get_user_account(view.request)
150    if account:
151        global_roles = getGlobalRoles(account)
152        local_roles = getLocalRoles(account)
153        return [global_roles,local_roles]
154    return
155
156
[6144]157class LocalRolesAssignable(grok.Adapter):
158    """Default implementation for `ILocalRolesAssignable`.
159
160    This adapter returns a list for dictionaries for objects for which
161    we want to know the roles assignable to them locally.
162
163    The returned dicts contain a ``name`` and a ``title`` entry which
164    give a role (``name``) and a description, for which kind of users
165    the permission is meant to be used (``title``).
166
167    Having this adapter registered we make sure, that for each normal
168    object we get a valid `ILocalRolesAssignable` adapter.
169
170    Objects that want to offer certain local roles, can do so by
[6162]171    setting a (preferably class-) attribute to a list of role ids.
[6144]172
173    You can also define different adapters for different contexts to
174    have different role lookup mechanisms become available. But in
175    normal cases it should be sufficient to use this basic adapter.
176    """
177    grok.context(Interface)
178    grok.provides(ILocalRolesAssignable)
179
180    _roles = []
181
182    def __init__(self, context):
183        self.context = context
[6162]184        role_ids = getattr(context, 'local_roles', self._roles)
185        self._roles = [(name, role) for name, role in getRoles()
186                       if name in role_ids]
[6144]187        return
188
189    def __call__(self):
190        """Get a list of dictionaries containing ``names`` (the roles to
191        assign) and ``titles`` (some description of the type of user
192        to assign each role to).
193        """
[6162]194        return [
195            dict(
196                name=name,
197                title=role.title,
[6163]198                description=role.description)
[6162]199            for name, role in self._roles]
[6144]200
[6163]201def get_users_with_local_roles(context):
202    """Get a list of dicts representing the local roles set for `context`.
203
204    Each dict returns `user_name`, `user_title`, `local_role`,
205    `local_role_title`, and `setting` for each entry in the local
206    roles map of the `context` object.
207    """
[6202]208    try:
209        role_map = IPrincipalRoleMap(context)
210    except TypeError:
211        # no map no roles.
212        raise StopIteration
[6163]213    for local_role, user_name, setting in role_map.getPrincipalsAndRoles():
214        user = grok.getSite()['users'].get(user_name,None)
215        user_title = getattr(user, 'description', user_name)
[6170]216        local_role_title = dict(getRoles())[local_role].title
[6163]217        yield dict(user_name = user_name,
218                   user_title = user_title,
219                   local_role = local_role,
220                   local_role_title = local_role_title,
221                   setting = setting)
Note: See TracBrowser for help on using the repository browser.