File: LDAPGroupFolder.py

package info (click to toggle)
zope-groupuserfolder 3.1.1-3
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 1,416 kB
  • ctags: 1,037
  • sloc: python: 6,755; sh: 1,365; makefile: 147
file content (348 lines) | stat: -rw-r--r-- 12,397 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
import time, traceback

# Zope imports
from Globals import DTMLFile, InitializeClass
from Acquisition import aq_base
from AccessControl import ClassSecurityInfo
from AccessControl.User import SimpleUser
from AccessControl.Permissions import view_management_screens, manage_users
from OFS.SimpleItem import SimpleItem
from DateTime import DateTime

import GroupUserFolder

from global_symbols import *

# LDAPUserFolder package imports
from Products.LDAPUserFolder.SimpleCache import SimpleCache

addLDAPGroupFolderForm = DTMLFile('dtml/addLDAPGroupFolder', globals())


class LDAPGroupFolder(SimpleItem):
    """ """
    security = ClassSecurityInfo()

    meta_type = 'LDAPGroupFolder'
    id = 'acl_users'

    isPrincipiaFolderish=1
    isAUserFolder=1

    manage_options=(
        ({'label' : 'Groups', 'action' : 'manage_main',},)
        + SimpleItem.manage_options
        )

    security.declareProtected(view_management_screens, 'manage_main')
    manage_main = DTMLFile('dtml/groups', globals())
    
    
    def __setstate__(self, v):
        """ """
        LDAPGroupFolder.inheritedAttribute('__setstate__')(self, v)

        self._cache = SimpleCache()
        self._cache.setTimeout(600)
        self._cache.clear()

    def __init__( self, title, luf=''):
        """ """
        self._luf = luf
        self._cache = SimpleCache()
        self._cache.setTimeout(600)
        self._cache.clear()

    security.declarePrivate(manage_users, 'getGRUF')
    def getGRUF(self):
        """ """
        return self.aq_parent.aq_parent


    security.declareProtected(manage_users, 'getLUF')
    def getLUF(self):
        """ """
        s = self.getGRUF().getUserSource(self._luf)
        if getattr(s, 'meta_type', None) != "LDAPUserFolder":
            # whoops, we moved LDAPUF... let's try to find it back
            Log(LOG_WARNING, "LDAPUserFolder moved. Trying to find it back.")
            s = None
            for src in self.getGRUF().listUserSources():
                if src.meta_type == "LDAPUserFolder":
                    self._luf = src.getPhysicalPath()[-2]
                    s = src
                    break
            if not s:
                raise RuntimeError, "You must change your groups source in GRUF if you do not have a LDAPUserFolder as a users source."
        return s


    security.declareProtected(manage_users, 'getGroups')
    def getGroups(self, dn='*', attr=None, pwd=''):
        """ """
        return self.getLUF().getGroups(dn, attr, pwd)


    security.declareProtected(manage_users, 'getGroupType')
    def getGroupType(self, group_dn):
        """ """
        return self.getLUF().getGroupType(group_dn)

    security.declareProtected(manage_users, 'getGroupMappings')
    def getGroupMappings(self):
        """ """
        return self.getLUF().getGroupMappings()

    security.declareProtected(manage_users, 'manage_addGroupMapping')
    def manage_addGroupMapping(self, group_name, role_name, REQUEST=None):
        """ """
        self._cache.remove(group_name)
        self.getLUF().manage_addGroupMapping(group_name, role_name, None)

        if REQUEST:
            msg = 'Added LDAP group to Zope role mapping: %s -> %s' % (
                group_name, role_name)
            return self.manage_main(manage_tabs_message=msg)

    security.declareProtected(manage_users, 'manage_deleteGroupMappings')
    def manage_deleteGroupMappings(self, group_names, REQUEST=None):
        """ Delete mappings from LDAP group to Zope role """
        self._cache.clear()
        self.getLUF().manage_deleteGroupMappings(group_names, None)
        if REQUEST:
            msg = 'Deleted LDAP group to Zope role mapping for: %s' % (
                ', '.join(group_names))
            return self.manage_main(manage_tabs_message=msg)


    security.declareProtected(manage_users, 'manage_addGroup')
    def manage_addGroup( self
                       , newgroup_name
                       , newgroup_type='groupOfUniqueNames'
                       , REQUEST=None
                       ):
        """Add a new group in groups_base.
        """
        self.getLUF().manage_addGroup(newgroup_name, newgroup_type, None)
        
        if REQUEST:
            msg = 'Added new group %s' % (newgroup_name)
            return self.manage_main(manage_tabs_message=msg)


    security.declareProtected(manage_users, 'manage_deleteGroups')
    def manage_deleteGroups(self, dns=[], REQUEST=None):
        """ Delete groups from groups_base """
        self.getLUF().manage_deleteGroups(dns, None)
        self._cache.clear()
 
        if REQUEST:
            msg = 'Deleted group(s):<br> %s' % '<br>'.join(dns)
            return self.manage_main(manage_tabs_message=msg)

    security.declareProtected(manage_users, 'getUser')
    def getUser(self, name):
        """ """
        # Get the group from the cache
        user = self._cache.get(name, '')
        if user:
            return user

        # Scan groups to find the proper user.
        # THIS MAY BE EXPENSIVE AND HAS TO BE OPTIMIZED...
        grps = self.getLUF().getGroups()
        valid_roles = self.userFolderGetRoles()
        dn = None
        for n, g_dn in grps:
            if n == name:
                dn = g_dn
                break
        if not dn:
            return None

        # Current mapping
        roles = self.getLUF()._mapRoles([name])

        # Nested groups
        groups = list(self.getLUF().getGroups(dn=dn, attr='cn', ))
        roles.extend(self.getLUF()._mapRoles(groups))

        # !!! start test
        Log(LOG_DEBUG, name, "roles", groups, roles)
        Log(LOG_DEBUG, name, "mapping", getattr(self.getLUF(), '_groups_mappings', {}))
        # !!! end test

        actual_roles = []
        for r in roles:
            if r in valid_roles:
                actual_roles.append(r)
            elif "%s%s" % (GROUP_PREFIX, r) in valid_roles:
                actual_roles.append("%s%s" % (GROUP_PREFIX, r))
        Log(LOG_DEBUG, name, "actual roles", actual_roles)
        user = GroupUser(n, '', actual_roles, [])
        self._cache.set(name, user)
        return user
        
    security.declareProtected(manage_users, 'getUserNames')
    def getUserNames(self):
        """ """
        return [g[0] for g in self.getLUF().getGroups()]

    security.declareProtected(manage_users, 'getUsers')
    def getUsers(self, authenticated=1):
        """ """
        data = []
        
        grps = self.getLUF().getGroups()
        valid_roles = self.userFolderGetRoles()
        for n, dn in grps:
            # Group mapping
            roles = self.getLUF()._mapRoles([n])
            
            # nested groups
            groups = list(self.getLUF().getGroups(dn=dn, attr='cn', ))
            roles.extend(self.getLUF()._mapRoles(groups))

            # computation
            actual_roles = []
            for r in roles:
                if r in valid_roles:
                    actual_roles.append(r)
                elif "%s%s" % (GROUP_PREFIX, r) in valid_roles:
                    actual_roles.append("%s%s" % (GROUP_PREFIX, r))
            user = GroupUser(n, '', actual_roles, [])
            data.append(user)

        return data

    security.declarePrivate('_doAddUser')
    def _doAddUser(self, name, password, roles, domains, **kw):
        """WARNING: If a role with exists with the same name as the group, we do not add
        the group mapping for it, but we create it as if it were a Zope ROLE.
        Ie. it's not possible to have a GRUF Group name = a Zope role name, BUT,
        with this system, it's possible to differenciate between LDAP groups and LDAP roles.
        """
        self.getLUF().manage_addGroup(name)
        self._doChangeUser(name, password, roles, domains, **kw)

    security.declarePrivate('_doDelUsers')
    def _doDelUsers(self, names):
        dns = []
        luf = self.getLUF()
        for g_name, dn in luf.getGroups():
            if g_name in names:
                dns.append(dn)
        self._cache.clear()
        return luf.manage_deleteGroups(dns)

    security.declarePrivate('_doChangeUser')
    def _doChangeUser(self, name, password, roles, domains, **kw):
        """WARNING: If a role with exists with the same name as the group, we do not add
        the group mapping for it, but we create it as if it were a Zope ROLE.
        Ie. it's not possible to have a GRUF Group name = a Zope role name, BUT,
        with this system, it's possible to differenciate between LDAP groups and LDAP roles.
        """
        luf = self.getLUF()
        self._cache.remove(name)

        # Get group DN
        dn = None
        for g_name, g_dn in luf.getGroups():
            if g_name == name:
                dn = g_dn
                break
        if not dn:
            raise ValueError, "Invalid LDAP group: '%s'" % (name, )
                
        # Edit group mappings
