[Flask] Validate the user credentials separately when logging users in
Validate the user credentials separately when logging users in
It’s common to query the DB directly during login to get the hashed password to compare with the entered password, rather than relying on a method that returns a “safe” user object, which doesn't store the hashed password at all. The hashed password is only needed for a brief moment—when verifying credentials. After that, the user object can omit it entirely. It’s common to keep a separate function or route that queries the database directly, grabs the hashed password, and checks it immediately—only at login time.
Example
def log_in(email, entered_password): user_doc = user_collection.find_one({"user_email": email}) if user_doc: hashed_pw = user_doc["password"] # hashed password from DB if bcrypt.checkpw(entered_password.encode(), hashed_pw): # Password is correct user = User( user_id=str(user_doc["_id"]), user_email=user_doc["user_email"], game_list=user_doc.get("game_list", []), ) login_user(user) # Flask-Login return user return None # or raise an error
Key Points:
-
Only log_in() queries the DB for the hashed password.
-
Once verified, a
Userobject is instantiated without storing the password field, because it is not needed anymore.
Comments
Post a Comment