What am I missing in this python login function? - python

I am trying to write a login function using python. However, I can't seem to write the code for checking the username and password against the ones stored in a file. The specific error is NameError: name 'adusername' is not defined. How do I fix this?
def adminlogindetails():
adusername = input("Admin Username: ")
adpassword = input("Admin Password: ")
adfile = open("adlogindetails.txt", "a")
adfile.write(adusername)
adfile.write(",")
adfile.write(adpassword)
adfile.write("\n")
adfile.close()
def adminverification():
adun = input("Enter your username:")
adpw = input("Enter your password:")
adinfo = open("adlogindetails.txt", "r")
for line in adinfo:
adun, adpw = line.split(",")
if adun == adusername and adpw == adpassword:
print("Login successful!")
adminoptions()
else:
print("Incorrect username/password")
roleselection()
adminverification()

You have not declared adusername and adpassword in adminverification(). So, it is causing the error. If you want to use the variables from adminlogindetails(), change the variables name since you have stored the details in adlogindetails.txt.
The below code should be changed as line variable contains the already stored username and password:
adun, adpw = line.split(",")
Change above piece of code to the shown below:
adusername, adpassword = line.split(",")
you can use this:
def adminlogindetails():
adusername = input("Admin Username: ")
adpassword = input("Admin Password: ")
adfile = open("adlogindetails.txt", "a")
adfile.writelines(adusername + ',' + adpassword )
adfile.close()
def adminverification():
adun = input("Enter your username:").strip()
adpw = input("Enter your password:").strip()
with open("adlogindetails.txt", "r") as f:
lines = f.readlines()
i = 0
for line in lines:
adusername, adpassword= line.split(",")
adusername = str(adusername).strip()
adpassword = str(adpassword).strip()
if (adun == adusername) and (adpw == adpassword):
print("Login successful!()")
adminoptions()
break
else:
i += 1
if i >= len(lines): #If no any match upto last line, this will be true
print("Incorrect username/password")
roleselection()
break
adminverification()

First of all you are not calling adminlogindetails().
Also adusername is a local variable and you should either make it global using global adusername in the adminlogindetails function or declare it outside of the functions in the global scope.
See this - https://www.w3schools.com/python/python_scope.asp

This line is your problem:
adun, adpw = line.split(",")
"adun" and "adpw" are your inputs and you are overwriting them. Replace with this and it will be ok:
adusername, adpassword = line.replace("\n", "").split(",")
Note: "\n" needs to be removed for your comparison to be ok.

Related

Python program to register accounts an log in

