Bird
Raised Fist0
Flaskframework~10 mins

User model with password in Flask - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - User model with password
Define User class
↓
Add password field (hashed)
↓
Create set_password method
↓
Hash plain password
↓
Store hashed password
↓
Create check_password method
↓
Compare input password hash with stored hash
↓
Return True if match, else False
This flow shows how a User model stores a hashed password and checks it securely.
Execution Sample
Flask
from werkzeug.security import generate_password_hash, check_password_hash

class User:
    def __init__(self, username):
        self.username = username
        self.password_hash = ''
    def set_password(self, password):
        self.password_hash = generate_password_hash(password)
    def check_password(self, password):
        return check_password_hash(self.password_hash, password)
Defines a User class that hashes passwords when set and verifies passwords by comparing hashes.
Execution Table
StepActionInputPassword HashOutput
1Create User instanceusername='alice'''User object created
2Call set_passwordpassword='secret123'hash('secret123')Password hash stored
3Call check_passwordpassword='secret123'hash('secret123')True (password matches)
4Call check_passwordpassword='wrongpass'hash('secret123')False (password does not match)
5Endhash('secret123')Process complete
💡 Password check returns False when input password hash does not match stored hash
Variable Tracker
VariableStartAfter set_passwordAfter check_password(True)After check_password(False)
usernamealicealicealicealice
password_hash''hash('secret123')hash('secret123')hash('secret123')
check_password resultN/AN/ATrueFalse
Key Moments - 2 Insights
Why do we store a hashed password instead of the plain password?
Storing a hashed password protects user security. The execution_table shows the password_hash stores a hash, not the plain password, preventing exposure if the database leaks.
How does check_password know if the password is correct?
check_password hashes the input and compares it to the stored hash. The execution_table rows 3 and 4 show True when hashes match and False when they don't.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the password_hash after calling set_password with 'secret123'?
A'' (empty string)
Bsecret123
Chash('secret123')
DNone
💡 Hint
Check Step 2 in the execution_table under Password Hash column
At which step does check_password return False?
AStep 4
BStep 3
CStep 2
DStep 1
💡 Hint
Look at the Output column in execution_table for check_password calls
If we change the input password in set_password, what changes in variable_tracker?
Ausername changes
Bpassword_hash changes
Ccheck_password result changes immediately
DNothing changes
💡 Hint
See variable_tracker row for password_hash after set_password
Concept Snapshot
User model stores password securely by hashing it.
Use set_password to hash and save the password.
Use check_password to verify input against stored hash.
Never store plain passwords.
Use werkzeug.security helpers for hashing.
This protects user data if database leaks.
Full Transcript
This example shows a User class in Flask that handles passwords safely. When a password is set, it is hashed using generate_password_hash and stored in password_hash. When checking a password, check_password_hash compares the input password's hash with the stored hash. The execution table traces creating a user, setting a password, and checking it with correct and incorrect inputs. The variable tracker shows how password_hash changes after setting the password and how check_password returns True or False. Key moments clarify why hashing is important and how password verification works. The visual quiz tests understanding of password hashing and verification steps. This approach keeps user passwords safe by never storing them in plain text.

Practice

(1/5)
1. What is the main purpose of the set_password method in a Flask user model?
easy
A. To delete the user's password from the database
B. To hash and store the user's password securely
C. To check if the password entered matches the stored password
D. To display the user's password in plain text

Solution

  1. Step 1: Understand the role of set_password

    This method is used to convert a plain password into a secure hashed version before saving it.
  2. Step 2: Differentiate from check_password

    check_password is for verifying passwords, not setting them.
  3. Final Answer:

    To hash and store the user's password securely -> Option B
  4. Quick Check:

    set_password hashes password [OK]
Hint: Remember: set_password hashes, check_password verifies [OK]
Common Mistakes:
  • Confusing set_password with check_password
  • Thinking set_password shows the password
  • Assuming set_password deletes passwords
