Logo Search packages:      
Sourcecode: zope-cmfldap version File versions

LDAPMemberDataTool.py

#####################################################################
#
# LDAPMemberDataTool       LDAP-enabled CMF Memberdata Tool
#
# This software is governed by a license. See
# LICENSE.txt for the terms of this license.
#
#####################################################################
__version__='$Revision: 1.22 $'[11:-2]


from Products.CMFCore.utils import getToolByName
from Products.CMFCore.CMFCorePermissions import View
from Globals import InitializeClass, DTMLFile
from Acquisition import aq_base
from AccessControl import ClassSecurityInfo
from Products.CMFCore.MemberDataTool import MemberDataTool, MemberData

_marker = []


00022 class LDAPMemberDataTool(MemberDataTool):
    """ This tool wraps user objects, making them act as Member objects. """
    security = ClassSecurityInfo()
    meta_type = 'LDAP Member Data Tool'
    title = 'LDAP Member Data Tool'
    manage_showContents = DTMLFile('dtml/memberdataContents', globals())


    def __init__(self, id='portal_memberdata'):
        self.id = id
        MemberDataTool.__init__(self)


00035     def wrapUser(self, u):
        """
        If possible, returns the Member object that corresponds
        to the given User object.
        """
        id = u.getUserName()
        members = self._members

        if not members.has_key(id):
            # Get a temporary member that might be
            # registered later via registerMemberData().
            temps = self._v_temps

            if temps is not None and temps.has_key(id):
                m = temps[id]
            else:
                base = aq_base(self)
                m    = LDAPMemberData(base, id)

                if temps is None:
                    self._v_temps = { id : m }
                else:
                    temps[id] = m
        else:
            m = members[id]

        wrapper = m.__of__(self).__of__(u)
        # We set the MemberData global options if we found values
        # in the UserData. (for instance the 'email')
        try:
            global mapped_attrs
            mapped_attrs = self.acl_users.getMappedUserAttrs()

            for MappedUserAttr in mapped_attrs:
                try:
                    # get the property value from LDAPUser object, if it is 
                    # empty then the method will raise an exception
                    PropertyValue = u.getProperty(MappedUserAttr[1])
                    # now read the value from the wrapper
                    WrapperPropertyValue = wrapper.getProperty(MappedUserAttr[1])
                    # redefine the wrapper value if it differ
                    if ( PropertyValue is not None and 
                         PropertyValue != '' and 
                         PropertyValue != WrapperPropertyValue ):
                        setattr(wrapper, MappedUserAttr[1], PropertyValue)
                except:
                    # the exception may be thrown if PropertyValue is empty
                    pass
        except:
            pass

        # Return a wrapper with self as containment and
        # the user as context.
        return wrapper


00091     def getMemberDataContents(self):
        """
        Return the number of members stored in the _members
        BTree and some other useful info
        """
        membertool = getToolByName(self, 'portal_membership')
        members = self._members
        temps = self._v_temps
        user_list = membertool.listMemberIds()
        member_list = members.keys()
        member_count = len(members)
        orphan_count = 0
        member_temp_count = 0
 
        if (len(user_list) == 1):
            # Possible LDAP Error?
            res_str = user_list[0].lower()
            if res_str.find('error') != -1:
                msg = 'No or too many results returned from LDAP'

                return [ { 'member_count' : member_count
                         , 'orphan_count' : msg
                         } ]

        for member in member_list:
            if member not in user_list:
                orphan_count = orphan_count + 1
 
        if temps is not None:
            member_temp_count=len(temps.keys())

        return [ { 'member_count' : member_count
                 , 'orphan_count' : orphan_count 
                 , 'member_temp_count' : member_temp_count
                 } ]
 

    security.declareProtected(View, 'getMemberProps')
00129     def getMemberProps(self):
        """
            Return a list of tuples with the property and a "friendly"
            name for it for any property that can be set on a user 
            object.
        """
        return self.acl_users.getLDAPSchema()


    security.declareProtected(View, 'getLoginAttribute')
00139     def getLoginAttribute(self):
        """ Get the attribute name used for login in LDAP """
        return self.acl_users.getProperty('_login_attr')


InitializeClass(LDAPMemberDataTool)


00147 class LDAPMemberData (MemberData):
    """ Member Data wrapper for the LDAP-driven Member Data Tool """

00150     def __init__(self, tool, id):
        """ class constructor """
        self.id = id
        # Make a temporary reference to the tool.
        # The reference will be removed by notifyModified().
        self._tool = tool


00158     def setMemberProperties(self, mapping):
        """ Sets the properties of the member.  """
        acl = self.acl_users
        ldap_schemakeys = [x[0] for x in acl.getLDAPSchema()]

        # back conversion of mapped attributes
        mapped_attrs = acl.getMappedUserAttrs()
        for mapped_attr in mapped_attrs:
            if ( not mapping.has_key(mapped_attr[0]) 
                 and mapping.has_key(mapped_attr[1]) ):
                mapping.set( mapped_attr[0]
                           , mapping[mapped_attr[1]]
                           )
        
        change_vals = filter( None
                            , map( lambda x, lsk=ldap_schemakeys: x in lsk
                                 , mapping.keys()
                                 )
                            )

        try:
            if change_vals:
                user_obj = self.getUser()
                dn = user_obj.getUserDN()
                rdn_attr = acl.getProperty('_rdnattr')

                if not mapping.has_key(rdn_attr):
                    mapping.set( rdn_attr
                               , user_obj.getUserName()
                               )

                acl.manage_editUser(dn, kwargs=mapping)
                user_obj._expire()
        except:
            pass

        # To be on the safe side...
        wrapper_keys = self.__dict__.keys()
        for key in ldap_schemakeys:
            if mapping.has_key(key) and key in wrapper_keys:
                setattr(self, key, mapping[key])

        MemberData.setMemberProperties(self, mapping)
        

00203     def setSecurityProfile(self, password=None, roles=None, domains=None):
        """ Set the user's basic security profile """
        acl = self.acl_users
        u = self.getUser()
        user_dn = u.getUserDN()
        
        if password is not None:
            acl.manage_editUserPassword(user_dn, password)
            u.__ = password

        if roles is not None:
            all_roles = acl.getGroups()
            role_dns = []
            my_new_roles = []
            
            for role_name, role_dn in all_roles:
                if role_name in roles:
                    my_new_roles.append(role_name)
                    role_dns.append(role_dn)
                    
            u.roles = my_new_roles
            acl.manage_editUserRoles(user_dn, role_dns)

        if domains is not None:
            u.domains = domains


00230     def getPassword(self):
        """
            Retrieve the user's password if there is a valid record in the 
            user folder cache, otherwise create a new one and set it
            on the user object and in LDAP
        """
        user_obj = self.getUser()
        pwd = user_obj._getPassword()

        if pwd == 'undef':      # This user object did not result from a login
            reg_tool = getToolByName(self, 'portal_registration')
            pwd = reg_tool.generatePassword()
            self.setSecurityProfile(password=pwd)
            self.acl_users._expireUser(user_obj)

        return pwd

InitializeClass(LDAPMemberData)


def manage_addLDAPMemberDataTool(self, REQUEST=None):
    """ Add an LDAP-based MemberDataTool """
    tool_obj = LDAPMemberDataTool()
    self._setObject(tool_obj.id, tool_obj)
 
    if REQUEST is not None:
        return self.manage_main(self, REQUEST)



Generated by  Doxygen 1.6.0   Back to index