Python bcrypt.checkpw() Examples

The following are 30 code examples of bcrypt.checkpw(). 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 bcrypt , or try the search function .
Example #1
Source File: account.py    From infrabox with MIT License 9 votes vote down vote up
def post(self):
        b = request.get_json()

        email = b['email']
        password = b['password']

        user = g.db.execute_one_dict('''
            SELECT id, password
            FROM "user"
            WHERE email = %s
        ''', [email])

        if not user:
            abort(400, 'Invalid email/password combination')

        if not bcrypt.checkpw(password.encode('utf8'), user['password'].encode('utf8')):
            abort(400, 'Invalid email/password combination')

        token = encode_user_token(user['id'])

        res = OK('Logged in')
        res.set_cookie('token', token)
        return res 
Example #2
Source File: test_auth_api.py    From SempoBlockchain with GNU General Public License v3.0 6 votes vote down vote up
def test_reset_password_valid_token(test_client, authed_sempo_admin_user):
    """
    GIVEN a Flask application
    WHEN a valid the password reset token is POSTED to '/api/auth/reset_password/'
    THEN check response is 200 and check if password changed
    """
    import bcrypt

    # Explicitly test None case since database migration can result in None instead of []
    authed_sempo_admin_user.password_reset_tokens = None

    password_reset_token = authed_sempo_admin_user.encode_single_use_JWS('R')
    authed_sempo_admin_user.save_password_reset_token(password_reset_token)
    password = 'NewTestPassword'

    response = test_client.post('/api/v1/auth/reset_password/',
                                data=json.dumps(dict(new_password=password, reset_password_token=password_reset_token)),
                                content_type='application/json', follow_redirects=True)

    f = Fernet(config.PASSWORD_PEPPER)
    decrypted_hash = f.decrypt(authed_sempo_admin_user.password_hash.encode())
    assert bcrypt.checkpw(
        password.encode(), decrypted_hash)
    assert authed_sempo_admin_user.password_reset_tokens == []
    assert response.status_code == 200 
Example #3
Source File: user.py    From Reseed-backend with GNU Affero General Public License v3.0 6 votes vote down vote up
def log_in():
    username = request.form['username']
    password = request.form['password']

    user = mysql.get_user(username)
    if user:
        if not user['enable']:
            return jsonify({'success': False, 'msg': 'User has been banned! Please contact administrator.'}), 403

        # 如果用户的TJUPT账户被封禁,则将Reseed账户同时封禁
        if user['tjupt_id']:
            user_active = check_id_tjupt(user['tjupt_id'])
            if not user_active:
                mysql.ban_user(user['id'])
                return jsonify({'success': False, 'msg': 'User has been banned! Please contact administrator.'}), 403

        if bcrypt.checkpw(password.encode('utf-8'), user['passhash'].encode('utf-8')):
            return jsonify({'success': True, 'msg': 'Success~', 'token': User(user).get_auth_token()})
        else:
            return jsonify({'success': False, 'msg': 'Invalid username or password!'}), 403
    else:
        return jsonify({'success': False, 'msg': 'Invalid username or password!'}), 403 
Example #4
Source File: route_handler.py    From education-sawtooth-simple-supply with Apache License 2.0 6 votes vote down vote up
def authenticate(self, request):
        body = await decode_request(request)
        required_fields = ['public_key', 'password']
        validate_fields(required_fields, body)

        password = bytes(body.get('password'), 'utf-8')

        auth_info = await self._database.fetch_auth_resource(
            body.get('public_key'))
        if auth_info is None:
            raise ApiUnauthorized('No agent with that public key exists')

        hashed_password = auth_info.get('hashed_password')
        if not bcrypt.checkpw(password, bytes.fromhex(hashed_password)):
            raise ApiUnauthorized('Incorrect public key or password')

        token = generate_auth_token(
            request.app['secret_key'], body.get('public_key'))

        return json_response({'authorization': token}) 
Example #5
Source File: forms.py    From callisto-core with GNU Affero General Public License v3.0 6 votes vote down vote up
def get_users(self, email):
        """Get users that would match the email passed in.

        Updated to support the encrypted login format created during 2019
        Summer Maintenance.
        """
        email = sha256(email.encode("utf-8")).hexdigest()
        email_index = auth.index(email)

        active_users = models.Account.objects.filter(**{"email_index": email_index})

        return (
            User.objects.get(pk=u.user_id)
            for u in active_users
            if bcrypt.checkpw(email.encode("utf-8"), u.encrypted_email.encode("utf-8"))
        ) 