So I'm making a program where I need a user to log in or register. The registered account goes to a .txt file from which I'm supposed to read the data to log in again.
I managed to get the basics working. I can register a new account to the file and I can log in with every account I've created, but I can't seem to get 2 important elements working. The first one is for when the user inserts an inexistent username/ password (in this case the program just does nothing as I can't figure out a condition to make it go back to asking the username and password), and the second one is for when I insert a username and password that don't match. Here the program goes back and asks for them again but then keeps asking, even if I put them correctly.
Here's my function if anyone's interested in having a look at it:
def ent():
util = False
ppass = False
login = False
while not login:
n_util = input("Introduce your username: ")
password = input("Introduce your password: ")
with open("dadoscontas.txt", "r") as f:
while not util:
vski = 0
for line in f:
vski += 1
if vski == 1:
if line.strip() == n_util:
util = True
else:
break
if vski == 2:
if line.strip() == password and user:
ppass = True
if user and ppass:
login = True
print("Logged in")
I've spent my whole afternoon trying different things to see if I can get these 2 things to work, but I can't. As I said, the function above is the part that kinda works, and if anyone could give any suggestions / point me in the right direction it would be really helpful. Thank you in advance.
Does this code cover your needs?
def ent():
util = False
login = False
while not login:
n_util = input("Introduce your username: ")
password = input("Introduce your password: ")
with open("some_test.txt", "r") as f:
vski = 0
for line in f:
vski += 1
if vski%2:
if line.strip() == n_util:
util = True
elif util:
if line.strip() == password:
login = True
else:
util = False
print("Logged in")
Or you even could exit the function with return in if line.strip() == password: block.
But i would recommend you to store the file content to dictionaries (user_name:passwor),
because you are parsing the whole file again and again while login=False:
def ent():
login = False
name=""
my_data = {}
with open("some_test.txt", "r") as f:
index = 0
for line in f:
index += 1
if index%2:
name = line.strip()
else:
my_data[name] = line.strip()
while not login:
n_util = input("Introduce your username: ")
password = input("Introduce your password: ")
if n_util in my_data and my_data[n_util] == password:
login = True
print("Logged in")
If you use python2 you can use .get() or try instead of n_util in my_data for better performance.

Python - how to read through text file for keyword

**This is a practice application
I have a text file containing a id & a password. Each pair is on separate lines like so:
P1 dogs
P2 tree
I then have 2 functions to allow the user the add another id/password or update the password by selecting an ID then the new password. (I have removed the save functionality so I don't create loads of pairs when testing)
The question is how would I write a check function so that when the user is creating a new pair.. it checks if the id/password already exists. Then on the update password function, it only checks if the password exists?
My code so far:
#Keyword check
def used_before_check(keyword, fname):
for line in open(fname, 'r'):
login_info = line.split()
username_found = False
for line in login_info:
if keyword in line:
username_found == True
if username_found == True:
return True
else:
return False
# New password function
def new_password():
print("\nCreate a new password")
new_id_input = input("Please give your new password an ID: ")
new_password_input = input("Please enter your new password: ")
print("ID in use?", used_before_check(new_id_input, txt_file))
print("Password in use?", used_before_check(new_password_input, txt_file))
#Change password function
def change_password():
print("\nChange password")
id_input = input("Enter the ID of the password you'd like to change: ")
password_input = input("Now enter the new password: ")
print("password_input",used_before_check(password_input, txt_file))
The easiest way would be to use JSON:
import json
import os
def new_password(user, password, password_dict={}):
if user in password_dict:
password_dict[user] = password # change password
else:
password_dict[user] = password # new password
return password_dict
def read_passwords(filename):
if not os._exists(filename):
return {}
with open(filename, 'r') as f:
s = f.read()
return json.loads(s)
password_filename = 'my_passwords.json'
password_dict = read_passwords(password_filename)
user = ''
while not user == 'q':
user = input('user:')
password = input('new password:')
if user != 'q':
password_dict = new_password(user, password, password_dict)
s = json.dumps(password_dict)
with open(password_filename, 'w') as f:
f.write(s)
Not that I have included a seemingly unnecessary if clause in new_password. This is just for you that you can easily enter your own code what you want to do (maybe different) in each case.
Create a function to store your usernames/passwords in a dictionary, then you can easily check it for existing usernames/passwords
To store in dictionary:
def process_file(fname):
username_pw_dict = {}
for line in open(fname, 'r'):
login_info = line.rstrip().split()
username = login_info[0]
pw = login_info[1]
username_pw_dict[username] = pw
return username_pw_dict
username_pw_dict = process_file(fname)
Then you can check for existing usernames or passwords like this:
if new_username in username_pw_dict:
print("username already exists")
if new_pw in username_pw_dict.values():
print("password already exists")
When you are reading the file, make a dictionary with all the IDs as its keys.
In next step, reverse the dictionary key-value pair so all its values (i.e all passwords) become its keys.
Finally, when you enter a new ID and password, just check those dictionaries to know if they already exist. You may refer to this below code:
dict_ids = {1 : "one", 2:"two", 3:"three"};
dict_pwds = {}
for key, value in dict_ids.items():
for string in value:
dict_pwds[value] = key;
print "dict_ids ", dict_ids;
print "dict_pwds ", dict_pwds;
if 'myid' in dict_ids.keys():
print "ID exist! "
else:
print "New ID"
if 'mypwd' in dict_pwds.keys():
print "Password exist! "
else:
print "New Password"

csv - Creating a login system, python not properly reading from .csv file?

I am trying to make a login system that is looped basically and whenever I try to enter the correct details that are even stored in the .csv file, it outputs as incorrect username/password no matter what I put. This code works for python 3.6 but I need it to work for python 3.2.3.
loop1 = False #for this bit of code (logging in)
loop2 = False #for next bit of code
while loop1 == False:
choice = input("Login/SignUp [TYPE 'L' OR 'S']: ").lower()
if choice == "l":
username = input("Username: ")
password = input("Password: ")
f = open("usernamepassword.csv","r")
for line in f:
details = line.split(",")
if username == details[0] and password == details[1]:
print("Welcome")
break
#this whole bit of code is meant to read from the csv and check if the login details are correct
else:
print("Username/Password [INCORRECT]")
Allow me to refactor your code:
def login(username, password):
with open("usernamepassword.csv", "r") as csv:
all_details =
[[attr.strip() for attr in line.split(",")]
for line in csv]
return any(
username == details[0]
and password == details[1]
for details in all_details)
def login_action():
username = input("Username: ")
password = input("Password: ")
if not login(username, password):
raise ValueError("Username/Password [INCORRECT]")
return True
_USER_ACTIONS = {
'l': login_action
}
def main():
while True:
choice = input("Login/SignUp [TYPE 'L' or 'S']: ").lower()
action = _USER_ACTIONS[choice]
try:
if action():
break
except Exception as err:
print(err.message)
I think your unexpected behavior comes from not stripping the values you get after splitting by ,
Solved by replacing:
if username == details[0] and password == details[1]:
With:
if username == details[0] and (password+"\n") == details[1]:
You may have a bug in line.split(','), try line.strip().split(',')
TL; DR: posted a proper solution there : https://github.com/cgte/stackoverflow-issues/tree/master/47207293-csv-dict
I'll stuff up my answer later if needed.
Furthermore you have a poor code design here, and find yourself debugging in the middle of a loop.
So first of all : load the data file, store content to a dict.
f = open("usernamepassword.csv","r")
for line in f:
details = line.split(",")
if username == details[0] and password == details[1]:
print("Welcome")
break
Should become
user_pass = {}
f = open("usernamepassword.csv","r")
for line in f:
user, password = line.strip().split(",")
user_pass[user] = password
f.close()
or better
with open("usernamepassword.csv","r") as f:
for line in f.readlines():
user, password = line.split().split(",")
user_pass[user] = password
eventually run python -i yourfile.py and type "user_pass" to see what is actually stored when correct go on further code.
Think of using the csv module : https://docs.python.org/3/library/csv.html
Then get username and password from input and check:
if login in user_pass and user_pass[login] = password:
# or better `if user_pass.get(login, None) == password:`
do_stuff()

Why is this `if` block not executed

The below piece of code intends to ask for a desired username and then to create it.
I want to tell the user when the username has already been taken. That works.
However, whenever a username is input that does not yet exist, I want all of the if a != 1: block to be executed, but that does not happen. Why is that?
Here is a snippet of the code that I've narrowed down to where the problem occurs:
UsernameRequest = input("What would you like your username to be set? ")
fname = UsernameRequest + ".txt"
try:
f2 = open(fname, 'r')
a = f2.readline(1)
if a == "a":
print ("This username is already taken!")
f2.close()
a = 1
except:
b = 1
if a != 1:
f = open(fname, 'w')
PasswordRequest = input("What would you like your password to be? ")
f.write("abcde" + '\n')
f.write(UsernameRequest)
f.write('\n' + PasswordRequest)
f.close()
print ("User created! Welcome to SterlOS!")
Login()
break
I think the scope of the variable a is the problem here. Try declaring a outside of the try block.

Finding Hash's in text files

I'm am trying to verify users using a text document but not having much success. Can someone please point me in the right direction? Here is my code. What I want to do is have have python look on the line which contains the hash and then verify the hash. It is able to verify the first hash but nothing after that. Does anyone know how to fix this?
def passwordVerify():
global hashOne
f = open("maindata.txt")
s = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
numberOne = userConfirm + 2
numberTwo = userConfirm + 1
for line in islice(f, numberTwo, numberOne):
hashOne = line
hashStripped = str.rstrip(hashOne)
hashchecker = sha256_crypt.verify(passWord, hashStripped)
f.close()
if hashchecker is True:
loggedIn()
else:
print "Please try again!"
time.sleep(2.5)
userLogin()
def userRegister():
screenClear()
print "!King of Hearts Registration System!"
realName = raw_input("What is your real name: ")
userName = raw_input("Choose a Username: ")
passWord = getpass.getpass("Please enter a password: ")
passHash = sha256_crypt.encrypt(passWord)
writeUser = "\n" + userName + "\n"
writePass = passHash
userDB = open("maindata.txt", "a")
userDB.write(str(writeUser))
userDB.write(str(writePass))
userDB.close()
print passHash
userLogin()

Categories