Comparing password cell to username cell in excel using python - python

I am new to python and i'm trying to build my first accounts projects, which i allow users to input name, username, password and other details.
to sign in i would ask user for username and password, i do know how to search in a specific column to check if the username exist, but what im struggling to find is how to check if the password in the same row of the username is correct, i dont want it to search in all passwords column, only the password of the username that has been entered.
i am using open openpyxl for this.
heres my code
def username_check(filename , minrow, maxrow, mincol, maxcol, name):
wd = load_workbook(filename)
ws = wd.active
for row in ws.iter_cols(min_row=minrow,max_row=maxrow,min_col=mincol, max_col=maxcol, values_only=True):
if name in row:
return True
else:
return False
this is the checking function ive made.
while True:
if x == 1:
username = input("enter your account username: ")
password = int(input("enter password: "))
usernamecheck = username_check("accounts.xlsx", 2 , len(ws["C"]), 3, 3, username)
passwordcheck = username_check("accounts.xlsx", 2, len(ws["D"]), 4, 4, password) # This is wrong
if usernamecheck and password == True:
print("ok")
break
this is the code and what im trying to do
enter image description here
this is the table

Its not good practice to 'do' things that take a lot of processing more than once if its not necessary. Making two calls to the function username_check which opens the excel file should be avoided since you can check both the username and password at the same time.
Also be careful of indentation in python code.
You can make the code much simpler and easier to read by using zip to iterate both columns at the same time.
from openpyxl import load_workbook
def username_check(filename, username, password):
wb = load_workbook(filename)
ws = wb.active
for user_col, pass_col in zip(ws['C'], ws['D']):
if user_col.row == 1: # This skips the Header row
continue
if user_col.value == username and pass_col.value == password:
return True
return False
filename = 'accounts.xlsx'
while True:
username = input("enter your account username: ")
password = int(input("enter password: "))
usernamecheck = username_check(filename, username, password)
if usernamecheck:
print("ok")
break

Related

How can I check with python if a hash is stored in a txt file

I was trying to write a simple log-in-programm, that stores the usernames and password as hashes in a .txt file (I know that that's not safe but I'm just trying to learn).
I also tried to implement a system that checks, if a username is already taken. And that's where my problem is. ("#check if it's already taken" in the code)
When the username is already taken, it tells me to choose a new one. But when I'm inputting the same name again, after it told me to take a new one, it just continious with the code, even though the name exists already in the file.
So is there a method to get a loop that checks over and over again, if the username, I'm trying to input, is already in the file?
import hashlib, time, os
def register():
#create new username
user = input('Create your username: ')
hashuser = hashlib.sha256(user.encode())
hexhashuser = hashuser.hexdigest()
#check if its already taken
with open('py\Hashed Login\Sign in data.txt') as temporary:
while hexhashuser in temporary.read():
user = input('Sorry, that username is already taken. Please chose a new one: ')
hashuser = hashlib.sha256(user.encode())
hexhashuser = hashuser.hexdigest()
data = open('py\Hashed Login\Sign in data.txt', 'a' )
data.write(hexhashuser)
if hexhashuser not in temporary.read():
data = open('py\Hashed Login\Sign in data.txt', 'a' )
data.write(hexhashuser)
#write to file
data.write('+')
time.sleep(1.5)
#create new password
password = input('Please choose your new password: ')
check = input('Please enter your password again: ')
while check != password:
check = input('Wrong password. Please enter it again: ')
hashpassword = hashlib.sha256(password.encode())
hexhashpassword = hashpassword.hexdigest()
data.write(hexhashpassword)
data.write('''
''')
data.close
def login():
print('placeholder')
register()

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()

While Loop CSV File Login - Loops 3 times, unsure why

import csv
def login():
global student
student = []
file = open("student.csv","r")
data = csv.reader(file)
UsernameVerified = False
PasswordVerified = False
while UsernameVerified == False:
username = input("Username: ")
for row in data:
user = []
student.append(row)
print(UsernameVerified)
for multi in row[5:6]:
if username in multi:
print("found")
UsernameVerified = True
print(UsernameVerified)
This is the current code I am using. However when I run this code and put in the correct user name, it finds the user 3 times which it shouldn't be doing.
Also when I put in the wrong user then the right user, it cannot find the user at all.
I am doing this for a school project and have had 2 teachers look into this, so far no progress was made.
Output when I input the correct User first
Output when I input the wrong User first, then the Correct one
New code
——————
import csv
def login():
global student
student = []
UsernameVerified = False
PasswordVerified = False
while UsernameVerified == False:
file = open("student.csv","r")
data = csv.reader(file)
username = input("Username: ")
for row in data:
user = []
student.append(row)
print(UsernameVerified)
for user in row[5:6]:
if username in user:
print("found")
UsernameVerified = True
print(UsernameVerified)
while PasswordVerified == False:
file = open("student.csv","r")
data = csv.reader(file)
password = input("Password: ")
for row in data:
user = []
student.append(row)
print(PasswordVerified)
for pass1 in row[4:5]:
if password in pass1:
print("found")
PasswordVerified = True
print(PasswordVerified)
For the first question: it returns 3 times because the while loop only stops and the end of for loop. if you want a quick fix use "break" inside for loop when you log in the user
For the second question that happens because "data" variable is pointed to the end of file. Basically you open the file, read it until the end when you enter the wrong user, and it stays there. try opening the file only after the "input" using a "with" statement

Can't verify password using passlib

So I'm back working on old project and I cant find whats wrong.
This is the part where the password is first time created, this is from the main script:
def first():
if os.path.isfile("secret.txt"):
folder()
else:
os.system("echo > secret.txt")
password = getpass.getpass("Set your password please --> ")
while len(password) < 4:
print("Password must have more then 4 characters!")
else:
password1 = getpass.getpass("repeat your password please --> ")
while password1 != password:
print("Password don't match")
password1 = getpass.getpass("repeat your password please --> ")
if password1 == password:
a = open('secret.txt', 'w').close()
f = open('secret.txt', 'w')
hashed_password = pbkdf2_sha256.hash(password)
f.write(hashed_password)
os.system("attrib +h secret.txt")
folder()
This is the login script and from here is password checked:
def log_in():
f = open("secret.txt", "r")
Password = f.read()
x = 0
while x < 5:
getPass = getpass.getpass("Password:")
if not pbkdf2_sha256.verify("getPass", Password):
print("Password is invalid")
x = x + 1
else:
f.close()
os.system('cls')
print("Welcome back sir\n")
x = 10
time.sleep(2)
if x == 5:
print("acces denied")
time.sleep(5)
os.system("nothing.bat")
So the problem is when I try to verify the password it says its not correct but the password is the same. In doc it says:
Note that since each call generates a new salt, the contents of the resulting hash will differ between calls (despite using the same password as input):
If this is the problem at .verify() then what should I do?
I'm not sure if this is enough info, if not I will post whole source code
I am probably missing some stupid thing but I just cant seem to find it..
I think the problem is:
if not pbkdf2_sha256.verify("getPass", Password):
Change it to:
if not pbkdf2_sha256.verify(getPass, Password):
You have called a str "getPass" not the password that user input.

Categories