def checkPassword(self, value) : """ Check the password, usefull when changing password """ if value is not None : return pw_validate(self.getPassword(), value) return False
def _authenticateCredentials(login, password, path, ignore_password=False): if not login or not (password or ignore_password): return None user_list = self.getUserByLogin(login) if not user_list: raise _AuthenticationFailure() user = user_list[0] try: # get assignment assignment_list = [x for x in user.contentValues(portal_type="Assignment") if x.getValidationState() == "open"] valid_assignment_list = [] # check dates if exist login_date = DateTime() for assignment in assignment_list: if assignment.getStartDate() is not None and \ assignment.getStartDate() > login_date: continue if assignment.getStopDate() is not None and \ assignment.getStopDate() < login_date: continue valid_assignment_list.append(assignment) if (ignore_password or pw_validate(user.getPassword(), password)) and \ len(valid_assignment_list) and user \ .getValidationState() != 'deleted': #user.getCareerRole() == 'internal': return login, login # use same for user_id and login finally: pass raise _AuthenticationFailure()
def checkPassword(self, value): """ Check the password, usefull when changing password """ if value is not None: return pw_validate(self.getPassword(), value) return False
def _authenticateCredentials(login, password, path): if not login or not password: return None user_list = self.getUserByLogin((login,)) if not user_list: return None user = user_list[0] user_portal_type = user.getPortalType() sm = getSecurityManager() if sm.getUser().getId() != SUPER_USER: newSecurityManager(self, self.getUser(SUPER_USER)) # search for assignment only on person entity if user_portal_type == 'Person': try: # get assignment assignment_list = [x for x in \ user.contentValues(portal_type="Assignment") if \ x.getValidationState() == "open"] valid_assignment_list = [] # check dates if exist login_date = DateTime() for assignment in assignment_list: if assignment.getStartDate() is not None and \ assignment.getStartDate() > login_date: continue if assignment.getStopDate() is not None and \ assignment.getStopDate() < login_date: continue valid_assignment_list.append(assignment) if pw_validate(user.getPassword(), password) and \ len(valid_assignment_list): #user.getCareerRole() == 'internal': return login, login # use same for user_id and login finally: setSecurityManager(sm) else: if pw_validate(user.getPassword(), password): return login, login # use same for user_id and login return None
def _authenticateCredentials(login, password, path): if not login or not password: return None user_list = self.getUserByLogin((login, )) if not user_list: return None user = user_list[0] user_portal_type = user.getPortalType() sm = getSecurityManager() if sm.getUser().getId() != SUPER_USER: newSecurityManager(self, self.getUser(SUPER_USER)) # search for assignment only on person entity if user_portal_type == 'Person': try: # get assignment assignment_list = [x for x in \ user.contentValues(portal_type="Assignment") if \ x.getValidationState() == "open"] valid_assignment_list = [] # check dates if exist login_date = DateTime() for assignment in assignment_list: if assignment.getStartDate() is not None and \ assignment.getStartDate() > login_date: continue if assignment.getStopDate() is not None and \ assignment.getStopDate() < login_date: continue valid_assignment_list.append(assignment) if pw_validate(user.getPassword(), password) and \ len(valid_assignment_list): #user.getCareerRole() == 'internal': return login, login # use same for user_id and login finally: setSecurityManager(sm) else: if pw_validate(user.getPassword(), password): return login, login # use same for user_id and login return None
def test_reset_password(self): member = self._createType(self.portal, 'dexterity.membrane.member', 'joe') member.email = '*****@*****.**' self.portal.membrane_tool.reindexObject(member) user_id = get_user_id_for_email(self.portal, '*****@*****.**') self.portal.acl_users.userSetPassword(user_id, 'foobar') from AccessControl.AuthEncoding import pw_validate self.assertTrue(pw_validate(member.password, 'foobar'))
def test_reset_password(self): member = self._createType(self.layer["portal"], "dexterity.membrane.organizationmember", "joe") member.email = "*****@*****.**" self.layer["portal"].membrane_tool.reindexObject(member) user_id = get_user_id_for_email(self.layer["portal"], "*****@*****.**") self.layer["portal"].acl_users.userSetPassword(user_id, "foobar") from AccessControl.AuthEncoding import pw_validate self.assertTrue(pw_validate(member.password, "foobar"))
def test_reset_password(self): member = self._createType( self.portal, 'dexterity.membrane.member', 'joe') member.email = '*****@*****.**' self.portal.membrane_tool.reindexObject(member) user_id = get_user_id_for_email(self.portal, '*****@*****.**') self.portal.acl_users.userSetPassword(user_id, 'foobar') from AccessControl.AuthEncoding import pw_validate self.assertTrue(pw_validate(member.password, 'foobar'))
def verifyCredentials(self, credentials): """Returns True is password is authenticated, False if not. """ user = IMembraneUserObject(self.context) if credentials.get('login') != user.getUserName(): # Should never happen, as the code should then never end # up here, but better safe than sorry. return False if not IProvidePasswordsSchema.providedBy(self.context): return False return pw_validate(self.context.password, credentials.get('password', ''))
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__doAddUser_with_not_yet_encrypted_passwords(self): # See collector #1869 && #1926 from AccessControl.AuthEncoding import pw_validate USER_ID = 'not_yet_encrypted' PASSWORD = '******' uf = self._makeOne() uf.encrypt_passwords = True self.assertFalse(uf._isPasswordEncrypted(PASSWORD)) uf._doAddUser(USER_ID, PASSWORD, [], []) user = uf.getUserById(USER_ID) self.assertTrue(uf._isPasswordEncrypted(user.__)) self.assertTrue(pw_validate(user.__, PASSWORD))
def test__doAddUser_with_not_yet_encrypted_passwords(self): # See collector #1869 && #1926 from AccessControl.AuthEncoding import pw_validate USER_ID = 'not_yet_encrypted' PASSWORD = '******' uf = UserFolder().__of__(self.app) uf.encrypt_passwords = True self.failIf(uf._isPasswordEncrypted(PASSWORD)) uf._doAddUser(USER_ID, PASSWORD, [], []) user = uf.getUserById(USER_ID) self.failUnless(uf._isPasswordEncrypted(user.__)) self.failUnless(pw_validate(user.__, PASSWORD))
def test__doAddUser_with_not_yet_encrypted_passwords(self): # See collector #1869 && #1926 from AccessControl.AuthEncoding import pw_validate USER_ID = 'not_yet_encrypted' PASSWORD = '******' uf = self._makeOne() uf.encrypt_passwords = True self.failIf(uf._isPasswordEncrypted(PASSWORD)) uf._doAddUser(USER_ID, PASSWORD, [], []) user = uf.getUserById(USER_ID) self.failUnless(uf._isPasswordEncrypted(user.__)) self.failUnless(pw_validate(user.__, PASSWORD))
def isPasswordAlreadyUsed(self, password): """ Return if password has already been used. """ preferred_number_of_last_password_to_check = self.portal_preferences.getPreferredNumberOfLastPasswordToCheck() password_event_list = self.getPortalObject().portal_catalog( portal_type = "Password Event", default_destination_uid = self.getUid(), sort_on = (('creation_date', 'DESC',),), validation_state = 'confirmed', limit = preferred_number_of_last_password_to_check) password_list = [x.getPassword() for x in password_event_list] for encoded_password in password_list: if pw_validate(encoded_password, password): return True return False
def test__doAddUser_with_preencrypted_passwords(self): # See collector #1869 && #1926 from AccessControl.AuthEncoding import pw_validate USER_ID = 'already_encrypted' PASSWORD = '******' uf = UserFolder().__of__(self.app) uf.encrypt_passwords = True ENCRYPTED = uf._encryptPassword(PASSWORD) uf._doAddUser(USER_ID, ENCRYPTED, [], []) user = uf.getUserById(USER_ID) self.assertEqual(user.__, ENCRYPTED) self.failUnless(uf._isPasswordEncrypted(user.__)) self.failUnless(pw_validate(user.__, PASSWORD))
def test__doAddUser_with_preencrypted_passwords(self): # See collector #1869 && #1926 from AccessControl.AuthEncoding import pw_validate USER_ID = 'already_encrypted' PASSWORD = '******' uf = self._makeOne() uf.encrypt_passwords = True ENCRYPTED = uf._encryptPassword(PASSWORD) uf._doAddUser(USER_ID, ENCRYPTED, [], []) user = uf.getUserById(USER_ID) self.assertEqual(user.__, ENCRYPTED) self.failUnless(uf._isPasswordEncrypted(user.__)) self.failUnless(pw_validate(user.__, PASSWORD))
def _authenticateCredentials(login, password, path, ignore_password=False): if not login or not (password or ignore_password): return None user_list = self.getUserByLogin(login) if not user_list: raise _AuthenticationFailure() user = user_list[0] try: if (ignore_password or pw_validate(user.getPassword(), password)) and \ len(getValidAssignmentList(user)) and user \ .getValidationState() != 'deleted': #user.getCareerRole() == 'internal': return login, login # use same for user_id and login finally: pass raise _AuthenticationFailure()
def validate(self, reference, attempt): """ Check to see if the reference is a hash of the attempt. """ return pw_validate(reference, attempt)
def authenticateCredentials(self, credentials): login_portal_type = credentials.get( 'login_portal_type', self.login_portal_type, ) if 'external_login' in credentials: # External plugin: extractor plugin can validate credential validity. # Our job is to locate the actual user and check related documents # (assignments...). check_password = False login_value = self._getLoginValueFromLogin( credentials.get('external_login'), login_portal_type=login_portal_type, ) elif 'login_relative_url' in credentials: # Path-based login: extractor plugin can validate credential validity and # directly locate the login document. Our job is to check related # documents (assignments...). check_password = False login_value = self.getPortalObject().unrestrictedTraverse( credentials.get("login_relative_url"), ) else: # Traditional login: find login document from credentials, check password # and check related documents (assignments...). check_password = True login_value = self._getLoginValueFromLogin( credentials.get('login'), login_portal_type=login_portal_type, ) if login_value is None: return user_value = login_value.getParentValue() if not user_value.hasUserId(): return if user_value.getValidationState() == 'deleted': return if user_value.getPortalType() in ('Person', ): now = DateTime() for assignment in user_value.contentValues( portal_type="Assignment"): if assignment.getValidationState() == "open" and ( not assignment.hasStartDate() or assignment.getStartDate() <= now) and ( not assignment.hasStopDate() or assignment.getStopDate() >= now): break else: return is_authentication_policy_enabled = self.getPortalObject( ).portal_preferences.isAuthenticationPolicyEnabled() if check_password: password = credentials.get('password') if not password or not pw_validate( login_value.getPassword(), password, ): if is_authentication_policy_enabled: login_value.notifyLoginFailure() return if is_authentication_policy_enabled: if login_value.isPasswordExpired(): login_value.notifyPasswordExpire() return if login_value.isLoginBlocked(): return return (user_value.getUserId(), login_value.getReference())
def checkPassword(self, value) : """ """ if value is not None : return pw_validate(self.getPassword(), value) return False
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 _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 checkPassword(self, value): """ """ if value is not None: return pw_validate(self.getPassword(), value) return False
def testSetPassword(self): self.membership.setPassword('geheim') member = self.membership.getMemberById(default_user) auth = self.membership.getAuthenticatedMember() self.failUnless(pw_validate(member.getPassword(), 'geheim')) self.failUnless(pw_validate(auth.getPassword(), 'geheim'))
def checkPassword(self, clearPassword): '''Returns True if p_clearPassword is the correct password for this user.''' encryptedPassword = self.getZopeUser()._getPassword() from AccessControl.AuthEncoding import pw_validate return pw_validate(encryptedPassword, clearPassword)