def test_manage_updateUserPassword_POST_permissions(self):
        USER_ID = 'testuser'
        PASSWORD = '******'
        ENCRYPTED = pw_encrypt(PASSWORD)

        zum = self._makeOne()
        zum.addUser(USER_ID, USER_ID, '')

        req, res = makeRequestAndResponse()
        # Fails with a GET
        req.set('REQUEST_METHOD', 'GET')
        req.set('method', 'GET')
        req.set('SESSION', {})
        self.assertRaises(Forbidden, zum.manage_updateUserPassword,
                          USER_ID, PASSWORD, PASSWORD, REQUEST=req)

        req.set('REQUEST_METHOD', 'POST')
        req.set('method', 'POST')
        self.assertRaises(Forbidden, zum.manage_updateUserPassword,
                          USER_ID, PASSWORD, PASSWORD, REQUEST=req)

        # Works with a POST + CSRF toekn
        req.form['csrf_token'] = 'deadbeef'
        req.SESSION['_csrft_'] = 'deadbeef'
        zum.manage_updateUserPassword(USER_ID, PASSWORD, PASSWORD, REQUEST=req)
示例#2
0
 def setPassword(self, value):
     """
     Set the password, only if the password is not empty.
   """
     if value is not None:
         self._setPassword(pw_encrypt(value))
         self.reindexObject()
示例#3
0
    def testPOSTProtections(self):
        from AccessControl.AuthEncoding import pw_encrypt
        from zExceptions import Forbidden
        USER_ID = 'testuser'
        PASSWORD = '******'

        ENCRYPTED = pw_encrypt(PASSWORD)

        zum = self._makeOne()
        zum.addUser(USER_ID, USER_ID, '')

        req, res = makeRequestAndResponse()
        # test manage_updateUserPassword
        # Fails with a GET
        req.set('REQUEST_METHOD', 'GET')
        self.assertRaises(Forbidden, zum.manage_updateUserPassword,
                          USER_ID, PASSWORD, PASSWORD, REQUEST=req)
        # Works with a POST
        req.set('REQUEST_METHOD', 'POST')
        zum.manage_updateUserPassword(USER_ID, PASSWORD, PASSWORD, REQUEST=req)

        # test manage_updatePassword
        req.set('REQUEST_METHOD', 'GET')
        self.assertRaises(Forbidden, zum.manage_updatePassword,
                          USER_ID, PASSWORD, PASSWORD, REQUEST=req)
        # XXX: This method is broken

        # test manage_removeUsers
        req.set('REQUEST_METHOD', 'GET')
        self.assertRaises(Forbidden, zum.manage_removeUsers,
                          [USER_ID], REQUEST=req)
        req.set('REQUEST_METHOD', 'POST')
        zum.manage_removeUsers([USER_ID], REQUEST=req)
示例#4
0
 def setPassword(self, value) :
   """
     Set the password, only if the password is not empty.
   """
   if value is not None :
     self._setPassword(pw_encrypt(value))
     self.reindexObject()
    def test_manage_removeUsers_POST_permissions(self):
        USER_ID = 'testuser'
        PASSWORD = '******'
        ENCRYPTED = pw_encrypt(PASSWORD)

        zum = self._makeOne()
        zum.addUser(USER_ID, USER_ID, '')

        req, res = makeRequestAndResponse()
        req.set('REQUEST_METHOD', 'GET')
        req.set('method', 'GET')
        req.set('SESSION', {})
        self.assertRaises(Forbidden,
                          zum.manage_removeUsers, [USER_ID],
                          REQUEST=req)

        req.set('REQUEST_METHOD', 'POST')
        req.set('method', 'POST')
        self.assertRaises(Forbidden,
                          zum.manage_removeUsers, [USER_ID],
                          REQUEST=req)

        req.form['csrf_token'] = 'deadbeef'
        req.SESSION['_csrft_'] = 'deadbeef'
        zum.manage_removeUsers([USER_ID], REQUEST=req)
