Search code examples
pythonpostgresqlfastapibcrypt

storing and retrieving hashed password in postgres


I am watching a tutorial on FastAPI, where it switched the database from SQLite to PostgreSQL, before generating a token. It was working before but now it has an error, shown below

return bcrypt.checkpw(password=password_byte_enc, hashed_password=hashed_password) TypeError: argument 'hashed_password': 'str' object cannot be converted to 'PyBytes'

I think this is the code concerning the error:

def get_password_hash(password):
    # return bcrypt_context.hash(password)
    pwd_bytes = password.encode('utf-8')
    salt = bcrypt.gensalt()
    hashed_password = bcrypt.hashpw(password=pwd_bytes, salt=salt)
    return hashed_password


def verify_password(plain_password, hashed_password):
    password_byte_enc = plain_password.encode('utf-8')
    return bcrypt.checkpw(password=password_byte_enc, hashed_password=hashed_password)

The entirity of the auth.py file is here https://pastebin.com/mHcd0YLU

This is where I input the username and password to generate a token but it gets an error: username and password input


Solution

  • SOLVED after hashing, using the decode property is needed to store correctly the hash password in the postgres database

    def get_password_hash(password):
        pwd_bytes = password.encode('utf-8')
        salt = bcrypt.gensalt()
        hashed_password = bcrypt.hashpw(password=pwd_bytes, salt=salt)
        string_password = hashed_password.decode('utf8')
        return string_password
    
    
    def verify_password(plain_password, hashed_password):
        password_byte_enc = plain_password.encode('utf-8')
        hashed_password = hashed_password.encode('utf-8')
        return bcrypt.checkpw(password_byte_enc, hashed_password)
    

    if any other has a better solution i am open for it