Python - Multiple Login Combinations - python

Basically, I've made a basic login program that accepts user input. But, it currently only allows one username and password combo. I'm trying to make it accept multiple usernames and passwords but don't know how to. I am new to python and I know my code is terrible/messy. This is what I've been trying to get it to accept multiple login combinations:
output = open("logfile.txt", 'a')
login = input("please enter the correct username and password\n")
a = ("username password")("username1 password1")
if a in login:
print("successfully logged in")
import time
localtime = time.asctime(time.localtime(time.time()))
output.write("Somebody successfully logged in at ")
output.write(localtime)
output.write("\n")
output.close()
else:
print("access denied.")
import time
output = open("logfile.txt", "a")
localtime = time.asctime(time.localtime(time.time()))
output.write("Somebody unsuccessfully logged at ")
output.write(localtime)
output.write("\n")
output.close()
`
When I just add another 'if' block, it runs the else block aswell. Also, when I just have 'a' value "username password" it works. The problem is when I try to have multiple values I believe.

Try
a = set(("username password","username1 password1"))
if login in a:
and it should work as you expect.
Why is left as an exercise (hint: print the value of a).

You don't want a = ("username password")("username1 password1") and if a in login:.
You want to set a to an iterable of some sort, the code you currently have actually produces a TypeError because you are trying to call a string (putting something in brackets doesn't make it a tuple, you need to add a trailing comma).
What you want instead is something like a = ["username password", "username1 password1"], doe create a list with all the valid usernames and passwords. You then want to check if the input - login - is in that list, so do if login in a: instead.

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 compare two variables which both contain strings in python?

I'm making a account login system in python by having the username and password stored in a separate file and the program access it, then read the password and compare it with what the user has entered. It can read the password in the file but for some reason when it compares it to what the user has entered, it always says it's wrong.
I've tried comparing the actual password to the user's input and I know it's reading the file right as I made it print out what it read and it printed the correct password. I've also made it print the user's input to make sure that's right and that was working too.
Just so you know, the file already exists which contains the password on the second line and it finds the right file as the file is named after the account that it's for.
Account = str(input("Enter the username. "))
Account_Password = str(input("Enter the password. "))
AccountFileName = (Account + ".txt")
with open(AccountFileName,"r") as AF:
for x, line in enumerate(AF):
if x == 1:
Account_Password_Check = (line)
if Account_Password == Account_Password_Check:
print("Welcome, " + Account + "!")
else:
print("Either the username or password were incorrect.")
If the user input is the same as the password, it should print, "Welcome (username here)!" and if they're different then it should print, "Either the username or password were incorrect."
If you know what's wrong, please let me know.
Thanks.
In comments to your question, you will find the first reason why it doesn't work, but:
for x, line in enumerate(AF):
if x == 1:
Account_Password_Check = (line)
Is also not fully correct, enumerate start count from zero, but condition checks 1 line, it means that you will compare your current user password from previous. The correct version will be
for x, line in enumerate(AF):
if x == 0:
Account_Password_Check = line.strip()
break

Program not working correctly (using Python) - Login Program

This is my code:
users = []
users.append([username, password])
usersFile = open("users.txt","w+")
for users in users:
usersFile.write("%s" % users)
usersFile.close()
def loginFunction():
userEntry = ""
foundName = 0
while userEntry == "":
userEntry = raw_input("Enter your username: ")
usersFile = open("users.txt", "r")
lines = usersFile.readlines()
usersLen = len(users)
for index in range (0, usersLen-1):
if userEntry == users[index, 0]:
foundName = 1
passwordEntry = raw_input("Enter your password: ")
if passwordEntry == users[index, 1]:
print "Username and passwords are correct"
else:
print "incorrect"
userEntry = ""
if foundName == 0:
print "Username not recognised"
userEntry = ""
I have produced a program that registers the username and password of a user. I have checked the files and it saves the username and password successfully but when I try to login using the correct username that I know is in the file as a list, it still always comes up "Username not recognised". Any ideas as to why this might be?
It looks like you're writing out the user/passwords, as lists, as single lines in the file. Then when you read it back, each pair is read back as one string. readlines() doesn't automatically convert text back to a list object. If you want to do that, you might use Pickle instead. Pickle should let you save the entire users list of lists object all at once.
Also to be pythonic your for loop should iterate over the list directly. If you need the current index, use for i, user in enumerate(users). Using range(len(users)) is suboptimal in python. You can then use user[0] to get the username and user[1] for the password.
I've made a few changes to your program. Firstly, I've changed it to use the modern print function instead of the print statement. The print function is available in Python 2.6 and later. It's more powerful than the old print statement, and IMHO it's a good idea to start using it in preparation for Python 3 (which doesn't have the print statement).
To simplify reading & writing the username & password data we can use the standard csv module. It's not strictly necessary for this simple task, but it means we don't have to worry about the messy details of parsing the name and password strings. Eg, if the strings contain spaces or quotes, the csv will handle them correctly. Note that in Python 2 CSV files must be opened in binary mode, but in Python 3 they must be opened in text mode. This is rather annoying when you're trying to write code that runs correctly on both versions.
The easy way to look up a password given the username is to use a dictionary with the username as the key and the password as the value. This is much more efficient than scanning through a list row by row looking for a match.
Of course, in a real program we would never store passwords as plain text. That's extremely insecure! The usual procedure is to store a hashed version of the password, using a strong cryptographic hash function applied a very large number of times to make it a time-consuming operation. For further info please see PBKDF2, scrypt, and bcrypt.
Also, it's bad practice to let a potential attacker know that a username is valid but that the password they submitted is invalid. That allows them to easily build a list of valid usernames. Instead, you should always ask for the password, even if the username is invalid.
from __future__ import print_function
import csv
users = [
['Alice', 'aardvark'],
['Bob', 'bobcat'],
['Steve', 'swordfish'],
]
# Save the users list to a CSV file
users_filename = "users.txt"
with open(users_filename, "wb") as f:
writer = csv.writer(f)
writer.writerows(users)
def login_function():
# Load the usernames & passwords into a dictionary
with open(users_filename, "rb") as f:
users = dict(csv.reader(f))
# Give the user 3 chances to login
for i in range(2, -1, -1):
user_entry = raw_input("Enter your username: ")
password_entry = raw_input("Enter your password: ")
if user_entry in users and password_entry == users[user_entry]:
print("Username and password are correct")
return True
else:
print("Username and password are invalid")
print(i, "login attempts remaining")
print("Login failed")
return False
print(login_function())
demo
Enter your username: Alan
Enter your password: runner
Username and password are invalid
2 login attempts remaining
Enter your username: Alice
Enter your password: aardvark
Username and password are correct
True

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

fault in readline() or condition

I am getting a problem in my code. I created a program which creates an account, saves username and password in a .txt file. Then asks for login and it checks whether the username and password is corrent or not. But everytime the else condition is executing. And i am getting output "You don' have any account". Please help. Thanks in advance.
# MyProgram: Account Verification
print "\ncreate account:\n"
f = open("data.txt",'w+')
def create():
user_name = raw_input("Enter username >> ")
password = raw_input("Enter password >> ")
confirm = raw_input("Enter password to confirm >> ")
if password == confirm:
f.write(user_name+"\n"+password)
f.close()
print "Account created"
else:
print "\nPassword not matched\n\n Enter details again:\n"
create()
create()
new = open("data.txt")
un = new.readline()
pw = new.readline()
new.close()
def login():
print "\nLogin:\n"
name = raw_input("Enter username >> ")
if name == un:
pas = raw_input("Enter password >> ")
if pas == pw:
print "Welcome!"
else:
print "Wrong password"
login()
else:
print "You don't have any account"
login()
readline includes the newline character at the end of the line, so you're probably comparing e.g. "hunter2\n" to "hunter2". Try stripping the whitespace off first.
un = new.readline().strip()
pw = new.readline().strip()
Alternatively, it may be preferable to store/retrieve your usernames and passwords in some way other than writing strings to and reading strings from a plain text file. For very lightweight applications, simple serialization like the pickle or json libraries might suffice; but anything really serious would benefit from a proper database. With any of these, you probably won't need to worry about the behavior of readline() at all.

Categories