示例#6
0
    def test_manage_updatePassword_POST_permissions(self):
        USER_ID = 'testuser'
        PASSWORD = '******'
        ENCRYPTED = pw_encrypt(PASSWORD)

        zum = self._makeOne()
        zum.addUser(USER_ID, USER_ID, '')

        req, res = makeRequestAndResponse()
        req.set('REQUEST_METHOD', 'GET')
        req.set('method', 'GET')
        self.assertRaises(Forbidden, zum.manage_updatePassword,
                          USER_ID, PASSWORD, PASSWORD, REQUEST=req)
示例#7
0
    def test_manage_updatePassword_POST_permissions(self):
        USER_ID = 'testuser'
        PASSWORD = '******'
        ENCRYPTED = pw_encrypt(PASSWORD)

        zum = self._makeOne()
        zum.addUser(USER_ID, USER_ID, '')

        req, res = makeRequestAndResponse()
        req.set('REQUEST_METHOD', 'GET')
        req.set('method', 'GET')
        self.assertRaises(Forbidden, zum.manage_updatePassword,
                          USER_ID, PASSWORD, PASSWORD, REQUEST=req)
    def test_addUser_with_preencrypted_password(self):
        # See collector #1869 && #1926
        USER_ID = 'already_encrypted'
        PASSWORD = '******'
        ENCRYPTED = pw_encrypt(PASSWORD)

        zum = self._makeOne()
        zum.addUser(USER_ID, USER_ID, ENCRYPTED)

        uid_and_info = zum.authenticateCredentials(
            {'login': USER_ID, 'password': PASSWORD
             })

        self.assertEqual(uid_and_info, (USER_ID, USER_ID))
示例#9
0
    def authenticate(self, password, request):
	"""try to authenticate the user"""
	if password in [None,'']:
	    return 0
	if not self.name:
	    return 0
	if pw_validate(self.__,password):
	    #print 'cashed auth!'
	    return 1
	try:
	    ld_user=ldap.open(self.domains[0])
	    ld_user.set_option(ldap.OPT_REFERRALS, 0)
	    ld_user.timelimit=10
	    #print 'try bind',fl(self.name+'@'+self.domains[1]),password
	    s=ld_user.simple_bind_s(fl(self.name+'@'+self.domains[1]),fl(password))
	    #print 'bind',s    
	    dn=fl('DC='+self.domains[1])
	    #print dn
	    fs=fl('(sAMAccountName='+self.name+')')
	    items=_clear( ld_user.search_s(dn,2,fs,['dn','sAMAccountName','memberOf']) )
	    if len(items) == 0 :
	      return 0
	    #s=ld_user.search_ext(dn,2,fs,['dn','sAMAccountName','memberOf'])
	    #items=ld_user.result(s,0)[1]
	    #print items
	    self.adroles=[]
	    roles=[]
	    try:
	      for role in items[0][1]['memberOf']:
		role=tl(role)
		r=role.split(',')[0].split('=')[1]
		if not r in ['Manager','Owner']:#Zope only roles!!
		    roles.append(r)
	      cn=items[0][0]
	      cnl=cn.split(',')
	      for cc in cnl[1:-1]:
		roles.append( tl(cc.split('=')[1]) )
	    except:
	      pass
	    self.adroles=roles
	    self.__=pw_encrypt(password, 'SSHA')
	    self.___=password
	    #print self.name,'auth success with adroles',
	    #for r in self.adroles:
		#print r,
	    return 1
	except:
	    #print self.name,'auth failire!!!'
	    return 0
    def test_manage_updatePassword_POST_permissions(self):
        from AccessControl.SecurityManagement import newSecurityManager
        from AccessControl.SecurityManagement import noSecurityManager
        from Acquisition import Implicit

        # Give the user a new password; attempting to authenticate with the
        # old password must fail
        class FauxUser(Implicit):
            def __init__(self, id):
                self._id = id

            def getId(self):
                return self._id

        USER_ID = 'testuser'
        PASSWORD = '******'
        ENCRYPTED = pw_encrypt(PASSWORD)

        zum = self._makeOne()
        zum.addUser(USER_ID, USER_ID, '')

        req, res = makeRequestAndResponse()
        req.set('REQUEST_METHOD', 'GET')
        req.set('method', 'GET')
        req.set('SESSION', {})
        newSecurityManager(None, FauxUser(USER_ID))
        try:
            self.assertRaises(Forbidden,
                              zum.manage_updatePassword,
                              USER_ID,
                              PASSWORD,
                              PASSWORD,
                              REQUEST=req)

            req.set('REQUEST_METHOD', 'POST')
            req.set('method', 'POST')
            self.assertRaises(Forbidden,
                              zum.manage_updatePassword,
                              USER_ID,
                              PASSWORD,
                              PASSWORD,
                              REQUEST=req)

            # Works with a POST + CSRF toekn
            req.form['csrf_token'] = 'deadbeef'
            req.SESSION['_csrft_'] = 'deadbeef'
            zum.manage_updatePassword(USER_ID, PASSWORD, PASSWORD, REQUEST=req)
        finally:
            noSecurityManager()
    def test_updateUserPassword_with_preencrypted_password(self):
        USER_ID = 'already_encrypted'
        PASSWORD = '******'

        ENCRYPTED = pw_encrypt(PASSWORD)

        zum = self._makeOne()
        zum.addUser(USER_ID, USER_ID, '')
        zum.updateUserPassword(USER_ID, ENCRYPTED)

        uid_and_info = zum.authenticateCredentials(
            {'login': USER_ID, 'password': PASSWORD
             })

        self.assertEqual(uid_and_info, (USER_ID, USER_ID))
