So, I have a program that acts like a local login/signup system. It asks the user if they want to signup, or login. If they signup, they shall type a username and password in a certain format and it puts it in a file.
If they choose to login, the program will assume that what they're about to type in is located in the file. The intended use is that if it is in the file, it will say that the account is valid. If the thing that the user typed in isn't located in the file, it should say that it is not a valid account.
As of now, the output always says that the account isn't valid, even though it is in the file. Here is the login portion of the code:
elif sol == "l":
os.system("clear")
print("You have chosen to login.")
time.sleep(2)
os.system("clear")
datasearch = input("What is your username and password?(username/password): ")
with open ("user_database.txt", "r") as searchdata:
if datasearch in os.linesep:
os.system("clear")
print("This is a valid account!")
time.sleep(3)
os.system("clear")
quit()
else:
os.system("clear")
print("This is not a valid account!")
time.sleep(3)
os.system("clear")
You are not searching the file. You are checking if the users input is in os.linesep.
You should put something like if datasearch in searchdata.read(): inplace of if datasearch in os.linesep: in your code.
Related
I have a program that asks the user for a username and password, then checks a text file to see if that username/password are in there. Then it is supposed to print the contents of the text file to screen. A couple of issues:
It ALWAYS takes two attempts to successfully log in, even if the username/password are correct.
On successful login, the contents of the text file are not printed.
Would very much appreciate some guidance on why these things are happening, and how they can be resolved!
def option3():
print('\nGelos Enterprise User Accounts\n')
global index_num,userName,passWord,balances,username,password
username=input("Enter your username : ")
password=input("Enter your password : ")
fileRead=open('accounts.txt','r')
fileContents = fileRead.read()
flag=False
while True:
line=fileRead.readline()
lineLength=len(line)
if lineLength==0:
break
lineItem=line.split()
if username.strip()==lineItem[0] and password.strip()==lineItem[1] :
print("\nHello",username,"you have logged in successfully."'\n')
print("Displaying all usernames and passwords: \n")
time.sleep(2)
print(fileContents)
flag=True
break
if flag==False:
print("\nThe user is not found.Please re-enter your username and password.\n")
option1()
I would try something like this.
def print_file_contents(file_name):
with open(file_name) as f:
for line in f:
print(line)
def option3():
print('\nGelos Enterprise User Accounts\n')
global index_num,userName,passWord,balances,username,password
username=input("Enter your username : ")
password=input("Enter your password : ")
file = 'accounts.txt'
flag = False
for line in open(file).readlines():
lineItem=line.split()
if username.strip() == lineItem[0] and password.strip() == lineItem[1] :
print("\nHello",username,"you have logged in successfully."'\n')
print("Displaying all usernames and passwords: \n")
time.sleep(2)
print_file_contents(file)
flag=True
break
if not flag:
print("\nThe user is not found.Please re-enter your username and password.\n")
option1()
However I haven't really modified what the code does, and I suspect the issue comes with how the text file is formatted.
I also assume this is a project and not actual passwords stored in a .txt file which wouldn't be a great idea.
I'm making a program in Python for a class that involves logging in to get to the main GUI. Currently, this file has 3 sets of usernames and passwords. My intention was for when the user clicks a button, the program reads through all account username and password combinations from a txt file, and if it does not find a match, an error message shows up. Right now it is giving that error message after it reads each set of names. So if I try to sign in with the last account's information in the file, it will give me the error 2 times, then proceed to log in. If anyone has any advice to help fix my logic, I'd greatly appreciate it.
def verify_login(login):
user = login.login_window.username_entry.get()
password = login.login_window.password_entry.get()
accounts = open("accounts.txt",'r')
for line in accounts.readlines():
login_info = line.split()
if (user == login_info[0] and password == login_info[1]):
print("Account found. Logging in...")
###
### take to main gui
###
else:
tk.messagebox.showerror("Error", "Account not found. Try again.")
login.login_window.username_entry.delete(0,END)
login.login_window.password_entry.delete(0,END)
Like this:
def verify_login(login):
user = login.login_window.username_entry.get()
password = login.login_window.password_entry.get()
accounts = open("accounts.txt",'r')
found = False
for line in accounts.readlines():
login_info = line.split()
if (user == login_info[0] and password == login_info[1]):
print("Account found. Logging in...")
found = True
break
###
### take to main gui
###
if not found:
tk.messagebox.showerror("Error", "Account not found. Try again.")
login.login_window.username_entry.delete(0,END)
login.login_window.password_entry.delete(0,END)
If you return during the "success" processing, then you don't need the found flag. Once you exit the loop, you know you have a failure.
Ok guys, I'm pretty much new to programing. I figured out, that I can learn to code writing something, that can have potential to actually be useful in future, so I made this code. Im trying to give myself 2 options 1 to login and 2 to register. When I register everything works, It encrypts my text into sha256 and writes it into file, but when i try to "login" the open read function deletes content of file Login.txt, so the check logicly fails. Thanks you in advance.
import hashlib
#Creating file to save token into.
login_file = open("Login.txt", "w")
def register():
print("Please insert your token:")
reg_token = input()
#Encrypting and writing token into file.
login_file.write(hashlib.sha256(reg_token.encode()).hexdigest())
login_file.close()
print("Registration completed.")
def login():
token_file = open("Login.txt", "r").read()
print("Please login with your token:")
log_token = input()
#Calculating hash for input.
hash = hashlib.sha256(log_token.encode()).hexdigest()
#Comparing hashes.
if hash == token_file:
print("Success!")
if hash != token_file:
print("Login was unsuccessful.")
def prompt():
print("For login type 1. For registration type 2.")
prompt_input = input()
if prompt_input == "1":
login()
if prompt_input == "2":
register()
###############################################################################
prompt()
The line where you first open the file should be inside the register() function.
The second argument to open() determines how the file is handled. ”w” deletes the content first. ”a” will allow you to append to the file.
I am creating a quiz algorithm which utilities a log in system. For the sign up process, the usernames and passwords are stored in a text file and are read in order to see if they already exist.If this is the case, the user is told that the username or password already exists and this is repeated until something that doesn't already exist is input. When this happens,the text file is appended to add the username. For some reason however, the program doesn't check if the user attempt is already in the text file,but just adds it to the text file, even if it already exists.
The log in procedure, which does the first part of checking if a string is the same in both the variable and text file works just fine. The program checks if the username and password are in the files and if they are it logs in. The hashed code is used for testing and will be removed when the program works.
##Sign up
if Option == ("2"):
exit = False
while exit == False:
Userattempt = input("Please enter a username:\n>>> ")
file = open("Usernames.txt","r")
searchline = file.readline()
Flag = False
Username = ""
for line in file:
print(Userattempt, line)# used to see how the program goes through each line
Username = str(line)
if Userattempt == Username:
Flag = True
print("Yes", Userattempt, line)# Used to test after each line
else:
print("False")# Used to test after each line
if Flag == True:
print("That Username already exists, Please try another")
else:
#file.close()
file = open("Usernames.txt","a")
file.write(Userattempt)
file.write("\n")
print("Okay",Userattempt, "is your username")
exit = True
file.close()
This program runs fine, but for some reason it doesn't check if the user input is equal to each line and if it does,the flag used to catch that the username or password already exists isn't changed.
The main reason it's not working is that you didn't remove the newline from the line being read from the file, so it never matches the user input.
You have other problems with the program logic. You shouldn't write the new username inside the for loop, because you don't know if the username is available until you get to the end of the file.
Instead of the Flag variable, you can use the else: block of the for loop. This will run if the loop completes normally instead of from a break statement. Then you break out of the loop when finding a matching line in the file.\
It's generally best to use a with statement to open a file and automatically close it when done.
##Sign up
if Option == ("2"):
while True:
Userattempt = input("Please enter a username:\n>>> ")
with open("Usernames.txt","r") as file:
for line in file:
Username = line.strip()
print(Userattempt, Username)# used to see how the program goes through each line
if Userattempt == Username:
print("That Username already exists, Please try another")
break # break out of for-loop
else: # name not found, so add it
with open("Usernames.txt","a") as outfile:
outfile.write(Userattempt)
outfile.write("\n")
print("Okay",Userattempt, "is your username")
break # break out of while-loop
The problem I have right now is that for my dictionary that uses a key:value to store username:password is that every time I rerun the program, the current key:value is reset and the dictionary is set to empty again. The goal of my program is to have a person log in with a username and password and be able to store notes and passwords (I did this with python .txt files). Then the next person can come along, create an account and do the same. Here is my code (I have commented every line of code pertaining to my problem):
def userPass():
checkAccount = input("Do you have an account (Y or N)?")
if (checkAccount == 'N' or checkAccount == 'n'):
userName = input("Please Set Your New Username: ")
password = input("Please Set Your New Password: ")
// if (userName in dictAcc):
print("Username is taken")
userPass()
else:
// dictAcc[userName] = password
print("Congratulations! You have succesfully created an account!")
time.sleep(1.5)
dataInput()
elif(checkAccount == 'Y' or checkAccount == 'y'):
login()
else:
print("Invalid answer, try again")
userPass()
def login():
global userName
global password
global tries
loginUserName = input("Type in your Username: ")
loginPass = input("Type in your Password: ")
if (tries < 3):
// for key in dictAcc:
// if (loginUserName == key and loginPass == dictAcc[key]):
// print("You have successfully logged in!")
dataInput()
else:
print("Please try again")
tries += 1
login()
if (tries >= 3):
print("You have attempted to login too many times. Try again later.")
time.sleep(300)
login()
userPass()
As others have mentioned, you need to have your dictionary saved into a file and load it when you restart your program. I adjusted your code to work for me and created two functions, one to save the dictionary (savedict) and another to load it (loaddict). The except IOError part is just so that it creates a new file if it doesn't exist.
Note that in general, storing passwords in a text file is a very bad idea. You can clearly see the reason why if you try to open the "dictAcc.txt" file (it will have all passwords there).
import pickle
import time
def loaddict():
try:
with open("dictAcc.txt", "rb") as pkf:
return pickle.load(pkf)
except IOError:
with open("dictAcc.txt", "w+") as pkf:
pickle.dump(dict(), pkf)
return dict()
def savedict(dictAcc):
with open("dictAcc.txt", "wb") as pkf:
pickle.dump(dictAcc, pkf)
def userPass():
dictAcc = loaddict() #Load the dict
checkAccount = raw_input("Do you have an account (Y or N)?")
if (checkAccount == 'N' or checkAccount == 'n'):
userName = raw_input("Please Set Your New Username: ")
password = raw_input("Please Set Your New Password: ")
if (userName in dictAcc):
print("Username is taken")
userPass()
else:
dictAcc[userName] = password
print("Congratulations! You have succesfully created an account!")
savedict(dictAcc) #Save the dict
time.sleep(1.5)
# dataInput() Code ends
elif(checkAccount == 'Y' or checkAccount == 'y'):
login()
else:
print("Invalid answer, try again")
userPass()
def login():
global userName
global password
global tries
loginUserName = raw_input("Type in your Username: ")
loginPass = raw_input("Type in your Password: ")
dictAcc = loaddict() #Load the dict
if (tries < 3):
for key in dictAcc:
if (loginUserName == key and loginPass == dictAcc[key]):
print("You have successfully logged in!")
# dataInput() Code ends
else:
print("Please try again")
tries += 1
login()
if (tries >= 3):
print("You have attempted to login too many times. Try again later.")
time.sleep(3)
tries=1 #To restart the tries counter
login()
global tries
tries=1
userPass()
There are different ways to do this. I'll mention two.
As you noticed, all variables created by your program are erased when the program finishes executing.
One way to keep those variables alive is to keep the program running indefinately; something like a background process. This could be achieved very simply by running the script within a while loop while True:, although there are more effective ways to do it too. Then, it's variables can continue to exist because the program never terminates.
However that is only useful in occasions when you want to have something running all the time, such as a user interface waiting for input. Most of the time, you want your script to run and be able to complete.
You can therefore output your needed data to a text file. Then, when you start your program, read that text file and organize the info into your dictionary. This will make use of open("Your_username_file") and reading that file's data. If you need help on how to do that, there are many tutorials about how to read information from files in Python.
How you will store it doesn't matter too much in your case, so it's better to keep things simple and store it in something like a text file. In anycase, you don't want to store the accounts in memory, because you will need to keep it running forever.
Since this is also running locally, no matter how you choose to store your passwords, it'll be accessible to anyone who uses it. So User_a can check User_b's account and password.
So you'll need to encrypt the password before storing them. It's not as hard as it sound. Actually, Python has built-in libraries to deal with it.
A quick google search returned a simple tutorial explaning all this step by step, check it out. You'll probably be able to implement it into your code very quickly.