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

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!

Related

Creating A Simple Login System as a personal project and having some issues with IO in python

My question is that I am creating a login system in python. This system is very simple. The user type login , his email and password. The program checks from a file whether the email or password is correct or not. But I am running into some issues with that. So I first opened the file then asked the user if he wants to log in or signup. If he types login the program asks for email and password and check in the file whether this matches or not. The program takes input correctly but at the time of checking it fails. It does not give an error but it does not print the desired statement. This my code
with open('Data_Login_System.txt' , 'r') as data:
user_input = input("""Type Either Login or SignUp> """)
if user_input.lower() == "login":
Email = input("""Type your Email> """)
Password = input("""Type Your Password> """)
for line in data:
if line.lower() == f"email : {Email.lower()}" or line.lower() == f"password : {Password.lower()}":
print("Logged in")
These are the contents of the file.
Email : shabeebasghar123#gmail.com
Password : shabeebasghar123
Whenever I enter the correct email and password it should print logged in but it does not the program just run finely and nothing at the end
This is the execution of the program
Type Either Login or SignUp
> login
Type your Email
> shabeebasghar123#gmail.com
Type Your Password
> shabeebasghar123
It worked by just doing line.lower().strip() intead of just line.lower()
First of all you got to use a readlines() function to read lines from the .txt file with a loop. You could actually read a lines without a loop on that one. See code below.
lines = data.readlines()
print(data)
The out put for that would be:
['Email : mail#gmail.com\n', 'Password : passwd123'].
So I would try a bit different approach. Make sure that you don't have any unwanted extra lines in txt file.
user_input = input("Type Either Login or SignUp")
if user_input.lower() == "login":
email = input("""Type your Email""")
password = input("""Type Your Password""")
with open("data.txt", 'r') as f:
t_mail = f.readline()
t_passwd = f.readline()
if f"Email : {email}\n" == t_mail and f"Password : {password}" == t_passwd:
print('You are now logged in')
This works fine for me.

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

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

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.

How to access the value of username from htpasswd file using python script

I have created a username/ password in htpasswd file. In my python script file I would like to access the username value for further processing. How do I achieve that? I am using Linux OS.
The htpasswd format is `:", something that isn't terribly difficult to parse. Simply go through line by line and split on a colon, taking the first value:
usernames = []
with open("passwdfile") as htpwd:
for line in htpwd.readlines():
username, pwd = line.split(":")
usernames.append(username)
Or more consisely:
with open("passwdfile") as htpwd:
usernames = [line.split(":")[0] for line in htpwd.readlines()]

Categories