Example #6
Source File: authorization.py    From sawtooth-marketplace with Apache License 2.0 6 votes vote down vote up
def authorize(request):
    """Requests an authorization token for a registered Account"""
    required_fields = ['email', 'password']
    common.validate_fields(required_fields, request.json)
    password = bytes(request.json.get('password'), 'utf-8')
    auth_info = await auth_query.fetch_info_by_email(
        request.app.config.DB_CONN, request.json.get('email'))
    if auth_info is None:
        raise ApiUnauthorized("No user with that email exists")
    hashed_password = auth_info.get('hashed_password')
    if not bcrypt.checkpw(password, hashed_password):
        raise ApiUnauthorized("Incorrect email or password")
    token = common.generate_auth_token(
        request.app.config.SECRET_KEY,
        auth_info.get('email'),
        auth_info.get('public_key'))
    return json(
        {
            'authorization': token
        }) 
Example #7
Source File: model.py    From polycul.es with MIT License 6 votes vote down vote up
def get(cls, db, graph_hash, password, force=False):
        if len(graph_hash) < 7:
            return None
        graph_hash = graph_hash + '_' * (40 - len(graph_hash))
        result = db.execute('''select id, graph, view_pass, delete_pass, hash
            from polycules where hash like ?''', [graph_hash])
        graph = result.fetchall()
        if len(graph) != 1:
            return None
        graph = graph[0]
        polycule = Polycule(
            db=db,
            id=graph[0],
            graph=graph[1],
            view_pass=graph[2],
            edit_pass=graph[3],
            graph_hash=graph[4])
        if not force and (
                polycule.view_pass is not None and
                not bcrypt.checkpw(password.encode('utf-8'),
                                   polycule.view_pass.encode('utf-8'))):
            raise Polycule.PermissionDenied
        return polycule 
Example #8
Source File: DatabaseUser.py    From FudgeC2 with GNU General Public License v3.0 6 votes vote down vote up
def user_login(self, email, password):
        # Auths a user and returns user object
        user = self.Session.query(Users).filter(Users.user_email == email).first()
        if user is not None:
            if bcrypt.checkpw(password.encode(), user.password):
                if int(user.active_account) != 1:
                    self.db_methods.app_logging("resources", f"Failed login attempt for disabled account: {email} ")
                    return False

                self.__update_last_logged_in__(email)
                self.db_methods.app_logging("resources", f"Successful login for user: {email}")

                return user
            else:
                self.db_methods.app_logging("resources", f"Failed login attempt for user {email} ")
                return False
        else:
            self.db_methods.app_logging("resources", f"Failed login attempt for unknown account: {email} ")
            return False 
Example #9
Source File: auth_basic.py    From ironic-lib with Apache License 2.0 6 votes vote down vote up
def auth_entry(entry, password):
    """Compare a password with a single user auth file entry

    :param: entry: Line from auth user file to use for authentication
    :param: password: Password encoded as bytes
    :returns: A dictionary of WSGI environment values to append to the request
    :raises: Unauthorized, if the entry doesn't match supplied password or
        if the entry is crypted with a method other than bcrypt
    """
    username, crypted = parse_entry(entry)

    if not bcrypt.checkpw(password, crypted):
        unauthorized()

    return {
        'HTTP_X_USER': username,
        'HTTP_X_USER_NAME': username
    } 
Example #10
Source File: local.py    From kqueen with MIT License 6 votes vote down vote up
def verify(self, user, password):
        """Implementation of :func:`~kqueen.auth.base.__init__`

        This function tries to find local user and verify password.
        """

        if isinstance(user, User):
            user_password = user.password.encode('utf-8')
            given_password = password

            if bcrypt.checkpw(given_password, user_password):
                return user, None

        msg = "Local authentication failed"
        logger.info(msg)
        return None, msg 
Example #11
Source File: test_user.py    From kqueen with MIT License 6 votes vote down vote up
def test_password_update(self):
        data = {'password': 'password123'}
        url = url_for('api.user_password_update', pk=self.obj.id)

        response = self.client.patch(
            url,
            data=json.dumps(data),
            headers=self.auth_header,
            content_type='application/json',
        )

        assert response.status_code == 200
        patched = self.obj.__class__.load(
            self.namespace,
            self.obj.id,
        )
        user_password = patched.password.encode('utf-8')
        given_password = "password123".encode('utf-8')
        assert bcrypt.checkpw(given_password, user_password) 
