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

Last change on this file since 7177 was 7177, checked in by Henrik Bettermann, 13 years ago

Role back some changes made earlier: global and local role strings with html tags should be better constructed in view not in permission module.

Rename some role related methods to avoid (my) confusion.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 7.5 KB
Line 
1import grok
2from zope.component import getUtilitiesFor
3from zope.interface import Interface
4from zope.securitypolicy.interfaces import IRole, IPrincipalRoleMap
5from waeup.sirp.interfaces import ILocalRolesAssignable
6from waeup.sirp.utils.helpers import get_user_account
7
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')
19
20class Anonymous(grok.Permission):
21    """Only-anonymous-can-do-this-permission.
22    """
23    grok.name('waeup.Anonymous')
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')
33
34class EditUser(grok.Permission):
35    grok.name('waeup.editUser')
36
37class ManageDataCenter(grok.Permission):
38    grok.name('waeup.manageDataCenter')
39
40class ManagePortalConfiguration(grok.Permission):
41    grok.name('waeup.managePortalConfiguration')
42
43# Local Roles
44class DepartmentOfficer(grok.Role):
45    grok.name('waeup.local.DepartmentOfficer')
46    grok.title(u'Department Officer')
47    grok.permissions('waeup.manageUniversity')
48
49
50class ClearanceOfficer(grok.Role):
51    """The clearance officer role is meant for the
52    assignment of dynamic roles only.
53    """
54    grok.name('waeup.local.ClearanceOfficer')
55    grok.title(u'Clearance Officer')
56
57class CourseAdviser(grok.Role):
58    """The course adviser role is meant for the
59    assignment of dynamic roles only.
60    """
61    grok.name('waeup.local.CourseAdviser')
62    grok.title(u'Course Adviser')
63
64class Owner(grok.Role):
65    grok.name('waeup.local.Owner')
66    grok.title(u'Owner')
67    grok.permissions('waeup.editUser')
68
69# Global Roles
70class PortalUser(grok.Role):
71    grok.name('waeup.PortalUser')
72    grok.title(u'Portal User')
73    grok.permissions('waeup.View', 'waeup.Public')
74
75class PortalManager(grok.Role):
76    grok.name('waeup.PortalManager')
77    grok.title(u'Portal Manager')
78    grok.permissions('waeup.manageUniversity', 'waeup.manageUsers',
79                     'waeup.View', 'waeup.Public','waeup.manageACBatches',
80                     'waeup.manageDataCenter','waeup.managePortalSettings',
81                     'waeup.managePortalConfiguration',
82                     'waeup.manageApplications', 'waeup.handleApplication',
83                     'waeup.viewStudent', 'waeup.manageStudent', 'clearStudent',
84                     'waeup.uploadStudentFile',
85                     'waeup.viewHostels', 'waeup.manageHostels')
86
87def getAllRoles():
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 getAllRoles():
105        if not name.startswith('waeup.'):
106            # Ignore non-WAeUP roles...
107            continue
108        if not also_local and name.startswith('waeup.local.'):
109            # Ignore local roles...
110            continue
111        yield item
112
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
122#def 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(getAllRoles())[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
137
138#def 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(getAllRoles())[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
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
171    setting a (preferably class-) attribute to a list of role ids.
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
184        role_ids = getattr(context, 'local_roles', self._roles)
185        self._roles = [(name, role) for name, role in getAllRoles()
186                       if name in role_ids]
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        """
194        return [
195            dict(
196                name=name,
197                title=role.title,
198                description=role.description)
199            for name, role in self._roles]
200
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    """
208    try:
209        role_map = IPrincipalRoleMap(context)
210    except TypeError:
211        # no map no roles.
212        raise StopIteration
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)
216        local_role_title = dict(getAllRoles())[local_role].title
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.