2014-04-30 76 views
0

嗨。我正在嘗試創建一個能夠創建用戶然後登錄的程序。登錄後,您可以更改密碼。我似乎無法弄清楚的是如何在您登錄後使用舊密碼來更改密碼。我可以通過輸入您的帳戶名稱來實現它,但那不是重點。 做任何你有如何解決這個問題的任何想法,我願意接受建議:)使用json的賬戶管理

import json 

with open("login_data.txt", "r") as login_file: 
    try: 
     users = json.load(login_file) 
    except: 
     users = {} 

status = "" 

def Display_Menu(): 

    status = input("Are you a registered user? (y/n)? Press q to quit: ") 
    if status == "y": 
     Old_User() 
    elif status == "n": 
     New_User() 
    elif status == "passwd": 
     Change_Passwd() 
    elif status == "q": 
     skriva = open("login_data.txt", "w") 
     json.dump(users, skriva) 
    return status 

def New_User(): 

    Create_Login =input("Create login name: ") 
    if Create_Login in users: 
     print ("Login name already exist!") 
    else: 
     Create_Password =input("Create password: ") 
     users[Create_Login] = Create_Password 
     print("New User created!") 

def Old_User(): 

    login =input("Enter login name: ") 
    Password =input("Enter password: ") 

    if login in users and users[login] == Password: 

     print("Login successful!") 
     print(users[login]) 

     status = input("Wanna quit, change pass, och logout?")  
     if status == "passwd": 
      Change_Passwd() 
     elif status == "logout": 
      Display_Menu() 
     elif status == "q": 
      skriva = open("login_data.txt", "w") 
      json.dump(users, skriva) 
     return status 

    else: 
     print("User doesn't exist or wrong password!") 

def Change_Passwd(): 

    oldpass =input("Old password: ") 

    if oldpass in users: 
     Create_Password =input("New password: ") 
     users[oldpass] = Create_Password 

     if Create_Password == input("Confirm password: "): 
      print("Password changed!") 
     else: 
      print("User authorization failure") 
      users[create_Login] = oldpass 
    else: 
     print ("No password match!") 


while status != "q":    
    status = Display_Menu() 

一個帳戶文件的例子「{‘暈’:‘莫莉’}」

回答

0

最小的改變是將當前登錄的用戶保存到Old_User()中的全局變量中。然後,當調用Change_Passwd時,您可以返回到該變量以確定您正在處理哪個用戶。以下是您對Old_User所做的更改。我將把Change_Passwd的更改保留給您執行。

current_user = None # Declare global variable for saving logged in user 
def Old_User(): 
    global current_user # Indicate that we're going to modify the global variable in the local scope 

    login =input("Enter login name: ") 
    Password =input("Enter password: ") 

    if login in users and users[login] == Password: 

     print("Login successful!") 
     print(users[login]) 
     current_user = login # Save the logged in user. 
     ... 

我還應該補充說,你最好使用這個類。嘗試使用全局變量維護狀態(如當前用戶的身份)不具有可伸縮性,並且可能會很快產生混淆。有代表用戶和活動會話的課程會讓事情變得更容易。