Example #12
Source File: server.py    From steam-buddy with MIT License 6 votes vote down vote up
def authenticate_route_handler():
    AUTHENTICATOR.kill()
    password = request.forms.get('password')
    session = request.environ.get('beaker.session')
    keep_password = SETTINGS_HANDLER.get_setting('keep_password') or False
    stored_hash = SETTINGS_HANDLER.get_setting('password')
    if AUTHENTICATOR.matches_password(password) or keep_password and bcrypt.checkpw(password.encode('utf-8'), stored_hash.encode('utf-8')):
        session['User-Agent'] = request.headers.get('User-Agent')
        session['Logged-In'] = True
        session.save()
        redirect('/')
    else:
        if session.get('Logged-In', True):
            session['Logged-In'] = False
            session.save()
        if not keep_password:
            AUTHENTICATOR.reset_password()
            AUTHENTICATOR.launch()
        return template('login', keep_password=keep_password, failed=True) 
Example #13
Source File: DatabaseUser.py    From FudgeC2 with GNU General Public License v3.0 5 votes vote down vote up
def User_ChangePasswordOnFirstLogon(self, guid, current_password, new_password):
        user_object = self.Session.query(Users).filter(Users.first_logon_guid == guid).first()
        if user_object is None:
            return False
        else:
            if bcrypt.checkpw(current_password.encode(), user_object.password):
                hashedpassword = self.__hash_cleartext_password__(new_password)
                self.Session.query(Users).filter(Users.first_logon_guid == guid).update({"password": hashedpassword, "first_logon": 1})
                self.Session.commit()
                updated_user_object = self.Session.query(Users).filter(Users.password == hashedpassword).first()
                return updated_user_object
            else:
                return False

    # Test / Remove / Refactor 
Example #14
Source File: DatabaseUser.py    From FudgeC2 with GNU General Public License v3.0 5 votes vote down vote up
def __hash_cleartext_password__(password):
        # Hashed a clear text password ready for insertion into the database
        password_bytes = password.encode()
        hashedpassword = bcrypt.hashpw(password_bytes, bcrypt.gensalt())
        if bcrypt.checkpw(password_bytes, hashedpassword):
            return hashedpassword
        else:
            return False 
Example #15
Source File: Database.py    From FudgeC2 with GNU General Public License v3.0 5 votes vote down vote up
def __hash_cleartext_password__(password):
        # Hashed a clear text password ready for insertion into the database
        password_bytes = password.encode()
        hashedpassword = bcrypt.hashpw(password_bytes, bcrypt.gensalt())
        if bcrypt.checkpw(password_bytes, hashedpassword):
            return hashedpassword
        else:
            return False 
Example #16
Source File: Administrator.py    From PyRecognizer with MIT License 5 votes vote down vote up
def check_password(plain_text_password: str, hashed_password: str) -> bool:
        # Check hashed password. Using bcrypt, the salt is saved into the hash itself
        log.warning("Comparing plain: {} with hashed {}".format(
            plain_text_password, hashed_password))
        check = bcrypt.checkpw(plain_text_password, hashed_password)
        if check:
            log.debug("Password match, user logged in!")
        else:
            log.debug("Password mismatch, user NOT logged in!")
        return check 
Example #17
Source File: api_key.py    From PowerDNS-Admin with MIT License 5 votes vote down vote up
def check_password(self, hashed_password):
        # Check hashed password. Using bcrypt,
        # the salt is saved into the hash itself
        if self.plain_text_password:
            return bcrypt.checkpw(self.plain_text_password.encode('utf-8'),
                                  hashed_password.encode('utf-8'))
        return False 
Example #18
Source File: user.py    From PowerDNS-Admin with MIT License 5 votes vote down vote up
def check_password(self, hashed_password):
        # Check hashed password. Using bcrypt, the salt is saved into the hash itself
        if (self.plain_text_password):
            return bcrypt.checkpw(self.plain_text_password.encode('utf-8'),
                                  hashed_password.encode('utf-8'))
        return False 
Example #19
Source File: plugin_bcrypt.py    From deen with Apache License 2.0 5 votes vote down vote up
def process(self, data, salt=None, password=None, check=False):
        super(DeenPluginBcrypt, self).process(data)
        if not BCRYPT:
            return
        if not salt:
            salt = bcrypt.gensalt()
        if salt and not isinstance(salt, bytes):
            salt = salt.encode()
        if password and not isinstance(password, bytes):
            password = password.encode()
        if check and password:
            try:
                state = bcrypt.checkpw(password, bytes(data))
                if state:
                    data = b'Hash is valid for given password'
                else:
                    data = b'Invalid hash for given password'
            except Exception as e:
                self.error = e
                self.log.error(self.error)
                self.log.debug(self.error, exc_info=True)
                return b'Invalud input data: ' + str(e).encode()
        else:
            try:
                data = bcrypt.hashpw(bytes(data), salt)
            except ValueError as e:
                self.error = e
                self.log.error(self.error)
                self.log.debug(self.error, exc_info=True)
                return b'Invalid salt: ' + salt
        return data 