##        if name in self.aq_parent.valid_roles():
##            # This is, in fact, a role
##            self.getLUF().manage_addGroupMapping(name, name)
##        else:
##            # This is a group -> we set it as a group
##            self.getLUF().manage_addGroupMapping(name, self.getGroupPrefix() + name)

        # Change roles
        if luf._local_groups:
            luf.manage_editUserRoles(dn, roles)
        else:
            # We have to transform roles into group dns: transform them as a dict
            role_dns = []
            all_groups = luf.getGroups()
            all_roles = luf.valid_roles()
            groups = {}
            for g in all_groups:
                groups[g[0]] = g[1]

            # LDAPUF < 2.4Beta3 adds possibly invalid roles to the user roles
            # (for example, adding the cn of a group additionnaly to the mapped zope role).
            # So we must remove from our 'roles' list all roles which are prefixed by group prefix
            # but are not actually groups.
            # If a group has the same name as a role, we assume that it should be a _role_.
            # We should check against group/role mapping here, but... well... XXX TODO !
            # See "HERE IT IS" comment below.

            # Scan roles we are asking for to manage groups correctly
            for role in roles:
                if not role in all_roles:
                    continue                        # Do not allow propagation of invalid roles
                if role.startswith(GROUP_PREFIX):
                    role = role[GROUP_PREFIX_LEN:]            # Remove group prefix : groups are stored WITHOUT prefix in LDAP
                    if role in all_roles:
                        continue                            # HERE IT IS
                r = groups.get(role, None)
                if not r:
                    Log(LOG_WARNING, "LDAP Server doesn't provide a '%s' group (asked for user '%s')." % (role, name, ))
                    continue
                role_dns.append(r)

            # Perform the change
            luf.manage_editGroupRoles(dn, role_dns)