示例#12
0
    def test__doAddUser_with_preencrypted_passwords(self):
        # See collector #1869 && #1926
        from AccessControl.AuthEncoding import pw_encrypt

        USER_ID = 'already_encrypted'
        PASSWORD = '******'

        ENCRYPTED = pw_encrypt(PASSWORD)

        self.uf._doAddUser(USER_ID, ENCRYPTED, [], [])

        uid_and_info = self.uf.users.authenticateCredentials(
                                {'login': USER_ID, 'password': PASSWORD})

        self.assertEqual(uid_and_info, (USER_ID, USER_ID))
    def test_updateUserPassword_with_preencrypted_password(self):
        USER_ID = 'already_encrypted'
        PASSWORD = '******'

        ENCRYPTED = pw_encrypt(PASSWORD)

        zum = self._makeOne()
        zum.addUser(USER_ID, USER_ID, '')
        zum.updateUserPassword(USER_ID, ENCRYPTED)

        uid_and_info = zum.authenticateCredentials(
                                { 'login': USER_ID
                                , 'password': PASSWORD
                                })

        self.assertEqual(uid_and_info, (USER_ID, USER_ID))
    def test__doAddUser_with_preencrypted_passwords(self):
        # See collector #1869 && #1926
        from AccessControl.AuthEncoding import pw_encrypt

        USER_ID = 'already_encrypted'
        PASSWORD = '******'

        ENCRYPTED = pw_encrypt(PASSWORD)

        self.uf._doAddUser(USER_ID, ENCRYPTED, [], [])

        uid_and_info = self.uf.users.authenticateCredentials(
            {'login': USER_ID, 'password': PASSWORD
             })

        self.assertEqual(uid_and_info, (USER_ID, USER_ID))
示例#15
0
    def test_manage_updatePassword_POST_permissions(self):
        from AccessControl.SecurityManagement import newSecurityManager
        from AccessControl.SecurityManagement import noSecurityManager
        from Acquisition import Implicit
        # Give the user a new password; attempting to authenticate with the
        # old password must fail
        class FauxUser(Implicit):

            def __init__(self, id):
                self._id = id

            def getId( self ):
                return self._id
        USER_ID = 'testuser'
        PASSWORD = '******'
        ENCRYPTED = pw_encrypt(PASSWORD)

        zum = self._makeOne()
        zum.addUser(USER_ID, USER_ID, '')

        req, res = makeRequestAndResponse()
        req.set('REQUEST_METHOD', 'GET')
        req.set('method', 'GET')
        req.set('SESSION', {})
        newSecurityManager(None, FauxUser(USER_ID))
        try:
            self.assertRaises(Forbidden, zum.manage_updatePassword,
                            USER_ID, PASSWORD, PASSWORD, REQUEST=req)

            req.set('REQUEST_METHOD', 'POST')
            req.set('method', 'POST')
            self.assertRaises(Forbidden, zum.manage_updatePassword,
                            USER_ID, PASSWORD, PASSWORD, REQUEST=req)

            # Works with a POST + CSRF toekn
            req.form['csrf_token'] = 'deadbeef'
            req.SESSION['_csrft_'] = 'deadbeef'
            zum.manage_updatePassword(USER_ID, PASSWORD, PASSWORD, REQUEST=req)
        finally:
            noSecurityManager()
