English 中文(简体)
Flask - 简单的Login页 - Invalid Hashed Password
原标题:Flask - Simple Login Page - Invalid Hashed Password

我正试图利用弗拉茨-斯密特建立一个基本的微薄标志页面,安全地储存数据库中的密码。

Based on the debugging it prints: Attempting password verification... Checking password for user: admin Hashed password from attempt: b 89ABrlAbxdOeLlup4L96Cv5sqsFL7xYmPNrS/fZ58Po40J4+zK8BqYZTt9Gqkm+/+fRKs/etPSTyJHfeRlFLg== Stored hashed password: 89ABrlAbxdOeLlup4L96Cv5sqsFL7xYmPNrS/fZ58Po40J4+zK8BqYZTt9Gqkm+/+fRKs/etPSTyJHfeRlFLg== Invalid password Rendering login.html...

这里就是这些模式。 py:

# app/models.py

from . import db
from flask_scrypt import generate_random_salt, generate_password_hash, check_password_hash
import os
import base64

class User(db.Model):
    __tablename__ =  users 
    userID = db.Column( userID , db.Integer, primary_key=True)
    username = db.Column( username , db.String(50), unique=True, nullable=False)
    password_hash = db.Column( password_hash , db.String(200), nullable=False)
    salt = db.Column( salt , db.String(200), nullable=False)

    def __init__(self, username, password):
        self.username = username
        self.set_password(password)

    def set_password(self, password):
        self.salt = generate_random_salt()
        print("Salt before hashing:", self.salt)  # Debugging
        password_bytes = password.encode( utf-8 )
        self.password_hash = generate_password_hash(password_bytes + self.salt, salt=self.salt)

    def check_password(self, password):
        print("Checking password for user:", self.username)
        password_bytes = password.encode( utf-8 )
        salt_bytes = self.salt.encode( utf-8 )
        hashed_password_attempt = generate_password_hash(password_bytes + salt_bytes, salt=salt_bytes)
        print("Hashed password from attempt:", hashed_password_attempt)  # Debugging
        print("Stored hashed password:", self.password_hash)  # Debugging
        return check_password_hash(self.password_hash, password_bytes, salt=salt_bytes)

这里是路线。 y

from flask import Blueprint, render_template, redirect, url_for, flash
from flask_login import login_user
from .forms import LoginForm
from .models import User
from . import db

auth = Blueprint("auth", __name__)
main = Blueprint("main", __name__)
admin = Blueprint("admin", __name__)

@auth.route("/login", methods=[ GET ,  POST ])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        # Retrieve user record from the database based on the provided username
        user = User.query.filter_by(username=form.username.data).first()
        print("User:", user)  # Debugging: Print user to check if retrieved
        if user:
            # Verify the password
            print("Attempting password verification...")  # Debugging: Check password verification attempt
            if user.check_password(form.password.data):
                # Password matches, authentication successful
                print("Password verified. Logging in...")  # Debugging: Indicate successful password verification
                login_user(user)
                return redirect(url_for( admin.admin_panel ))
            else:
                # Password doesn t match, render login page with error message
                print("Invalid password")  # Debugging: Indicate invalid password
                flash( Invalid username or password ,  error )
        else:
            # User not found, render login page with error message
            print("User not found")  # Debugging: Indicate user not found
            flash( Invalid username or password ,  error )

    # If GET request or form validation failed, render the login page
    print("Rendering login.html...")  # Debugging: Indicate rendering of login.html
    return render_template( login.html , form=form)

@main.route("/")
def index():
    return render_template("index.html")

@admin.route("/admin")
def admin_panel():
    return render_template("admin.html")

它正在研究我的奇克勒数据库的细节,并依据的是,它正在寻找正确的密码,但认为这是无效的。

我尝试了笔录中的一些改动。

问题回答

我认为,你对口语和便衣口说不正确,也好像。

from flask_scrypt import (
    generate_random_salt,
    generate_password_hash,
    check_password_hash,
)


def save_password(password: str) -> tuple[str, str]:
    password_salt = generate_random_salt()
    password_hash = generate_password_hash(password, password_salt)
    return password_salt, password_hash.decode()


def validate_password(plain_password: str, salt: str, hash_password: bytes) -> bool:
    return check_password_hash(plain_password, hash_password, salt)


if __name__ == "__main__":
    user_password = "very_secret_password"
    salt_gen, hash_pass = save_password(user_password)
    is_valid = validate_password(user_password, salt_gen, hash_pass.encode())
    print(is_valid)  # this value is supposed to true

For function check_password_hash(plain_password, hash_password, salt) it should

  • plain_password in the 1st argument
  • hash_password that is stored in db in 2nd argument
  • salt that is stored in db on 3rd argument.

就像这样。

return check_password_hash(password_bytes, self.password_hash, salt=salt_bytes)

第二点是,你不需要再把产生的海口与这种盐类混为一谈,这已经混淆了口号。

hashed = generate_password_hash(plain, salt) # -> already mixed with the salt

但你所写的是

hashed = generate_password_hash(plain + salt, salt) # this is double salt

你们可以这样简单地这样做。

self.password_hash = generate_password_hash(password_bytes, salt=self.salt)




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签