65 lines
1.8 KiB
Python
65 lines
1.8 KiB
Python
|
import csv
|
|||
|
|
|||
|
|
|||
|
def register(username, password):
|
|||
|
# 读取现有的用户信息
|
|||
|
existing_users = read_users()
|
|||
|
|
|||
|
# 检查用户名是否已存在
|
|||
|
if username in existing_users:
|
|||
|
return False, "Username already exists."
|
|||
|
|
|||
|
# 添加新用户信息
|
|||
|
new_user = {"username": username, "password": password}
|
|||
|
existing_users[username] = new_user
|
|||
|
|
|||
|
# 将用户信息保存到CSV文件
|
|||
|
save_users(existing_users)
|
|||
|
|
|||
|
return True, "Registration successful."
|
|||
|
|
|||
|
|
|||
|
def login(username, password):
|
|||
|
# 读取用户信息
|
|||
|
existing_users = read_users()
|
|||
|
|
|||
|
# 验证用户名和密码
|
|||
|
user = existing_users.get(username)
|
|||
|
if user and user["password"] == password:
|
|||
|
return True, "Login successful."
|
|||
|
return False, "Invalid credentials."
|
|||
|
|
|||
|
|
|||
|
def read_users():
|
|||
|
# 从CSV文件中读取用户信息
|
|||
|
users = {}
|
|||
|
try:
|
|||
|
with open("data/users.csv", "r", newline="") as csvfile:
|
|||
|
reader = csv.DictReader(csvfile)
|
|||
|
for row in reader:
|
|||
|
users[row["username"]] = {"username": row["username"], "password": row["password"]}
|
|||
|
except FileNotFoundError:
|
|||
|
pass # 如果文件不存在,说明还没有注册用户,返回一个空字典
|
|||
|
return users
|
|||
|
|
|||
|
|
|||
|
def save_users(users):
|
|||
|
# 将用户信息保存到CSV文件
|
|||
|
with open("data/users.csv", "w", newline="") as csvfile:
|
|||
|
fieldnames = ["username", "password"]
|
|||
|
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
|
|||
|
writer.writeheader()
|
|||
|
for user in users.values():
|
|||
|
writer.writerow(user)
|
|||
|
|
|||
|
# 测试注册功能
|
|||
|
# register("user1", "password1")
|
|||
|
# register("user2", "password2")
|
|||
|
|
|||
|
# 测试登录功能
|
|||
|
# login_success, message = login("user1", "password1")
|
|||
|
# print(message) # 输出:Login successful.
|
|||
|
#
|
|||
|
# login_success, message = login("user3", "password3")
|
|||
|
# print(message) # 输出:Invalid credentials.
|