示例#16
0
    def test_manage_removeUsers_POST_permissions(self):
        USER_ID = 'testuser'
        PASSWORD = '******'
        ENCRYPTED = pw_encrypt(PASSWORD)

        zum = self._makeOne()
        zum.addUser(USER_ID, USER_ID, '')

        req, res = makeRequestAndResponse()
        req.set('REQUEST_METHOD', 'GET')
        req.set('method', 'GET')
        req.set('SESSION', {})
        self.assertRaises(Forbidden, zum.manage_removeUsers,
                          [USER_ID], REQUEST=req)

        req.set('REQUEST_METHOD', 'POST')
        req.set('method', 'POST')
        self.assertRaises(Forbidden, zum.manage_removeUsers,
                          [USER_ID], REQUEST=req)

        req.form['csrf_token'] = 'deadbeef'
        req.SESSION['_csrft_'] = 'deadbeef'
        zum.manage_removeUsers([USER_ID], REQUEST=req)
    def handleOk(self, action):
        data, errors = self.extractData()
        if errors:
            self.status = self.formErrorsMessage
            return

        # NOTE: The validator on email should have already checked if the password can be set and auto logged the user in
        res = get_brains_for_email(self.context, data['email'], self.request)
        person = res[0].getObject()
        person.password = pw_encrypt(data['password'])
        person.registered = True

        # See if came_from was passed
        # fix odd bug where came_from is a list of two values
        came_from = data.get('came_from', None)
        if came_from and isinstance(came_from, (list, tuple)):
            came_from = came_from[0]

        self.request.form['came_from'] = came_from

        # merge in with standard plone login process.  
        login_next = self.context.restrictedTraverse('login_next')
        login_next()
示例#18
0
 def hashPassword(self, password):
     """
     Delegate to AccessControl.AuthEncoding.
     """
     return pw_encrypt(password)
 def _set_password(self, password):
     # When editing, the password field is empty in the browser; do
     # not do anything then.
     if password is not None:
         self.context.password = pw_encrypt(password)
示例#20
0
 def _forceSetPassword(self, value):
   self.password = PersistentMapping()
   self._setEncodedPassword(pw_encrypt(value))
示例#21
0
 def hashPassword(self, password):
     """
     Delegate to AccessControl.AuthEncoding.
     """
     return pw_encrypt(password)
示例#22
0
 def _set_password(self, password):
     # When editing, the password field is empty in the browser; do
     # not do anything then.
     if password is not None:
         self.context.password = pw_encrypt(password)
示例#23
0
 def _doRemoteAuthentication(self, login, password):
     # Do remote authentication with local ZODB caching
     # Thanks to this it is possible to login to instance, even
     # if master authentication server is down
     #
     # socket.sslerror and socket.error are assumed as acceptable ones
     # and invoke authentication against locally available cache of
     # users
     #
     # any other error is assumed as fatal and results in disallowing
     # authentication and clearing local cache
     if self.remote_authentication_cache is None:
         self.remote_authentication_cache = OOBTree()
     portal = self.getPortalObject()
     encrypted_password = pw_encrypt(password)
     callRemoteProxyMethod = portal.portal_wizard.callRemoteProxyMethod
     erp5_uid = portal.ERP5Site_getExpressInstanceUid()
     try:
         # XXX: This mix of passed parameters is based on
         # WizardTool_authenticateCredentials. As current implementation
         # shall be bug-to-bug compatible with previous one, kept such
         # behaviour
         result = int(callRemoteProxyMethod(
                    'Base_authenticateCredentialsFromExpressInstance',
                    use_cache = 0,
                    ignore_exceptions = 0,
                    **{'login': login,
                       'password': password,
                       'erp5_uid': erp5_uid}))
     except socket.error:
         # issue with socket, read from "ZODB cache"
         LOG('ERP5RemoteUserManager', INFO, 'Socket issue with server, '
           'used local cache', error=True)
         stored_encrypted_password = self.remote_authentication_cache.get(
            login, None)
         result = int(stored_encrypted_password is not None and pw_validate(
           stored_encrypted_password, password))
     except: # XXX: It would be better to do except Exception, but
             # to-be-bug compatible with WizardTool_authenticateCredentials
             # is better to catch the same way
         # any other issue, work like WizardTool_authenticateCredentials
         # XXX: To be fine tuned
         LOG('ERP5RemoteUserManager', WARNING, 'Not supported exception '
           'assuming that authentication failed', error=True)
         result = 0
         # clear local cache
         if login in self.remote_authentication_cache:
             del self.remote_authentication_cache[login]
     else:
         # update ZODB cache
         if result == 1:
             # successfully logged in
             stored_encrypted_password = self.remote_authentication_cache\
                 .get(login, None)
             if stored_encrypted_password is None or \
                not pw_validate(stored_encrypted_password, password):
                 # not yet in cache or changed on server
                 self.remote_authentication_cache[login] = encrypted_password
         else:
             # wrong login, so clear local cache
             if login in self.remote_authentication_cache:
                 del self.remote_authentication_cache[login]
     return result
示例#24
0
 def _doRemoteAuthentication(self, login, password):
     # Do remote authentication with local ZODB caching
     # Thanks to this it is possible to login to instance, even
     # if master authentication server is down
     #
     # socket.sslerror and socket.error are assumed as acceptable ones
     # and invoke authentication against locally available cache of
     # users
     #
     # any other error is assumed as fatal and results in disallowing
     # authentication and clearing local cache
     if self.remote_authentication_cache is None:
         self.remote_authentication_cache = OOBTree()
     portal = self.getPortalObject()
     encrypted_password = pw_encrypt(password)
     callRemoteProxyMethod = portal.portal_wizard.callRemoteProxyMethod
     erp5_uid = portal.ERP5Site_getExpressInstanceUid()
     try:
         # XXX: This mix of passed parameters is based on
         # WizardTool_authenticateCredentials. As current implementation
         # shall be bug-to-bug compatible with previous one, kept such
         # behaviour
         result = int(
             callRemoteProxyMethod(
                 'Base_authenticateCredentialsFromExpressInstance',
                 use_cache=0,
                 ignore_exceptions=0,
                 **{
                     'login': login,
                     'password': password,
                     'erp5_uid': erp5_uid
                 }))
     except socket.error:
         # issue with socket, read from "ZODB cache"
         LOG('ERP5RemoteUserManager',
             INFO, 'Socket issue with server, '
             'used local cache',
             error=True)
         stored_encrypted_password = self.remote_authentication_cache.get(
             login, None)
         result = int(stored_encrypted_password is not None
                      and pw_validate(stored_encrypted_password, password))
     except:  # XXX: It would be better to do except Exception, but
         # to-be-bug compatible with WizardTool_authenticateCredentials
         # is better to catch the same way
         # any other issue, work like WizardTool_authenticateCredentials
         # XXX: To be fine tuned
         LOG('ERP5RemoteUserManager',
             WARNING, 'Not supported exception '
             'assuming that authentication failed',
             error=True)
         result = 0
         # clear local cache
         if login in self.remote_authentication_cache:
             del self.remote_authentication_cache[login]
     else:
         # update ZODB cache
         if result == 1:
             # successfully logged in
             stored_encrypted_password = self.remote_authentication_cache\
                 .get(login, None)
             if stored_encrypted_password is None or \
                not pw_validate(stored_encrypted_password, password):
                 # not yet in cache or changed on server
                 self.remote_authentication_cache[
                     login] = encrypted_password
         else:
             # wrong login, so clear local cache
             if login in self.remote_authentication_cache:
                 del self.remote_authentication_cache[login]
     return result
 def _forceSetPassword(self, value):
     # this method is kept for backward compatibility, as there might be interaction
     # workflows on this method.
     self.password = PersistentMapping()
     if value:
         self._setEncodedPassword(pw_encrypt(value))
