How do I add user input to a list and able to see it? - python

I am trying to make a sign up system in python 3.7 but I don't know how to permanently add a users login to a list and not having to sign up for the same account every time you open the program.
I was not able to make up a solution to this problem.
Usernames = ['User1', 'User2']
Passwords = ['password123', 'password123']
print('Type SU to Sign Up or type LI to Log In!')
UOption = input('Option>> ')
if UOption == 'SU':
SI = True
LI = False
if SI == True:
print('Signing Up!')
SUUsername = input('Username>> ')
SUEmail = input('Email>> ')
SUPassword = input('Password>> ')
Usernames.append(SUUsername)
Emails.append(SUEmail)
Passwords.append(SUPassword)
LI = True
SI = False
I am expecting when I get this working that the user will be able to sign up once then be able to log in if they reopen the program without having to sign up again.

You could use the pickle module:
Firstly, to create the necessary files, run the following code in the folder that your program is saved in:
import pickle
pickle.dump([],open("usernames.dat","wb"))
pickle.dump([],open("emails.dat","wb"))
pickle.dump([],open("passwords.dat","wb"))
In your program, add:
import pickle
at the start of the program
Replace the lines:
Usernames = ['User1', 'User2']
Emails = ['Email1', 'Email2'] # I'm assuming this line has just been missed off your question
Passwords = ['password123', 'password123']
With:
Usernames = pickle.load(open("usernames.dat","rb"))
Emails = pickle.load(open("emails.dat","rb"))
Passwords = pickle.load(open("passwords.dat","rb"))
To read from the files
And finally add these lines at the end of your program to update the files with the new user's details
pickle.dump(Usernames,open("usernames.dat","wb"))
pickle.dump(Emails,open("emails.dat","wb"))
pickle.dump(Passwords,open("passwords.dat","wb"))
This is a link to more details on how to use pickles, if your interested
https://www.tutorialspoint.com/python-pickling
For source code including these edits see here:
https://pastebin.com/H4ryP6cT

Related

How to convert a file into a list and then that list into a dictionary and load it into the program everytime I run it

I made a User login system in which user must enter one of three alphabets that is x to stop the program, y if you are a new user and n if you are not a new user.
self.register = input('Enter y if you have register or n if you are new or x to quit:')
If user enter's 'n' then it will create a new user and store it into a dictionary:-
ex:- username = Fread
password = hello
{'Fread':'hello'}
From here if user enter's y then it will check if te user exist with this condition:-
self.existing_Id = input('Please enter your existing id here:')
self.existing_Password = input('Please enter your existing password here:')
if self.existing_Id in self.save and self.save[self.id] == self.password:
print('you have successfully logged in')
else:
print('user not found please try again')
Also if the user already exist then it will also not create a user:-
while True:
self.id = input('please enter your ID here:')
if self.id in self.save:
print('User already exist!!!')
break
Here i am trying to save all the username and password into file then everytime i stop and rerun te code again it should load all the previous saved file into a dictionary?
What you're trying to do is called serialization : Turning python objects into things you can write into files, and back into python objects.
Python has some built in capabilities in the form of pickles :
from pathlib import Path
import pickle
SAVE_FILE = Path('some/path/file.pickle')
def save_state(state_dict):
pickle.dump(state_dict, SAVE_FILE)
def restore_state():
return pickle.load(SAVE_FILE)
In this example, you can use the save_state function before exiting the program to write your data to some/path/file.saved, and load_state when you open to read data.
Note that pickling has some security issues if the saved state file will be handled by someone malicious. In those circumstances, you could do a similar job with the JSON module, albeit with a little less leway with the data structures you could store in the file.
import JSON
from pathlib import Path
SAVE_FILE = Path('some/path/file.json')
def save_state(state_dict):
JSON.dump(state_dict, SAVE_FILE)
def restore_state():
return JSON.load(SAVE_FILE)

Check variable against specific line in a text file | Python 3.6.x

Pretend I am making an email script. The user has already made a username and password, which has been stored in a text file so they can log in later at anytime.
The user needs to be able to log in. I want python to check that the users input matches the information in the text file from earlier, on their corresponding line. Capitalization doesn't matter.
The text file that was created initially reads:
johncitizen
johnspassword
My python script should read something like:
##Reads text file
guessusername = input('What is your username? ')
guesspassword = input('What is your password? ')
if guessusername.lower() = lines[0] and guesspassword = lines[1]:
##Grant access
I don't mind if capitalization is wrong, as long as the string itself matches up
Before first of all, what you are doing with plain text password storage is ill-advised. You should be using hashing+salting, or even better, pick a decent framework to work in and learn from how they do it.
First of all, your data storage format should be more record like:
user_id<tab>username<tab>password
user_id<tab>username<tab>password
user_id<tab>username<tab>password
In that case, you are able to read the file like this:
username = ... #user input
password = ... #user input
found_user_id = None
with open('pass.txt', 'rt') as f:
for line in f:
fields = line.split("\t")
if fields[1] == username and fields[2] == password:
found_user_id = fields[0]
break
#okay, here if found_user_id is not None, then you have found them
#if it is None, then you did not find them.
Truly, a database is much more useful than a text file, but this is how it works!

Why doesn't my code read this line?

