How can I save the items in lists because when using Sign_in function, it prints "invalid" not "success"?
import lists_module
def Sign_in():
email = input("Enter Your Email").strip()
password = input("Enter your password").strip()
if email in lists_module.emails and int(password) in lists_module.passwords:
print("success")
else : print("invalid")
def Sign_up():
first_name = input("Enter Your First Name").strip().capitalize()
last_name = input("Enter Your Last Name").strip().capitalize()
new_email = input("Enter Your Email").strip().capitalize()
new_password = input("Enetr New Password").strip().capitalize()
lists_module.Fname.append(first_name)
lists_module.Lname.append(last_name)
lists_module.emails.append(new_email)
lists_module.passwords.append(new_password)
print("Sign-In Page")
Sign_in()
Note: Fname and Lname and email are empty lists in another module.
The appended values are just temporary. Use file I/O for permanent changes. I.e.:
def Sign_in():
email = input("Enter Your Email").strip()
password = input("Enter your password").strip()
emails = open('emails.txt','r').readlines()
passwords = open('passwords.txt','r').readlines()
if email in emails and password in passwords:
print("success")
else : print("invalid")
def Sign_up():
first_name = input("Enter Your First Name").strip().capitalize()
last_name = input("Enter Your Last Name").strip().capitalize()
new_email = input("Enter Your Email").strip()
new_password = input("Enetr New Password").strip()
open('fnames.txt','a+').write(first_name+'\n')
open('lnames.txt','a+').write(first_name+'\n')
open('emails.txt','a+').write(new_email+'\n')
open('passwords.txt','a+').write(new_password+'\n')
print("Sign-In Page")
Sign_in()
This will write the values to files on your computer, then read them from those files, that way, when you run the prorgam a second time, the changes are permanent.
The reason you keep getting "invalid" is because you don't process the user's input consistently in the Sign_up() and Sign_in() functions. One way to update the lists in the lists_module is by using the atexit module to register a function that will be executed when the script ends.
import atexit
import lists_module
def Sign_in():
email = input("Enter Your Email ").strip().capitalize()
password = input("Enter your password ").strip().capitalize()
if email in lists_module.emails and password in lists_module.passwords:
print("success")
else:
print("invalid")
def Sign_up():
first_name = input("Enter Your First Name ").strip().capitalize()
last_name = input("Enter Your Last Name ").strip().capitalize()
new_email = input("Enter Your Email ").strip().capitalize()
new_password = input("Enetr New Password ").strip().capitalize()
lists_module.Fname.append(first_name)
lists_module.Lname.append(last_name)
lists_module.emails.append(new_email)
lists_module.passwords.append(new_password)
print("Sign-In Page")
Sign_in()
def update_lists_module():
with open('lists_module.py', 'w') as outp:
for name in dir(lists_module):
if not name.startswith('_'):
value = getattr(lists_module, name)
outp.write(f'{name} = {value!r}\n')
atexit.register(update_lists_module)
Sign_up()
Related
I am geting an error when trying to check a password using the bcrypt library. The issue seems to be that the hashed variable should be a plain string without "quotation marks". I've attempted to remove the quotation marks multiple times but the error persists. I am seeking assistance in removing the quotation marks from the "hashed" variable in order to make the bcrypt checkpw function work properly.
#----------------------------------------------------------------
#----------------------------------------------------------------
# import module to dencrypt password
#----------------------------------------------------------------
#----------------------------------------------------------------
import bcrypt
def Log_in():
# Print separator line
print("-"*70)
# Prompt user for email or username and password
msg0 = "Enter your username or your email address"
msg1 = "Enter your password"
user_input = input(f"{msg0:45}| ")
user_pasword = input(f"{msg1:45}| ")
print("-"*70)
# Open and read the text file where the user database is stored
db = open("database.txt",'r')
contant = db.readlines()
email_list = []
username_list = []
password_list=[]
# Check if there's content in the database
if contant == None:
pass
else:
# Split each line of the content by '| ' and append the parts to their corresponding lists
for i in contant:
a, b, c, d = i.split("| ")
email_list.append(a.strip())
username_list.append(b.strip())
password_list.append(d.strip())
# Close the file
db.close()
# Check if the entered email or username exists in the email_list or username_list
if user_input in username_list or user_input in email_list:
x = None
y = None
# Try to get the index of the entered email or username in the email_list and username_list
try:
x = username_list.index(user_input)
except:
pass
try:
y = email_list.index(user_input)
except:
pass
if x != None and y == None:
# If the entered username exists in the username_list
# Strip the 'b' character, encode the string to utf-8 and compare it with the entered password
hashed = password_list[x].strip('b')
# hashed = hashed.replace("'","")
hashed = hashed.encode('utf-8')
if bcrypt.checkpw(user_pasword.encode('utf-8'), hashed):
print("Welcome")
else:
print("incorrect password")
Log_in()
elif y != None or x == None:
# If the entered email exists in the email_list
# Remove the double quotes and compare it with the entered password
hashed = password_list[y][:-1]
hashed = hashed.replace('"','')
# hashed1 = hashed.replace(b"\n", b"")
if bcrypt.checkpw((user_pasword.encode("utf-8")),hashed): #error happening here
print("Welcome")
else:
print("incorrect password")
Log_in()
else:
print("incorrect password")
Log_in()
else:
# If the entered email or username doesn't exist in the email_list or username_list
print("This username or the email does not exist")
Log_in()
# main function
if __name__ == "__main__":
Log_in()
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
I am a function (logger) that expects two arguments from another python file. one of the arguments is a user input: firstname, lastname, email and phone number. the logger function should write the user input into txt file with comma operator between all elements. Then the next time the user executes the code, it should append the new data to a newline, but does not do that. It continues with the same line. Can someone please take a look of what I am getting wrong. code is attached below:
import re
def firstnamechecker(firstname):
firstEx = re.compile('[a-zA-Z]+$')
if firstEx.match(firstname):
return True
else:
return False
def lastnamechecker(lastname):
lastnameEx = re.compile('[a-zA-Z]+$')
if lastnameEx.match(lastname):
return True
else:
return False
def emailchecker(email):
emailEx = re.compile('[a-zA-Z0-9]+#[a-zA-Z]+\.[a-zA-Z]+$')
if emailEx.match(email):
return True
else:
return False
def phonenumberchecker(phonenumber):
numEx = re.compile('\d{3}-\d{3}-\d{4}$')
if numEx.match(phonenumber):
return True
else:
return False
def logger(logfile, data):
filewrite = open(logfile, "a")
data = data.splitlines()
data[:-1:] = [x+',' for x in data[:-1:]]
for item in data:
filewrite.write(item)
filewrite.close()
The code where the above code gets the information from is posted below:
import re
from checker import firstnamechecker, lastnamechecker, emailchecker,phonenumberchecker,logger
#lettersreg = re.compile('[a-zA-Z]+$')
#phonereg = re.compile('\d{3}-\d{3}-\d{4}$')
#emailreg = re.compile('[a-zA-Z0-9]+#[a-zA-Z]+\.[a-zA-Z]+$')
ADDBOOKPATH = "addbookFinal.txt"
ADDBOOKDATA = "addbook.txt"
LOGGING = True
def firstname():
firstname = input("put in your first name: ")
if LOGGING:
logger(ADDBOOKDATA, firstname)
while not firstnamechecker(firstname):
firstname = input("put in your first name: ")
if LOGGING:
logger(ADDBOOKDATA, firstname)
return firstname
#lastname
def lastname():
lastname = input("put in your last name: ")
if LOGGING:
logger(ADDBOOKDATA, lastname)
while not lastnamechecker(lastname):
lastname = input("put in your last name: ")
if LOGGING:
logger(ADDBOOKDATA, lastname)
return lastname
#email
def email():
email = input("put in your email: ")
if LOGGING:
logger(ADDBOOKDATA, email)
while not emailchecker(email):
email = input("put in your email: ")
if LOGGING:
logger(ADDBOOKDATA, email)
return email
#phonenumber
def phonenumber():
phonenumber = input("put in your phone number: ")
if LOGGING:
logger(ADDBOOKDATA, phonenumber)
while not phonenumberchecker(phonenumber):
phonenumber = input("put in your phone number: ")
if LOGGING:
logger(ADDBOOKDATA, phonenumber)
return phonenumber
def main():
firstname()
lastname()
email()
phonenumber()
main()
I updated the question and posted the code where the logger gets the information from. so basically, it should append like: firstname, lastname, email, phonenumber in one line and the next time the code is executed. it should write the new info into a newline in the same txt file.
I am trying to ask a user for a username and password and check a file with user name and passwords to see if it exists if it does it just says welcome if it doesnt tells the user he put in the wrong info. The file is just a simple text file with format "username,password" as shown below
SSD,adgEgd
aegag,asdhasdh
here is my code
class Account():
def __init__(self, name, password):
self.name = name
self.password = password
username_input = input("Enter the name: ")
userpassword_input = input("Enter password: ")
file = open('account information.txt', 'r')
data = []
for lines in file:
temp = lines.split(',')
data.append(Account(temp[0], temp[1]))
file.close()
isExsits = ' '
for d in data:
if username_input == d.name and userpassword_input == d.password:
isExsits = 'huzzah'
print(isExsits)
It identifies the username but not the password
There is a newline character in the password and it looks like adgEgd\n after reading from file.
You can get rid from it by using rstrip
data.append(Account(temp[0], temp[1].rstrip()))
This works as you intended, it iterates over all accounts in the account_information.txt file and creates an Account object for each of them which is added to the data list.
Afterwards, we iterate through every account and check to see if the credentials provided by the user match any within the list.
class Account():
def __init__(self, name, password):
self.name = name
self.password = password
username_input = input("Enter the name: ")
userpassword_input = input("Enter password: ")
data = []
with open("account_information.txt") as file:
for line in file.readlines():
credentials = line.rstrip().split(",")
data.append(Account(credentials[0], credentials[1]))
accountExists = False
for account in data:
if (account.name == username_input) and (account.password == userpassword_input):
accountExists = True
print(accountExists)
It seems to working fine like this, so I would likewise say it's probably the newlines or other extraneous characters at the end of the lines that are throwing off the calculation.
user_pass_list = [
('SSD', 'adgEgd'),
('aegag', 'asdhasdh')
]
username = 'SSD'
password = 'adgEgd'
exists = False
for d in user_pass_list:
if username == d[0] and password == d[1]:
exists = True
print(exists) # True
Another approach can be to just do an in check, so that we don't need to iterate over user_pass_list for example:
user_pass_list = [
('SSD', 'adgEgd'),
('aegag', 'asdhasdh')
]
username = 'SSD'
password = 'adgegd' # casing is different
exists = (username, password) in user_pass_list
assert exists is False # True
With the Account class example from the original question, reformatted as a dataclass for slightly cleaner code:
from dataclasses import dataclass
# same as `#dataclass(eq=True)`, so an equals (__eq__) method
# is automatically generated for the class.
#dataclass
class Account:
name: str
password: str
user_pass_list = [
Account('SSD', 'adgEgd'),
Account('aegag', 'asdhasdh')
]
username = 'SSD'
password = 'adgEgd'
exists = Account(username, password) in user_pass_list
assert exists is True # True
**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"