微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决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 举报,一经查实,本站将立刻删除。