示例#26
0
    def handleOk(self, action):
        data, errors = self.extractData()
        if errors:
            self.status = self.formErrorsMessage
            return

        data = {
            'first_name': data['first_name'],
            'last_name': data['last_name'],
            'fullname': '%s %s' % (data['first_name'], data['last_name']),
            'username': data['email'],
            'email': data['email'].lower(),
            'email_opt_in': data['email_opt_in'],
            'password': pw_encrypt(data['password']),
            'registered': True,
        }

        data_enc = {}
        for key, value in data.items():
            if key == 'email':
                data_enc[key] = value.encode('ascii')
                continue
            if isinstance(value, unicode):
                data_enc[key] = value.encode('utf8')
            else:
                data_enc[key] = value

        # Create the login user
        reg = getToolByName(self.context, 'portal_registration')
        reg.addMember(
            data_enc['email'],
            data_enc['password'],
            properties=data,
        )

        # Create the user object portal reg and PAS should do this for us
        people_container = getattr(getSite(), 'people')
        createContentInContainer(people_container,
                                 'collective.salesforce.fundraising.person',
                                 checkConstraints=False,
                                 **data)

        # Authenticate the user
        mtool = getToolByName(self.context, 'portal_membership')
        acl = getToolByName(self.context, 'acl_users')
        newSecurityManager(None, acl.getUser(data_enc['email']))
        mtool.loginUser()

        # See if came_from was passed
        # fix odd bug where came_from is a list of two values
        came_from = self.request.form.get('form.widgets.came_from', None)
        if came_from and isinstance(came_from, (list, tuple)):
            came_from = came_from[0]

        if came_from:
            self.request.form['came_from'] = came_from

        # merge in with standard plone login process.
        login_next = self.context.restrictedTraverse('login_next')
        html = login_next()

        # Send the response from login_next() to the browser.
        if self.request.response.getStatus() == 200:
            self.render = lambda: html
示例#27
0
 def _forceSetPassword(self, value):
     self.password = PersistentMapping()
     self._setEncodedPassword(pw_encrypt(value))
    def handleOk(self, action):
        data, errors = self.extractData()
        if errors:
            self.status = self.formErrorsMessage
            return

        data = {
            'first_name': data['first_name'],
            'last_name': data['last_name'],
            'fullname': '%s %s' % (
                data['first_name'],
                data['last_name']),
            'username': data['email'],
            'email': data['email'].lower(),
            'email_opt_in': data['email_opt_in'],
            'password': pw_encrypt(data['password']),
            'registered': True,
        }

        data_enc = {}
        for key, value in data.items():
            if key == 'email':
                data_enc[key] = value.encode('ascii')
                continue
            if isinstance(value, unicode):
                data_enc[key] = value.encode('utf8')
            else:
                data_enc[key] = value

        # Create the login user
        reg = getToolByName(self.context, 'portal_registration')
        reg.addMember(
            data_enc['email'],
            data_enc['password'],
            properties=data,
        )

        # Create the user object portal reg and PAS should do this for us
        people_container = getattr(getSite(), 'people')
        createContentInContainer(
            people_container,
            'collective.salesforce.fundraising.person',
            checkConstraints=False,
            **data
        )

        # Authenticate the user
        mtool = getToolByName(self.context, 'portal_membership')
        acl = getToolByName(self.context, 'acl_users')
        newSecurityManager(None, acl.getUser(data_enc['email']))
        mtool.loginUser()

        # See if came_from was passed
        # fix odd bug where came_from is a list of two values
        came_from = self.request.form.get('form.widgets.came_from', None)
        if came_from and isinstance(came_from, (list, tuple)):
            came_from = came_from[0]

        if came_from:
            self.request.form['came_from'] = came_from

        # merge in with standard plone login process.
        login_next = self.context.restrictedTraverse('login_next')
        html = login_next()

        # Send the response from login_next() to the browser.
        if self.request.response.getStatus() == 200:
            self.render = lambda: html