Example #20
Source File: database.py    From od-database with MIT License 5 votes vote down vote up
def check_login(self, username, password) -> bool:
        with psycopg2.connect(self.db_conn_str) as conn:
            cursor = conn.cursor()

            cursor.execute("SELECT password FROM Admin WHERE username=%s", (username,))

            db_user = cursor.fetchone()

            if db_user:
                return bcrypt.checkpw(password.encode(), db_user[0].tobytes())
            return False 
Example #21
Source File: users.py    From streamingbandit with MIT License 5 votes vote down vote up
def get_user_info(self, username, password):
        user = self.userinfo.find_one({'username':username})
        if user is not None:
            # Check password with given password
            if checkpw(password.encode('utf-8'), user['password']):
                # If correct, return user_id
                return user['user_id']
            else:
                # Else return False
                return False
        else:
            # Return error
            return None 
Example #22
Source File: csv.py    From alertR with GNU Affero General Public License v3.0 5 votes vote down vote up
def areUserCredentialsValid(self, username: str, password: str) -> bool:
        """
        This function checks if the user credentials are valid

        :param username: name of the user
        :param password: password of the user
        :return True or False
        """
        self._acquireLock()

        # Check all usernames if the given username exist
        # and then if the password is the correct one.
        for userData in self.userCredentials:

            if userData.username != username:
                continue

            else:
                if bcrypt.checkpw(password.encode("ascii"), userData.pwhash.encode("ascii")):
                    self._releaseLock()
                    return True

                else:
                    self._releaseLock()
                    return False

        self._releaseLock()
        return False 
Example #23
Source File: auth.py    From callisto-core with GNU Affero General Public License v3.0 5 votes vote down vote up
def authenticate(self, request, username, password):
        username = sha256(username.encode("utf-8")).hexdigest()
        username_index = index(username)
        for user in Account.objects.filter(username_index=username_index):
            if not user or not bcrypt.checkpw(
                username.encode("utf-8"), user.encrypted_username.encode("utf-8")
            ):
                return None

            if not check_password(password, user.user.password):
                return None

            return self.get_user(user.user.id)
        return None 
Example #24
Source File: config.py    From maubot with GNU Affero General Public License v3.0 5 votes vote down vote up
def check_password(self, user: str, passwd: str) -> bool:
        if user == "root":
            return False
        passwd_hash = self["admins"].get(user, None)
        if not passwd_hash:
            return False
        return bcrypt.checkpw(passwd.encode("utf-8"), passwd_hash.encode("utf-8")) 
Example #25
Source File: middleware.py    From aerial_wildlife_detection with MIT License 5 votes vote down vote up
def _check_password(self, providedPass, hashedTargetPass):
        return bcrypt.checkpw(providedPass, hashedTargetPass) 
Example #26
Source File: security.py    From TitleDB with The Unlicense 5 votes vote down vote up
def check_password(pw, hashed_pw):
    expected_hash = hashed_pw.encode('utf8')
    return bcrypt.checkpw(pw.encode('utf8'), expected_hash) 
Example #27
Source File: hashing.py    From manager with GNU General Public License v3.0 5 votes vote down vote up
def check_secret_matches(value_to_check, hashed_value):
    if bcrypt.checkpw(value_to_check.encode('utf-8'), hashed_value.encode('utf-8')):
        return True
    else:
        return False 
Example #28
Source File: app.py    From ambassador-auth-httpbasic with Apache License 2.0 5 votes vote down vote up
def check_auth(username, password):
    user_data = users.get(username, None)
    if user_data:
        # Passwords in the users database are stored as base64 encoded sha256 to work around the fact bcrypt only
        # supports a maximum password length of 72 characters (yes that is very long). See the below link for more
        # detail.
        #
        # see "Maximum Password Length" -> https://pypi.python.org/pypi/bcrypt/3.1.0
        sha256_password = sha256(password.encode("UTF-8")).hexdigest().encode("UTF-8")
        prepared_password = b64encode(sha256_password)

        return bcrypt.checkpw(prepared_password, user_data.get("hashed_password", "").encode("UTF-8"))
    else:
        return False 
Example #29
Source File: user.py    From SempoBlockchain with GNU General Public License v3.0 5 votes vote down vote up
def check_salt_hashed_secret(password, hashed_password):
        f = Fernet(config.PASSWORD_PEPPER)
        hashed_password = f.decrypt(hashed_password.encode())
        return bcrypt.checkpw(password.encode(), hashed_password) 
Example #30
Source File: hash.py    From Bast with MIT License 5 votes vote down vote up
def compare(cls, plain_text, hash_text):
        plain_text = str(plain_text).encode('utf-8')
        return bcrypt.checkpw(plain_text, hash_text)