You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python+SQLite3+Kivy登录脚本:登录验证逻辑错误求助

登录验证问题的修复方案

核心问题分析

  1. 逻辑判断完全反转:if not c.fetchone() 意为「数据库未找到匹配记录时」执行登录成功,和预期逻辑完全相反。
  2. 密码哈希验证方式错误:pbkdf2_sha256每次哈希会生成随机盐,直接重新哈希输入密码和数据库存储的哈希值对比永远无法匹配,必须用专门的验证方法校验。
  3. 存在SQL注入风险:字符串拼接SQL语句,恶意输入可能破坏或泄露数据库数据。

修正后的代码

def login_menu_press(self):
    login = False

    lusername = self.login_username.text.strip()
    lpassword = self.login_password.text.strip()
    print(f"Your username is {lusername}, and your password is {lpassword}.")
    self.login_username.text = ""
    self.login_password.text = ""

    # 加密上下文可提前初始化,无需每次登录重复创建
    context = CryptContext(
        schemes=["pbkdf2_sha256"],
        default="pbkdf2_sha256",
        pbkdf2_sha256__default_rounds=50000
    )

    # 使用with语句自动管理数据库连接,避免资源泄漏
    with sqlite3.connect('users.db') as conn:
        c = conn.cursor()
        # 参数化查询,彻底避免SQL注入
        c.execute("SELECT Password from users WHERE username=?", (lusername,))
        result = c.fetchone()

        if result:
            # 取出数据库中存储的哈希密码
            stored_hash = result[0]
            # 用verify方法验证明文密码与哈希的匹配性
            if context.verify(lpassword, stored_hash):
                print("Login successful")
                login = True
            else:
                print("Login failed: Invalid password")
        else:
            print("Login failed: Username not found")

关键修改说明

  • 改用参数化SQL查询,用?作为占位符传递参数,杜绝SQL注入风险。
  • 先查询用户对应的存储哈希,再通过context.verify()验证明文密码与哈希的匹配性,这是带盐哈希算法的标准验证流程。
  • 拆分错误提示:区分「用户名不存在」和「密码错误」,方便定位问题。
  • 用with语句管理数据库连接,自动完成连接关闭,避免资源泄漏。
  • 对输入的用户名/密码做strip()处理,避免首尾空字符导致的无效查询。

内容的提问来源于stack exchange,提问作者maxyaners

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 23:45:59