2. Which of the following is the correct way to define a password hashing method in a Flask user model using Werkzeug?
easy
A. def set_password(self, password): return check_password_hash(self.password_hash, password)
B. def set_password(self, password): self.password = password
C. def set_password(self, password): self.password_hash = password
D. def set_password(self, password): self.password_hash = generate_password_hash(password)

Solution

  1. Step 1: Identify correct hashing usage

    The method must use generate_password_hash to hash the password before storing.
  2. Step 2: Check assignment to password_hash

    The hashed password should be saved in self.password_hash, not plain password.
  3. Final Answer:

    def set_password(self, password): self.password_hash = generate_password_hash(password) -> Option D
  4. Quick Check:

    Use generate_password_hash to store hashed password [OK]
Hint: Use generate_password_hash to hash passwords [OK]
Common Mistakes:
  • Storing plain password instead of hashed
  • Using check_password_hash inside set_password
  • Assigning password to wrong attribute
3. Given this Flask user model snippet, what will user.check_password('secret') return if the password was set with user.set_password('secret')?
from werkzeug.security import generate_password_hash, check_password_hash

class User:
    def __init__(self):
        self.password_hash = ''
    def set_password(self, password):
        self.password_hash = generate_password_hash(password)
    def check_password(self, password):
        return check_password_hash(self.password_hash, password)

user = User()
user.set_password('secret')
medium
A. None
B. False
C. True
D. Raises an error

Solution

  1. Step 1: Understand password setting

    The password 'secret' is hashed and stored in password_hash.
  2. Step 2: Check password verification

    check_password compares the hash with 'secret' and returns True if they match.
  3. Final Answer:

    True -> Option C
  4. Quick Check:

    Matching password returns True [OK]
Hint: check_password returns True if password matches hash [OK]
Common Mistakes:
  • Expecting False for correct password
  • Thinking check_password returns the hash
  • Assuming error if password matches
4. Identify the error in this Flask user model code snippet:
from werkzeug.security import generate_password_hash, check_password_hash

class User:
    def __init__(self):
        self.password_hash = None
    def set_password(self, password):
        self.password_hash = generate_password_hash(password)
    def check_password(self, password):
        return check_password_hash(password, self.password_hash)
medium
A. The order of arguments in check_password_hash is reversed
B. password_hash should be initialized as an empty string, not None
C. set_password should return the hashed password
D. The class is missing a username attribute

Solution

  1. Step 1: Review check_password_hash usage

    The correct order is check_password_hash(stored_hash, password).
  2. Step 2: Identify argument mistake

    The code passes password first and self.password_hash second, which is wrong.
  3. Final Answer:

    The order of arguments in check_password_hash is reversed -> Option A
  4. Quick Check:

    check_password_hash needs (hash, password) order [OK]
Hint: check_password_hash(hash, password) order matters [OK]
Common Mistakes:
  • Swapping arguments in check_password_hash
  • Initializing password_hash as None causes no error but is not best
  • Expecting set_password to return a value
  • Confusing missing attributes with password errors
5. You want to add a method change_password to your Flask user model that updates the password only if the old password matches. Which implementation correctly applies this logic?
hard
A. def change_password(self, old_password, new_password): if self.check_password(old_password): self.set_password(new_password) return True return False
B. def change_password(self, old_password, new_password): self.set_password(new_password) return True
C. def change_password(self, old_password, new_password): if old_password == new_password: self.set_password(new_password) return True return False
D. def change_password(self, old_password, new_password): if not self.check_password(new_password): self.set_password(old_password) return True return False

Solution

  1. Step 1: Verify old password before changing

    The method must check if the old password matches using check_password.
  2. Step 2: Update password only if old password is correct

    If the check passes, call set_password with the new password and return True; else return False.
  3. Final Answer:

    def change_password(self, old_password, new_password): if self.check_password(old_password): self.set_password(new_password) return True return False -> Option A
  4. Quick Check:

    Change password only if old password matches [OK]
Hint: Always verify old password before setting new one [OK]
Common Mistakes:
  • Changing password without verifying old password
  • Comparing old and new passwords incorrectly
  • Swapping old and new passwords in checks
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard