python中的bcrypt在比较输入和存储的密码时返回false

问题描述

我知道这已经被问过好几次了,但我尝试了不同的解决方案,但似乎没有用。 “哈希”存储在我的数据库中,我可以正确地看到它,但是当我比较它时,它总是返回 False。

控制台显示TypeError:视图函数没有返回有效的响应。该函数要么返回 None 要么在没有返回语句的情况下结束。

这是我的代码

routes.py

@api.route('/signup',methods=['POST'])
def signup():
    body = request.get_json()
    password = body["password"]
    password_bytes = password.encode('utf-8')
    if len(password_bytes) > 72:
        password_bytes = base64.b64encode(hashlib.sha256(password_bytes).digest())
    hashed = bcrypt.hashpw(password_bytes,bcrypt.gensalt())
    hashed_str = hashed.decode('ascii')

    User.create_user(body["name"],body["lastname"],body["email"],hashed_str)
        
    return jsonify({}),200


@api.route("/login",methods=["POST"])
def login():
    body = request.get_json()
    email = body["email"]
    password = body["password"]
    password_bytes = password.encode('utf-8')
    user = User.get_with_email(email)
    hashed_str = user.password

    if user is None:
        raise APIException("Incorrect details")
    if len(password_bytes) > 72:
        password_bytes = base64.b64encode(hashlib.sha256(password_bytes).digest())
    valid = bcrypt.checkpw(password_bytes,hashed_str.encode('ascii'))
    print(valid)
    if(valid == True):
        access_token = create_access_token(identity = user.id)
        return jsonify({"access_token": access_token})

models.py

class User(db.Model):
    id = db.Column(db.Integer,primary_key=True)
    name = db.Column(db.String(120),unique=False,nullable=False)
    lastname = db.Column(db.String(120),nullable=False)
    email = db.Column(db.String(120),unique=True,nullable=False)
    password = db.Column(db.Text,nullable=False)
    is_active = db.Column(db.Boolean(),nullable=False)
    token = db.Column(db.String(254),nullable=True)
    propiedades = db.relationship('Propiedad',back_populates="user")

    @classmethod
    def create_user(cls,name,lastname,email,hashed_str):
        user = cls()
        user.name = name
        user.lastname = lastname
        user.email = email
        user.password = hashed_str
        user.is_active = True

        db.session.add(user)
        db.session.commit()

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)