【问题标题】:Flask - authenticate hashed password from SQLAlchemyFlask - 验证来自 SQLAlchemy 的散列密码
【发布时间】:2018-05-02 12:06:18
【问题描述】:

当我使用名称和明文密码对用户登录进行基本身份验证时,用户已正确登录。

在注册过程中密码正确散列。 当我存储散列密码并尝试对其进行身份验证时,程序给出错误:

AttributeError: type object 'User' has no attribute 'query'

你能告诉我,有什么问题吗?我怀疑检查功能无法从 SQLAlchemy 数据库中找到散列密码。谢谢。

当我使用时:

query = s.query(User).filter(User.username.in_([POST_USERNAME]))

我明白了:

AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object associated with User.password has an attribute 'split'

   engine = create_engine('sqlite:///tutorial.db', echo=True)

   app = Flask(__name__)
   app.config.from_object(__name__)
   app.config['SECRET_KEY'] = 'XXXXX'

   def hash_password(password):
        salt = uuid.uuid4().hex
        return hashlib.sha256(salt.encode() + password.encode()).hexdigest() + ':' + salt

    def check_password(hashed_password, user_password):
        password, salt = hashed_password.split(':')
        return password == hashlib.sha256(salt.encode() + user_password.encode()).hexdigest()

   Base = declarative_base()
   class User(Base):

       __tablename__ = "users"

       id = Column(Integer, primary_key=True)
       username = Column(String(64))
       password = Column(String(120))
       email = Column(String(64))

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

       def check_password(hashed_password, user_password):
           password, salt = hashed_password.split(':')
           return password == hashlib.sha256(salt.encode() + user_password.encode()).hexdigest()

    Base.metadata.create_all(engine)

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

    @app.route('/login', methods=['POST'])
     def do_admin_login():
       POST_USERNAME = str(request.form['username'])
       POST_PASSWORD = str(request.form['password'])

       Session = sessionmaker(bind=engine)
       s = Session()
       user = User.query.filter_by(username=POST_USERNAME).first()
       if check_password(User.password, POST_PASSWORD) == True:
            session['logged_in'] = True
       else:
           flash('wrong password!')
       return index()

【问题讨论】:

    标签: python python-3.x flask sqlalchemy


    【解决方案1】:

    这样查询。 s 是您的会话。

    user = s.query(User).filter_by(username=POST_USERNAME).first()

    那么你检查密码的 if 语句是错误的。您正在尝试使用模型类而不是您刚刚获得的用户实例。应该是:

    if check_password(user.password, POST_PASSWORD) == True:

    还有其他一些提示:模块Flask-SQLAlchemy 帮助您在 Flask 中使用 SQLAlchemy(全局定义您的会话)。还可以考虑使用bcrypt 作为密码。它比 SHA 安全得多。

    【讨论】:

    • 工作,非常感谢,我花了几个小时试图解决它。我会看看 bcrypt,这只是原型,bcrypt 给出了同样的错误,所以现在应该很好了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-16
    • 2016-05-22
    • 2020-02-29
    • 1970-01-01
    • 2019-04-28
    • 2022-01-09
    相关资源
    最近更新 更多