so I made a program that reads usernames with passwords (which are salted and hashed) from an SFTP server, and the user can log in securely. Users can also make their own accounts, but I am having a problem with the checking if the username already exists. I have managed to write the code correctly, but for some strange reason I can't find out why my code won't read one for loop, at least it doesn't print the "debug" string, example below. Any help would be appreciated!
def createUser():
f = ftp.open("paroolid.txt", "a+")
passListDecode = f.read().decode("UTF-8")
passList = passListDecode.splitlines()
newName = input("Uus kasutajanimi: ")
if len(newName) <= 0:
print("Nimi peab olema vähemalt 1 täht!")
createUser()
#This is the loop that won't be read
for line in passList:
print("debug")
pp = ""
pp += line.split(",")[1].strip().split("-")[0].strip()
pp += newName
userInFile = hashlib.md5(pp.strip().encode()).hexdigest()
if userInFile == line.split(":")[0].strip():
print("Nimi juba olemas!")
createUser()
#But this line is read successfully, like the above for loop is just being skipped.
newPass = getpass.getpass("Uus parool: ")
Everyone, I got it fixed.
I learned that you cannot use the read() function when you're using the "a+" mode while opening a file, you'll need to use seek(0).
With that the problem is answered, thanks to Mike Scotty for suggesting that the list might be empty, I didn't think of that before.

Python- Reading back usernames and passwords into a program to authenticate

I am currently writing a program in Python that asks if you have a log in. If no, they proceed to create a username and password. If yes, they log in and their details are checked against a text file. The text file looks like this (Username then password):
whitehallj27
EXpass%20
Username2
EXPASSWORD%%%
james_27
password1234
I am trying to figure out a way of programming this as simply as possible. It seems to work, but isn't nearly as simple and doesn't really work how I thought it would. Here is the code snippet:
logins={}
usernames_passwords=open("UsernamesAndPasswords.txt","r")
count=0
for line in usernames_passwords:
count=count+1
count=count/2
usernames_passwords.close()
usernames_passwords=open("UsernamesAndPasswords.txt","r")
try:
for x in range(count):
username=usernames_passwords.readline()
password=usernames_passwords.readline()
logins[username]=password
except TypeError:
count=int(count+0.5)
for x in range(count):
username=usernames_passwords.readline()
password=usernames_passwords.readline()
logins[username]=password
usernames_passwords.close()
print(logins)
Also, how would I go about authenticating the username and password to check it's correct.
Many thanks,
James Duxbury
Assuming that variables user and passwd have the username and password provided by the user, then just read the file in two lines:
file_contents = []
with open("UsernamesAndPasswords.txt","r") as f: #use "with", it will auotamtically close the file
file_contents = f.readlines()
usernames = file_contents[0::2] #step by 2, take all elements starting at index 0
passwords = file_contents[1::2] #step by 2, take all elements starting at index 1
found_at_index = -1
for i in range(0,len(usernames)):
if user == usernames[i] and passwd == passwrods[i]:
found_at_index = i
break
if found_at_index >= 0 :
#do whatever you want, there is match
else:
#I don't know what you wanted to do in this case
Please read this for the with keyword and this for how to read a file nicelly.
Also this about the [::] syntax.
You could create a dictionary with the user names and passwords like this:
dict = {
'user-name': 'password-hashing',
'another-user': 'another-password'
}
after you've done it you can save this dict in a json file, and load its content when the user asks for login.
the docs for handling json files with python: https://docs.python.org/3/library/json.html
obs.: it will look simpler, but its not the best way of doing this king of thing

Username and Password login

I'd like to create a Login in which will open a text/csv file read the "Valid" usernames and passwords from the file and then if whatever the user has added has matched what was in the file then it will allow access to the rest of the program
How would i integrate the code below into one of which opens a file reads valid usernames and passwords and checks it against the users input
Currently i have something which works but there is only one password which i have set in the code.
Password = StringVar()
Username = StringVar()
def EnterPassword():
file = open('Logins.txt', 'w') #Text file i am using
with open('Logins.txt') as file:
data = file.read() #data=current text in text file
UsernameAttempt = Username.get()#how to get value from entry box
PasswordAttempt = Password.get()#how to get value from entry box
if PasswordAttempt == '' and UsernameAttempt == '':
self.delete()
Landlord = LandlordMenu()
else:
PasswordError = messagebox.showerror('Password/Username Entry','Incorrect Username or Password entered.\n Please try again.')
PasswordButton = Button(self.GenericGui,text = 'Landlord Section',height = 3, width = 15, command = EnterPassword, font = ('TkDefaultFont',14),relief=RAISED).place(x=60,y=175)
Some assistance would be appreciated
Please have a look at some documentation. Your question in "Coding Comments" -> #how to get value from entry box is easy to be solved using official documentation.
For reading files there is also official documentation on strings and file operations (reading file line by line into string, using string.split(';') to get arrays instead of row-strings).
Please do read documentation before writing applications. You do not need to know the complete API of all python modules but where to look. It is very exhausting to be dependent on other users / developers when there is no actual need for it (as there is very detailed documentation and tons of howtows for that kind of stuff).
This is not meant to be offensive but to show you how easy you can get documentation. Both results where first-results from a search engine. (ddg)
Please keep in mind that SO is neither a code writing service nor a let-me-google-that-for-you forum.

Categories