This article explains how to securely hash user passwords before storing them in a database to enhance application security.
Earlier, we outlined the process for creating a new user. However, storing passwords as plain text poses a significant security risk. Even if your database is secure now, a breach could expose these passwords to attackers. Instead, always store a hashed version of the password. Hashing is a one-way process that makes it practically impossible to retrieve the original password from its hash.For instance, running the following SQL command:
Copy
Ask AI
select * from users;
reveals that storing plain text passwords (as the query would show) is unsafe. Always hash passwords before saving them to your database.
To implement password hashing, you need two libraries: Passlib (which supports multiple hashing algorithms) and bcrypt (the algorithm we will use). Install them using pip:
Copy
Ask AI
pip install passlib[bcrypt]
Alternatively, install both libraries directly:
Copy
Ask AI
pip install passlib bcrypt
After installation, verify that both libraries are installed by running pip freeze.
To improve code maintainability, extract the password hashing logic into a separate utility function. Create a new file named utils.py with the following content:
Update the user registration endpoint to use the utility function for hashing:
Copy
Ask AI
@app.post("/users", status_code=status.HTTP_201_CREATED, response_model=schemas.UserOut)def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)): # Hash the user's password using the utility function from utils.py hashed_password = utils.hash(user.password) user.password = hashed_password new_user = models.User(**user.dict()) db.add(new_user) db.commit() db.refresh(new_user) return new_user
After testing the endpoint—by creating a new user (e.g., email “[email protected]” with password “password123”)—query the users table:
Copy
Ask AI
select * from users;
This query will confirm that the application stores only the hashed password, significantly reducing security risks in the event of a data breach.
By following these steps, you enhance your application’s security by ensuring user passwords are hashed rather than stored in plain text. This practice is essential for maintaining user data integrity.