def manage_addLDAPGroupFolder( self, title = '', luf='', REQUEST=None):
    """ """
    this_folder = self.this()

    if hasattr(aq_base(this_folder), 'acl_users') and REQUEST is not None:
        msg = 'This+object+already+contains+a+User+Folder'

    else:
        # Try to guess where is LUF
        if not luf:
            for src in this_folder.listUserSources():
                if src.meta_type == "LDAPUserFolder":
                    luf = src.aq_parent.getId()

        # No LUF found : error
        if not luf:
            raise KeyError, "You must be within GRUF with a LDAPUserFolder as one of your user sources."
            
        n = LDAPGroupFolder( title, luf )

        this_folder._setObject('acl_users', n)
        this_folder.__allow_groups__ = self.acl_users
        
        msg = 'Added+LDAPGroupFolder'
 
    # return to the parent object's manage_main
    if REQUEST:
        url = REQUEST['URL1']
        qs = 'manage_tabs_message=%s' % msg
        REQUEST.RESPONSE.redirect('%s/manage_main?%s' % (url, qs))


InitializeClass(LDAPGroupFolder)


class GroupUser(SimpleUser):
    """ """

    def __init__(self, name, password, roles, domains):
        SimpleUser.__init__(self, name, password, roles, domains)
        self._created = time.time()

    def getCreationTime(self):
        """ """
        return DateTime(self._created)