0
0
Flaskframework~30 mins

User model with password in Flask - Mini Project: Build & Apply

Choose your learning style9 modes available
User model with password
📖 Scenario: You are building a simple Flask app that needs to store user information securely. You want to create a user model that keeps usernames and hashed passwords.
🎯 Goal: Create a Flask user model class called User with attributes for username and password_hash. Implement a method to set the password by hashing it and a method to check a password against the stored hash.
📋 What You'll Learn
Create a User class with username and password_hash attributes
Add a method set_password(password) that hashes the password and stores it in password_hash
Add a method check_password(password) that returns True if the password matches the stored hash
Use werkzeug.security functions generate_password_hash and check_password_hash
💡 Why This Matters
🌍 Real World
Web applications need to store user passwords securely to protect user accounts and data.
💼 Career
Understanding how to hash and verify passwords is essential for backend developers working on user authentication.
Progress0 / 4 steps
1
Create the User class with username and password_hash attributes
Create a class called User with an __init__ method that takes username and sets self.username to it. Also initialize self.password_hash to None.
Flask
Need a hint?

Define a class named User. Inside __init__, assign username to self.username and set self.password_hash to None.

2
Import password hashing functions
Add an import statement to import generate_password_hash and check_password_hash from werkzeug.security.
Flask
Need a hint?

Use from werkzeug.security import generate_password_hash, check_password_hash to import the needed functions.

3
Add set_password method to hash and store password
Inside the User class, add a method called set_password that takes password as a parameter. Use generate_password_hash(password) to create a hash and assign it to self.password_hash.
Flask
Need a hint?

Define set_password method that sets self.password_hash using generate_password_hash(password).

4
Add check_password method to verify password
Inside the User class, add a method called check_password that takes password as a parameter and returns the result of check_password_hash(self.password_hash, password).
Flask
Need a hint?

Define check_password method that returns check_password_hash(self.password_hash, password).