【问题标题】:Checking a username and password from a text file从文本文件中检查用户名和密码
【发布时间】:2018-09-14 19:07:57
【问题描述】:

我正在尝试使用 python 创建一个身份验证器以添加到另一个项目中。

这是我的代码:

# User authentication
global authenticated

def checkAuth():
    global authenticated
    authenticated = False
    # User enters their username and password
    username = input("Enter your username: ")
    password = input("Enter your password: ")
    username = username.strip()
    password = password.strip()

    for line in open("users.txt","r").readlines():
        line = line.strip()
        loginInfo = line.split(",")
        print(loginInfo)
        if username == loginInfo[0] and password == loginInfo[1]:
            print("Authorised")
            authenticated = True

isAuth = checkAuth()

if (isAuth):
    input("Authorised \t Press any key to continue: ")
else:
    input("no auth")

当我运行我的代码并输入正确的用户名和密码时,checkAuth 函数中的 if 语句评估为 true,但底部的 if 语句没有得到 True 值。

这是 users.txt 文件中的两个用户名和密码组合。

users.txt file

【问题讨论】:

  • 阅读ericlippert.com/2014/03/05/how-to-debug-small-programs 了解如何调试代码的提示。
  • 我希望这只是一个“玩具”示例,并且您不打算将它用于暴露在 Internet 上且实际上需要任何形式的安全性的项目中。
  • @PM2Ring 用于学校编程任务,不会暴露在互联网上。
  • 如果用户名或密码中存在逗号,我担心使用逗号分隔用户名和密码可能会使您的代码失败。
  • @BlackThunder 这是一个很好的观点。在这种情况下,您始终可以使用正则表达式模式来检查密码验证。像^[^,]*$ 这样的东西会拒绝任何带逗号的密码

标签: python


【解决方案1】:

您要么需要if(authenticated),要么不需要将authenticated 设置为true,只需return true。你的 checkAuth() 函数是无效的,所以它没有返回值。为此使用全局变量不是一个好主意。

如果您确定要为此使用文本文件,请尝试以下操作:

def isAuthorized():
  username = input("Enter your username: ").strip()
  password = input("Enter your password: ").strip()

  with open("users.txt", "r") as f:
    for line in f:
      loginInfo = line.strip().split(",")
      if username == loginInfo[0] and password == loginInfo[1]:
        return True
    return False

if isAuthorized():
  input("Authorized \t Press any key to continue: ")
else:
  input("no auth")

为此使用文本文件不会提供任何安全性,因此请记住这一点。全局布尔值的问题是您必须在每次登录后重置它,否则即使给出错误信息,它仍将保持为真。

【讨论】:

    【解决方案2】:

    你需要从checkAuth()函数返回一个值

    checkAuth()
       ...
       ...
       return authenticated
    

    【讨论】:

      猜你喜欢
      • 2018-03-26
      • 2021-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多