Python passlib.hash.pbkdf2_sha256.verify() Examples

The following are 25 code examples of passlib.hash.pbkdf2_sha256.verify(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module passlib.hash.pbkdf2_sha256 , or try the search function .
Example #1
Source File: test_sessions.py    From amivapi with GNU Affero General Public License v3.0 6 votes vote down vote up
def assertRehashed(self, user_id, plaintext, old_hash):
        """Assert that the password was rehased.

        Check
        - that the password in the database is not the old hash
        - that the password in the datbase is a correct hash of the password

        Args:
            user_id (ObjectId): Id of user
            plaintext (str): Password of user as plaintext
            old_hash (str): Old hash of passwor
        """
        user = self.db['users'].find_one({'_id': user_id})

        self.assertNotEqual(user['password'], old_hash)

        self.assertTrue(pbkdf2_sha256.verify(plaintext, user['password'])) 
Example #2
Source File: test_sessions.py    From amivapi with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_verify_hash(self):
        """Test verify hash.

        Also needs app context to access config.
        """
        with self.app.app_context():
            hashed = self.app.config['PASSWORD_CONTEXT'].hash("some_pw")

            # Correct password
            self.assertTrue(
                verify_password({'password': hashed}, "some_pw")
            )

            # Wrong password
            self.assertFalse(
                verify_password({'password': hashed}, "NotThePassword")
            ) 
Example #3
Source File: util.py    From GeoHealthCheck with MIT License 5 votes vote down vote up
def verify_hash(hash1, hash2):
    # https://passlib.readthedocs.io/en/stable/narr/hash-tutorial.html
    return pbkdf2_sha256.verify(hash1, hash2) 
Example #4
Source File: models.py    From flask-api-boilerplate with MIT License 5 votes vote down vote up
def check_password(self, password):
        if password is None:
            return False
        return pbkdf2_sha256.verify(password, self.password) 
Example #5
Source File: models.py    From flask-jwt-auth with MIT License 5 votes vote down vote up
def verify_hash(password, hash):
        return sha256.verify(password, hash) 
Example #6
Source File: models.py    From flask-jwt-auth with MIT License 5 votes vote down vote up
def verify_hash(password, hash):
        return sha256.verify(password, hash) 
Example #7
Source File: models.py    From flask-jwt-auth with MIT License 5 votes vote down vote up
def verify_hash(password, hash):
        return sha256.verify(password, hash) 
Example #8
Source File: models.py    From flask-jwt-auth with MIT License 5 votes vote down vote up
def verify_hash(password, hash):
        return sha256.verify(password, hash) 
Example #9
Source File: test_security.py    From amivapi with GNU Affero General Public License v3.0 5 votes vote down vote up
def assertVerifyDB(self, user_id, plaintext):
        """Check that the stored password was hashed correctly.

        Shorthand to query db and compare.

        Args:
            user_id (str): The user.
            hashed_password (str): The hash which should be stored

        Returns:
            bool: True if hashed correctly.
        """
        user = self.db["users"].find_one({'_id': ObjectId(user_id)})

        self.assertTrue(pbkdf2_sha256.verify(plaintext, user['password'])) 
Example #10
Source File: test_security.py    From amivapi with GNU Affero General Public License v3.0 5 votes vote down vote up
def assertVerify(self, plaintext, hashed_password):
        """Assert the hash matches the password."""
        self.assertTrue(pbkdf2_sha256.verify(plaintext, hashed_password)) 
Example #11
Source File: User.py    From TensorHive with Apache License 2.0 5 votes vote down vote up
def verify_hash(password, hash):
        return sha256.verify(password, hash) 
Example #12
Source File: auth.py    From netflix-proxy with MIT License 5 votes vote down vote up
def validate_user(username,password):
    try:
        results = db.query("SELECT * FROM users WHERE username=$username ORDER BY ROWID ASC LIMIT 1",
                           vars={'username': username})
        user = results[0]

        try:
            valid_hash = pbkdf2_sha256.verify(password, user.password)
        except ValueError as e:
            web.debug('%s user=%s' % (str(e), user.username))
            valid_hash = None
            pass
            
        date_now = datetime.datetime.now()
        date_expires = datetime.datetime.combine(user.expires, datetime.time.min)
        if date_now <= date_expires:
            if valid_hash:
                web.debug('login_success_hash: user=%s' % user.username)
                return user
            else:
                web.debug('login_failed_hash: incorrect password user=%s, fallback to plaintext' % user.username)
            
                if password == user.password:
                    web.debug('login_success_plaintext: user=%s' % user.username)
                    return user
                else:
                    web.debug('login_failed_plaintext: incorrect password user=%s' % user.username)
                    return None
        else:
            web.debug('login_failed: expired account user=%s' % user.username)
            return None
    
    except IndexError as e:
        web.debug('login_failed: not found user=%s' % username)
        return None 
Example #13
Source File: DatabaseLayer.py    From watchdog with Apache License 2.0 5 votes vote down vote up
def verifyUser(user, pwd):
  person = getUser(user)
  return (person and pbkdf2_sha256.verify(pwd, person['password'])) 
Example #14
Source File: user.py    From wb_contest_submission_server with GNU General Public License v3.0 5 votes vote down vote up
def verify(self, password):
        return pbkdf2_sha256.verify(password, self._password_hash) 
Example #15
Source File: user.py    From wb_contest_submission_server with GNU General Public License v3.0 5 votes vote down vote up
def validate(username, password):
        user = User.query.filter(User._username == username).first()
        if user is not None and \
           pbkdf2_sha256.verify(password, user._password_hash):
            return user
        else:
            return None 
Example #16
Source File: utils.py    From appkernel with Apache License 2.0 5 votes vote down vote up
def change_p(self, current_password, new_password):
        if not pbkdf2_sha256.verify(current_password, self.password):
            raise ServiceException(403, _('Current password is not correct'))
        else:
            self.password = new_password
            self.save()
        return _('Password changed') 
Example #17
Source File: service_hateoas_test.py    From appkernel with Apache License 2.0 5 votes vote down vote up
def test_working_action(client):
    print('\n> links >{}'.format(User.actions))
    user = create_and_save_a_user('test user', 'test password', 'test description')
    rsp = client.get('/users/{}'.format(user.id))
    print('\nResponse: {} -> {}'.format(rsp.status, rsp.data))
    assert rsp.status_code == 200, 'the status code is expected to be 200'
    result = rsp.json
    assert result.get('_links') is not None
    assert 'change_password' in result.get('_links')
    assert 'get_description' in result.get('_links')
    assert 'self' in result.get('_links')
    assert 'collection' in result.get('_links')
    change_pass_included = False
    newpass = 'new pass'
    for link_name, link_value in result.get('_links').items():
        if link_name == 'change_password':
            change_pass_included = True
            post_data = json.dumps({'current_password': 'test password', 'new_password': newpass})
            assert link_value.get('href') is not None
            rsp = client.post(link_value.get('href'), data=post_data)
            print('\nResponse: {} -> {}'.format(rsp.status, rsp.data.decode))
            assert rsp.status_code == 200, 'the status code is expected to be 200'
            break
    assert change_pass_included, 'Should contain change_password link'
    rsp = client.get('/users/{}'.format(user.id))
    print('\nResponse: {} -> {}'.format(rsp.status, rsp.data.decode()))
    assert rsp.status_code == 200, 'the status code is expected to be 200'
    result = rsp.json
    assert 'password' not in result
    assert pbkdf2_sha256.verify(newpass, User.find_by_id(result.get('id')).password) 
Example #18
Source File: user.py    From zoe with Apache License 2.0 5 votes vote down vote up
def check_password(self, candidate_pw: str) -> bool:
        """Checks if the password is correct."""
        if self.auth_source != "internal" or self.password is None:
            return False
        return hash_algo.verify(candidate_pw, self.password) 
Example #19
Source File: models.py    From yugioh-game with MIT License 5 votes vote down vote up
def check_password(self, password):
		return pbkdf2_sha256.verify(password, self.password) 
Example #20
Source File: projectmgr.py    From sia-cog with MIT License 5 votes vote down vote up
def ValidateUser(username, password):
    result = False
    try:
        user = GetUserInfo(username)
        if user is None:
            raise Exception("User not found")

        result = pbkdf2_sha256.verify(password, user.password)
    except:
        raise

    return result 
Example #21
Source File: models.py    From papers with MIT License 5 votes vote down vote up
def verify_password(password, _hash):
        return pbkdf2_sha256.verify(password, _hash) 
Example #22
Source File: users.py    From hackit with Apache License 2.0 5 votes vote down vote up
def checkpassword(self, pwd):
        return pbkdf2_sha256.verify(pwd, self.password) 
Example #23
Source File: server.py    From PenguinDome with Apache License 2.0 4 votes vote down vote up
def verify_signature(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        try:
            data = request.form['data']
        except Exception:
            remote_addr = getattr(request, 'remote_addr', None)
            # Probably just somebody port-scanning us, not worth logging as
            # an error and making people waste time investigating.
            if remote_addr:
                log.info('Ignoring empty request from {}'.format(
                    remote_addr))
            else:
                log.info('Ignoring empty request with no remote address')
            return('error')
        try:
            signature = request.form['signature']
        except Exception:
            # We're not logging the data here because it may contain
            # sensitive info that should not be logged. Perhaps I am being
            # too paranoid about this. ¯\_(ツ)_/¯
            hostname = getattr(data, 'hostname', None)
            remote_addr = getattr(request, 'remote_addr', None)
            log.error('Ignoring malformed request (no signature) from '
                      'host {}, addr {}'.format(hostname, remote_addr))
            return('error')
        with tempfile.NamedTemporaryFile('w+') as data_file, \
                tempfile.NamedTemporaryFile('w+') as signature_file:
            data_file.write(data)
            data_file.flush()
            signature_file.write(signature)
            signature_file.flush()
            try:
                gpg_command('--verify', signature_file.name,
                            data_file.name)
            except Exception:
                hostname = getattr(data, 'hostname', None)
                remote_addr = getattr(request, 'remote_addr', None)
                log.error('Ignoring malformed request (bad signature) from '
                          'host {}, addr {}'.format(hostname, remote_addr))
                return('error')
        return f(*args, **kwargs)
    return wrapper 
Example #24
Source File: server.py    From PenguinDome with Apache License 2.0 4 votes vote down vote up
def check_password(auth_name):
    # Get list of users who are allowed access
    users = get_server_setting(auth_name + ':users') or []
    if isinstance(users, str):
        users = [users]
    users = {u: None for u in users}

    # Get list of groups who are allowed access
    groups = get_server_setting(auth_name + ':groups') or []
    if isinstance(groups, str):
        groups = [groups]

    # Get users for authorized groups
    for group in groups:
        group_users = get_server_setting('groups:' + group) or []
        if isinstance(group_users, str):
            group_users = [group_users]
        if group_users:
            users.update({u: None for u in group_users})
        else:
            log.warn('check_password: group {} is empty', group)

    # Warn about and remove invalid users
    for user in list(users.keys()):
        users[user] = get_server_setting('users:' + user)
        if not users[user]:
            log.warn('check_password: user {} has no password', user)
            del users[user]

    auth_info = get_server_setting(auth_name + ':passwords') or {}
    users.update(auth_info)
    if not users:
        log.debug('No auth: no passwords configured in {}', auth_name)
        return False

    if not request.authorization:
        log.debug('No auth: no username specified in request')
        return False
    try:
        password_hash = users[request.authorization.username]
    except KeyError:
        # N.B. One does not log usernames from authentication requests, in
        # case the user accidentally typed the password in the username field,
        # so that one doesn't accidentally log passwords.
        log.debug('No auth: invalid username for {}', auth_name)
        return False
    if not pbkdf2_sha256.verify(request.authorization.password, password_hash):
        # It's OK to log the username here, since we've already confirmed that
        # it's a valid username, not a password.
        log.warn('No auth: incorrect password for {} in {}',
                 request.authorization.username, auth_name)
        return False
    log.info('check_password: authenticated {} for {}',
             request.authorization.username, auth_name)
    return True 
Example #25
Source File: authentication_decision_point.py    From calvin-base with Apache License 2.0 4 votes vote down vote up
def authentication_decision(self, request):
        #TODO: remove debug prints (or set as DEBUG/ANALYZE) as they leak loads of information
        _log.debug("authentication_decision: request = %s" % request)
        try:
            users_db = self.node.authentication.arp.get_users_db()
            groups_db = self.node.authentication.arp.get_groups_db()
            # Verify users against stored passwords
            subject_attributes = {}
            decision = False
            if ('subject' in request) and ('user' in request['subject']) and (request['subject']['user'] in users_db):
                user = users_db[request['subject']['user']]
                if 'password' in request['subject'] and ('password' in user):
                    try:
                        #Verify password
                        decision = pbkdf2_sha256.verify(request['subject']['password'], user['password'])
                        if decision:
                            #Password was correct
                            if 'attributes' in user:
                                for key in user['attributes']:
                                    if key == "groups" and groups_db:
                                        for group_key in user['attributes']['groups']:
                                            if group_key in groups_db:
                                                for group_attribute in groups_db[group_key]:
                                                    if not group_attribute in subject_attributes:
                                                        # If there is no key, create array and add first value
                                                        subject_attributes.setdefault(group_attribute, []).append(groups_db[group_key][group_attribute])
                                                    elif not groups_db[group_key][group_attribute] in subject_attributes[group_attribute]:
                                                        # List exists, make sure we don't add same value several times
                                                        subject_attributes[group_attribute].append(groups_db[group_key][group_attribute])
                                    else:
                                        if not user['attributes'][key] in subject_attributes:
                                            # If there is no key, create array and add first value
                                            subject_attributes.setdefault(key, []).append(user['attributes'][key])
                                        elif not user['attributes'][key] in subject_attributes[key]:
                                            # List exists, make sure we don't add same value several times
                                            subject_attributes[key].append(user['attributes'][key])
                            else:
                                _log.error("No attributes for user={}".format(user))
                            return (decision, subject_attributes)
                        else:
                            _log.error("Supplied password is not correct")
                    except Exception as err:
                        _log.error("PBKDF calculation failed, err={}".format(err))
                else:
                    _log.error("No password in request or no password in database")
                    return (decision, None)
            else:
                _log.error("Incorrectly formated request or user not allowed: \n\trequest={}".format(request))
            return (decision, None)
        except Exception as err:
            _log.error("authentication_decision: Authentication failed, err={}".format(err))
            return (False, None)