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