File: DelegatingMultiPlugin.py

package info (click to toggle)
zope-pas 1.4-1
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 1,084 kB
  • ctags: 1,205
  • sloc: python: 9,373; xml: 348; makefile: 31; sh: 2
file content (262 lines) | stat: -rw-r--r-- 8,722 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
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights
# Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL).  A copy of the ZPL should accompany this
# distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
""" DelegatingMultiPlugin   Shim to use any User Folder with the
                            PluggableAuthenticationService
"""

__doc__     = """ Delegating User Folder shim module """
__version__ = '$Revision: 40169 $'[11:-2]

# General Python imports
import copy, os
from urllib import quote_plus

# Zope imports
from Acquisition import aq_base
from OFS.Folder import Folder
from Globals import InitializeClass
from AccessControl import ClassSecurityInfo
from AccessControl.SpecialUsers import emergency_user
from Products.PageTemplates.PageTemplateFile import PageTemplateFile

from Products.PluggableAuthService.interfaces.plugins import \
    IAuthenticationPlugin
from Products.PluggableAuthService.interfaces.plugins import \
    IUserEnumerationPlugin
from Products.PluggableAuthService.interfaces.plugins import \
    IRolesPlugin
from Products.PluggableAuthService.interfaces.plugins import \
    ICredentialsUpdatePlugin
from Products.PluggableAuthService.interfaces.plugins import \
    ICredentialsResetPlugin
from Products.PluggableAuthService.interfaces.plugins import \
    IPropertiesPlugin
from Products.PluggableAuthService.plugins.BasePlugin import BasePlugin
from Products.PluggableAuthService.utils import classImplements
from Products.PluggableAuthService.utils import Interface

class IDelegatingMultiPlugin(Interface):
    """ Marker interface.
    """

manage_addDelegatingMultiPluginForm = PageTemplateFile(
    'www/dmpAdd', globals(), __name__='manage_addDelegatingMultiPluginForm' )


def manage_addDelegatingMultiPlugin( self
                                   , id
                                   , title=''
                                   , delegate_path=''
                                   , REQUEST=None
                                   ):
    """ Factory method to instantiate a DelegatingMultiPlugin """
    # Make sure we really are working in our container (the 
    # PluggableAuthService object)
    self = self.this()

    # Instantiate the folderish adapter object
    lmp = DelegatingMultiPlugin( id, title=title
                               , delegate_path=delegate_path )
    self._setObject(id, lmp)

    if REQUEST is not None:
        REQUEST.RESPONSE.redirect('%s/manage_main' % self.absolute_url())



class DelegatingMultiPlugin(Folder, BasePlugin):
    """ The adapter that mediates between the PAS and the DelegatingUserFolder
    """
    security = ClassSecurityInfo()
    meta_type = 'Delegating Multi Plugin'

    manage_options = ( BasePlugin.manage_options[:1]
                     + Folder.manage_options
                     )

    _properties = ( { 'id' : 'delegate'
                    , 'label' : ' Delegate Path'
                    , 'type' : 'string'
                    , 'mode' : 'w'
                    }
                  ,
                  )

    def __init__(self, id, title='', delegate_path=''):
        """ Initialize a new instance """
        self.id = id
        self.title = title
        self.delegate = delegate_path


    security.declarePrivate('_getUserFolder')
    def _getUserFolder(self):
        """ Safely retrieve a User Folder to work with """
        uf = getattr(aq_base(self), 'acl_users', None)

        if uf is None and self.delegate:
            uf = self.unrestrictedTraverse(self.delegate)

        return uf


    security.declarePrivate('authenticateCredentials')
    def authenticateCredentials(self, credentials):
        """ Fulfill AuthenticationPlugin requirements """
        acl = self._getUserFolder()
        login = credentials.get('login', '')
        password = credentials.get('password', '')

        if not acl or not login or not password:
            return (None, None)

        if login == emergency_user.getUserName():
            return ( login, login )

        user = acl.getUser(login)
        if user is None:
            return (None, None)
        elif user and user._getPassword() == password:
            return ( user.getId(), login )
            
        return (None, None)


    security.declarePrivate('updateCredentials')
    def updateCredentials(self, request, response, login, new_password):
        """ Fulfill CredentialsUpdatePlugin requirements """
        # Need to at least remove user from cache
        pass


    security.declarePrivate('resetCredentials')
    def resetCredentials(self, request, response):
        """ Fulfill CredentialsResetPlugin requirements """
        # Remove user from cache?
        pass


    security.declarePrivate('getPropertiesForUser')
    def getPropertiesForUser(self, user, request=None):
        """ Fullfill PropertiesPlugin requirements """
        acl = self._getUserFolder()

        if acl is None:
            return {}

        user = acl.getUserById(user.getId())

        if user is None:
            return {}

        # XXX WAAA
        return copy.deepcopy(user.__dict__)


    security.declarePrivate('getRolesForPrincipal')
    def getRolesForPrincipal(self, user, request=None):
        """ Fullfill RolesPlugin requirements """
        acl = self._getUserFolder()

        if acl is None:
            return ()

        user = acl.getUserById(user.getId())

        if user is None:
            return ()

        return tuple(user.getRoles())


    security.declarePrivate('enumerateUsers')
    def enumerateUsers( self
                      , id=None
                      , login=None
                      , exact_match=0
                      , sort_by=None
                      , max_results=None
                      , **kw
                      ):
        """ Fulfill the EnumerationPlugin requirements """
        result = []
        acl = self._getUserFolder()
        plugin_id = self.getId()
        edit_url = '%s/%s/manage_userrecords' % (plugin_id, acl.getId())

        if acl is None:
            return ()

        if exact_match:
            if id:
                user = acl.getUserById(id)
            elif login:
                user = acl.getUser(login)
            else:
                msg = 'Exact Match specified but no ID or Login given'
                raise ValueError, msg

            if user is not None:
                result.append( { 'id' : user.getId()
                               , 'login' : user.getUserName()
                               , 'pluginid' : plugin_id
                               , 'editurl' : '%s' % edit_url
                               } ) 
        else:
            l_results = []
            seen = []
            # XXX WAAAAA!!!!
            all_users = acl.getUsers()

            for user in all_users:
                if id:
                    if user.getId().find(id) != -1:
                        result.append( { 'login' : user.getUserName()
                                       , 'id' : user.getId()
                                       , 'pluginid' : plugin_id
                                       } )
                elif login:
                    if user.getUserName().find(login) != -1:
                        result.append( { 'login' : user.getUserName()
                                       , 'id' : user.getId()
                                       , 'pluginid' : plugin_id
                                       } )

            if sort_by is not None:
                result.sort(lambda a, b: cmp( a.get(sort_by, '').lower()
                                            , b.get(sort_by, '').lower()
                                            ) )

            if max_results is not None:
                try:
                    max_results = int(max_results)
                    result = result[:max_results+1]
                except ValueError:
                    pass

        return tuple(result)

classImplements( DelegatingMultiPlugin
               , IDelegatingMultiPlugin
               , IAuthenticationPlugin
               , IUserEnumerationPlugin
               , IRolesPlugin
               , ICredentialsUpdatePlugin
               , ICredentialsResetPlugin
               , IPropertiesPlugin
               )


InitializeClass(DelegatingMultiPlugin)