Search code examples
pythonauthenticationaccount

How to create a login system that can validate user to enter valid username and password?


I was trying to create a login system that can check if the username and password is include in the userlist (which I use it to store different user password and their name).

userlist = []
def userpage():
     print("user page accessed")
     opt = int(input("Enter '0' to log out"))
     if opt == 0:
          mainpage()

def signin():
     username = input("Please enter username: ")
     for user in userlist:
          if username in user:
               password = input("Please enter password: ")
               if password in user:
                    userpage()
               else:
                    print("Incorrect password")
                    mainpage()
          else:
               print("Unregister username")
               mainpage()

def signup():
     username = input("Please enter username: ")
     password = input("Please enter password: ")
     userlist.append([username,password])
     print(userlist)
     userpage()

def mainpage():
     opt = int(input("Enter '0' to sign up, '1' to sign in: "))
     if opt == 0:
          signup()
     elif opt == 1:
          signin()
mainpage()

Notice that I use print(userlist) to check whether the username and password is being store in the list or not. The signup function works(As from what I saw from the print(userlist), but there's issue with signin function(which I want to use it to check valid username and password). As the user will straight away access the userpage after they signup, the signin function works when the first user signup and sign in again after they logout. But the follow up user signup and wanted to sign in again after log out, it will keep saying it is an unregister username, but I can clearly see that the userlist have their username.


Solution

  • Your problem is that you raise an error immediately if the first array of credentials does not match. It checks the first user-password pair, then if it doesn't match,you raise an error. So your code should be:

    def signin():
         username = input("Please enter username: ")
         for c,user in enumerate(userlist):
              if username in user:
                   password = input("Please enter password: ")
                   if password in user:
                        userpage()
                   else:
                        print("Incorrect password")
                        mainpage() 
              else:
                   if c != len(userlist):
                        pass                    
                   else:
                        print("Unregistered username")
                        mainpage()