Python: How to compare file context to user input - python

I have a Register.txt file in which I enter all user information such as username, email and password.
The content is written into the file as follows:
> emailadress, username, password;
That's my code:
import os
script_dir = os.path.dirname(__file__)
rel_path = 'Register.txt'
abs_file_path = os.path.join(script_dir, rel_path)
print('Welcome')
ExistingUser = input('Do you already have an Account y/n?: ')
def add_user(email, username, password):
file = open(abs_file_path, 'a')
file.write('> ' + email + ', ' + username + ', ' + password + ';\n')
file.close()
def check_password(userPassword, userName):
file = open(abs_file_path, 'r')
file_contents = file.read()
password = userPassword
Flag = 0
for i in file_contents.split('\n'):
if password == i:
Flag = 1
if Flag == 1:
print('Welcome back, ', userName)
else:
print('Something went wrong.')
if ExistingUser.lower() == 'n':
while True:
userEmail = input('email: ')
userName = input('username: ')
userPassword = input('password: ')
userPasswordConfirm = input('Confirm password: ')
if userPassword == userPasswordConfirm:
add_user(userEmail, userName, userPassword)
ExistingUser = 'y'
break
print('Passwords does NOT match!')
print('You have successfully registered!')
if ExistingUser.lower() == 'y':
while True:
userName = input('username: ')
userPassword = input('password: ')
check_password(userPassword, userName)
My Output looks in the Login section always like this: Something went wrong

If each line in the file looks like this
>>> line = '> emailadress, username, password;'
You need to separate it into its three parts before doing comparisons. First remove the unwanted characters at the beginning and the end.
>>> line = line[2:-1]
>>> line
'emailadress, username, password'
Then split the line on the commas.
>>> email,uname,password = line.split(', ')
>>> uname, password
('username', 'password')
>>> uname == 'username' and password == 'password'
True
>>>

Related

Checking for the users input in a text file and if it is there it will print something

I am making a login/ sign up page in python for fun but im kinda stuck.
I have made my sign up page but im stuck with the login page
I need some code that reads the text file(info.txt) for what the user inputted and if they are both there in the same line it will print something
https://i.stack.imgur.com/ONsWB.png <- here is what my files look like and here is my sign up code
print("Welcome to sign up Enter your details below")
username = input("Enter Username:")
password = input("Enter Password:")
#input text
input_dictionary = {"one" : 1, "two" : 2}
#open file
file = open("info.txt", "w")
#convert variable to string
str = repr(username)
lol = repr(password)
file.write(str + ":" + lol + "\n")
#close file
file.close()
f = open('info.txt', 'r')
if f.mode=='r':
contents= f.read()
print("Well done you now have a account!")
and so far my login page code is
username = input("Username:")
password = input("Password:")
Something like this should work
username = input("Username:")
password = input("Password:")
with open('info.txt') as f:
# split file on newline
users = f.read().split('\n')
if username + ":" + password in users:
# user logged in
you could do something like this:
import time as t
f_content = open("info.txt",'r').read()
while True:
username = input("Username:")
password = input("Password:")
infos = [username,password]
for user in f_content:
user_info = user.split(":")
if user_info == infos:
found = True
print("Successfully logged in!")
#some code
if not found:
print("User was not found!\nWait 20 seconds to reset")
t.sleep(20)
and you should always put things like this in functions, to avoid calling external modules:
import time as t
f_content = open("info.txt",'r').read()
def signin():
print("Welcome to sign up Enter your details below")
username = input("Enter Username:")
password = input("Enter Password:")
#input text
input_dictionary = {"one" : 1, "two" : 2}
#open file
file = open("info.txt", "w")
#convert variable to string
str = repr(username)
lol = repr(password)
file.write(str + ":" + lol + "\n")
#close file
file.close()
f = open('info.txt', 'r')
if f.mode=='r':
contents= f.read()
print("Well done you now have a account!")
def login(username,password):
infos = [username,password]
for user in f_content:
user_info = user.split(":")
if user_info == infos:
found = True
print("Successfully logged in!")
#some code
if not found:
print("User was not found!\nWait 20 seconds to reset")
t.sleep(20)
if __name__ == '__main__':
if f_content == '':
signin()
exit()
while True:
username = input("Username >> ")
password = input("Password >> ")
login(username,password)
if you though i overcomplicated things, you should do just like this:
username = input("Username:")
password = input("Password:")
f = open('info.txt')
# split file on newline
users = f.read().split('\n')
if username + ":" + password in users:
# do some code
...

I need to read a json file for my Login System in Python

I am struggling with reading the json file and checking if the username is registered and wether the password is correct. I tried to do it my self but it just work when the username and the password is in the first line. Please Help:
import json
print("LoginSystem #mvtthis")
myRL = input("Login or Register?")
if myRL == "Register":
User = input("Username:")
PW = input("Password:")
PW1 = input("Confirm Password:")
if(PW == PW1):
print("Registration successfully.")
with open('LoginSystemData.json', 'a') as f:
f.write("\n" + User + "," + PW)
else:
print("Registration failed! Please confirm your Password correctly.")
if myRL == "Login":
User = input("Username:")
PW = input("Password:")
success = False
with open('LoginSystemData.json', 'r') as f:
for i in f:
a,b = i.split(",")
b = b.strip()
a = a.strip()
if(a==User and b==PW):
print("Login successful")
else:
print("Login failed. Wrong Username or Password.")
f.close()
break
it works for me:Try this
...
if myRL == "Login":
User = input("Username:")
PW = input("Password:")
with open('LoginSystemData.json', 'r') as f:
readable = f.read() # --> you need to readable:str your file
lines = readable.splitlines() # --> ['name,pw','name,pw','name,pw']
user = list(filter(lambda l:l.split(',')[0] == User and l.split(',')[1] == PW,lines))
if user:
print("Login successful")
else:
print("Login failed. Wrong Username or Password.")
f.close()
actually the filter() doing like for loop:
if you wanna check it : https://www.w3schools.com/python/ref_func_filter.asp

How to convert a list to a file and the load that file into a list again?

I am trying to create a lock which can only be opened with a password in python. You can also create an account to login to the lock. How do I save accounts to a list and access them again when I want to login?
This is what I have tried:
from sys import exit
import re
def num_there(s):
return any(i.isdigit() for i in s)
def special_character_check(String):
rex = re.compile('[#_!#$%^&*()<>?/\|}{~:]')
search = rex.search(String)
if search == None:
print('This password has no special characters')
exit()
f = open('file.txt', 'w')
e = open('file2.txt', 'w')
login_signup = input('Do you want to login or sign up?')
available_accounts_usernames = [f]
available_accounts_passwords = [e]
content = available_accounts_usernames
content2 = available_accounts_passwords
login_username = ''
login_password = ''
signup_username = ''
signup_password = ''
signup_confirm_password = ''
if login_signup in ('login', 'Login'):
login_username = input('Please enter your username')
login_password = input('Please enter your password')
if login_username not in (available_accounts_usernames) or login_password not in (available_accounts_passwords):
print('Access denied')
exit()
if login_username in (available_accounts_usernames) and login_password in (available_accounts_passwords):
print('Access granted')
exit()
if login_signup in ('sign up', 'Sign up'):
signup_username = input('Please enter a username. This username will be asked if you want to login')
signup_password = input('Please enter a password. You will be asked to confirm your password')
if len(signup_password) < 8:
print('This password should be more than 8 characters. PLease enter your info again.')
exit()
if num_there(signup_password) == False:
print('This password has no number')
exit()
if num_there(signup_password) == True:
special_character_check(signup_password)
signup_confirm_password = input('Please confirm your password')
if signup_password == signup_confirm_password:
available_accounts_usernames.append(signup_username)
available_accounts_passwords.append(signup_password)
print('Your account has been created. Please login to access it.')
if signup_password != signup_confirm_password:
print("These passwords don't match. Please enter your info again")
exit()
content = available_accounts_usernames
content2 = available_accounts_passwords
f.write(str(content))
e.write(str(content2))
It just doesn't work. Sorry if its a long question. I am new to python
To solve the problem of storing and reading data you can use some data format such as pickle, json, yaml, toml. But for the simplicity and for the most common data format we will use json. Now, json comes with the python standard library by default and here is some sample json files if you want to know how json looks:
{
"name": "xcodz",
"languages": ["python", "html", "css"],
}
[
"eggs",
"bread",
"wheat",
{
"name": "CustomObject",
"cost": 1000
},
"noodles"
]
So how does files work. you can open a file using open method.
file = open('MyFile.txt', 'r') # 'r' can be replaced with different modes
file.read() # read all the contents
file.write('some content') # works only when mode is 'w', 'wb', 'w+b', 'a', 'ab', 'a+b'
file.seek(0) # change the position
now for your purpose here is the json code:
from sys import exit
import re
import json
import os # For creating defaults
def num_there(s):
return any(i.isdigit() for i in s)
def special_character_check(String):
rex = re.compile('[#_!#$%^&*()<>?/\|}{~:]')
search = rex.search(String)
if search == None:
print('This password has no special characters')
exit()
if not os.path.isfile('database.json'):
with open('database.json', 'w') as f:
f.write('{"usernames": [], "passwords": []}')
with open('database.json', 'r') as f:
data = json.load(f)
available_accounts_usernames = data['usernames']
available_accounts_passwords = data['passwords']
login_signup = input('Do you want to login or sign up?')
content = available_accounts_usernames
content2 = available_accounts_passwords
login_username = ''
login_password = ''
signup_username = ''
signup_password = ''
signup_confirm_password = ''
if login_signup in ('login', 'Login'):
login_username = input('Please enter your username')
login_password = input('Please enter your password')
if login_username not in (available_accounts_usernames) or login_password not in (available_accounts_passwords):
print('Access denied')
exit()
if login_username in (available_accounts_usernames) and login_password in (available_accounts_passwords):
print('Access granted')
exit()
if login_signup in ('sign up', 'Sign up'):
signup_username = input('Please enter a username. This username will be asked if you want to login')
signup_password = input('Please enter a password. You will be asked to confirm your password')
if len(signup_password) < 8:
print('This password should be more than 8 characters. PLease enter your info again.')
exit()
if num_there(signup_password) == False:
print('This password has no number')
exit()
if num_there(signup_password) == True:
special_character_check(signup_password)
signup_confirm_password = input('Please confirm your password')
if signup_password == signup_confirm_password:
available_accounts_usernames.append(signup_username)
available_accounts_passwords.append(signup_password)
print('Your account has been created. Please login to access it.')
if signup_password != signup_confirm_password:
print("These passwords don't match. Please enter your info again")
exit()
content = available_accounts_usernames
content2 = available_accounts_passwords
with open('database.json', 'w') as f:
json.dump({'usernames': content, 'passwords': content2}, f)
More info at https://docs.python.org/3.9/library/json.html
You might want to use pickle files instead.
import pickle as pkl
# Write to file
with open("accounts.pkl","wb") as f:
pkl.dump(accounts, f) # accounts is the list
# Read the file
with open("accounts.pkl","rb") as f:
accounts = pkl.load(f)

why am I getting cryptography fernet InvalidToken when using the same key

Hello so I am making a password manager and I want to encrypt the password file, so I generate and create the first password and when I read it and decrypt it reads it. And then when making another password it creates it but then when decrypting it throws an error. From what I can see I am using the same key.
Here is the code:
#imports
import random,string,os,sys
from cryptography.fernet import Fernet
import bcrypt
if os.path.isfile('salt.txt'):
#Gets the salt
with open('salt.txt','rb') as saltfile:
salt = saltfile.read()
else:
with open('salt.txt','wb')as saltfile:
salt = bcrypt.gensalt()
saltfile.write(salt)
saltfile.close()
#Hashes the item
def hashPass(item):
global passwordOut
hashed = bcrypt.hashpw(item,salt)
passwordOut = hashed
return passwordOut
#Password Generator
def setPassword(length=30,char=string.ascii_letters+string.digits+string.punctuation):
global generatedPassword
generatedPassword= ''.join(random.choice(char) for x in range(length))
return generatedPassword
if os.path.isfile('mykey.key') == True:
#Opens the key
with open('mykey.key', 'rb') as mykey:
print('True')
key = mykey.read()
f = Fernet(key)
mykey.close()
elif os.path.isfile('mykey.key')== False:
print('False')
# Generates a kay
key = Fernet.generate_key()
# Writes a new key
with open('mykey.key', 'wb') as mykey:
mykey.write(key)
f = Fernet(key)
mykey.close()
#Sets the key
#Stating initalization
print("Hello and welcome to your password manager!")
while True:
#If there is a user file
if os.path.isfile('user.txt'):
#Read the user file
with open('user.txt','rb') as user_file:
file = user_file.read()
#Gets the inputs
getUser = input("Enter your username ").encode('utf-8')
getPass = input('Enter your password: ').encode('utf-8')
#Hashes the inputs through the hashing funcion
hashPass(item=getUser)
usr = passwordOut
hashPass(item=getPass)
passw = passwordOut
#If the users hashed input is the same in the users file it carries on with the procedure
if usr in file and passw in file:
while True:
print("""Pick from the list of what you want to do:
1. Generate a new password
2. See passwords
3. Quit""")
usrinput = int(input('Enter a number from the menu: '))
if usrinput == 1:
print("\nGenerating password...")
setPassword()
usrinput = input("What is the password for: ")
splitter = ': '
#
if os.path.isfile('passwordenc.txt'):
with open('passwordenc.txt','ab')as password_file:
var = usrinput + splitter + generatedPassword + '\n'
encrypted = f.encrypt(bytes(var.encode('utf-8')))
password_file.write(encrypted)
print("Your new password for: "+usrinput)
print("And the password is: "+generatedPassword)
password_file.close()
else:
with open('passwordenc.txt','wb')as password_file:
var = usrinput + splitter + generatedPassword + '\n'
encrypted = f.encrypt(bytes(var.encode('utf-8')))
password_file.write(encrypted)
print("Your new password for: " + usrinput)
print("And the password is: " + generatedPassword)
password_file.close()
if usrinput == 2:
if os.path.isfile('passwordenc.txt'):
with open('passwordenc.txt','rb') as password_file:
read = password_file.read()
decrypt = f.decrypt(read)
print(decrypt)
password_file.close()
else:
print('File not found! Need to create a new file.')
if usrinput == 3:
quit()
#If not the same it loops back around
else:
print("\nUser not found!\n")
#If there is no file:
else:
#Gets a user input
username = input('Enter a username: ').encode('utf-8')
password = input('Enter a password, cannot be changed! ').encode('utf-8')
#Hashes the user input
hashPass(item=username)
usr = passwordOut
hashPass(item=password)
passw = passwordOut
#Writes the user input
with open('user.txt','wb') as user:
user.write(usr)
user.write(passw)
print('\nUser has been created!\n')
Here is the terminal code:
C:\Users\James\Documents\passwords\venv\Scripts\python.exe C:/Users/James/Documents/passwords/main.py
True
Hello and welcome to your password manager!
Enter your username james
Enter your password: Kaits_1204
Pick from the list of what you want to do:
1. Generate a new password
2. See passwords
3. Quit
Enter a number from the menu: 2
Traceback (most recent call last):
File "C:\Users\James\Documents\passwords\venv\lib\site-packages\cryptography\fernet.py", line 119, in _verify_signature
h.verify(data[-32:])
File "C:\Users\James\Documents\passwords\venv\lib\site-packages\cryptography\hazmat\primitives\hmac.py", line 74, in verify
ctx.verify(signature)
File "C:\Users\James\Documents\passwords\venv\lib\site-packages\cryptography\hazmat\backends\openssl\hmac.py", line 75, in verify
raise InvalidSignature("Signature did not match digest.")
cryptography.exceptions.InvalidSignature: Signature did not match digest.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:/Users/James/Documents/passwords/main.py", line 106, in <module>
decrypt = f.decrypt(read)
File "C:\Users\James\Documents\passwords\venv\lib\site-packages\cryptography\fernet.py", line 80, in decrypt
return self._decrypt_data(data, timestamp, time_info)
File "C:\Users\James\Documents\passwords\venv\lib\site-packages\cryptography\fernet.py", line 137, in _decrypt_data
self._verify_signature(data)
File "C:\Users\James\Documents\passwords\venv\lib\site-packages\cryptography\fernet.py", line 121, in _verify_signature
raise InvalidToken
cryptography.fernet.InvalidToken
Process finished with exit code 1
The problem is that you take input of user for chosen account password then you append splitter and random generated password then '/n'. After that you encrypt this var using fernet. This method will work to view your first password since with first password you read and decrypt whole file but not with multiple encrypted passwords since each var encryption is unique (having different IV) which means that to decrypt all the passwords you will need a way to signal the end of an encrypted password and beginning of another encrypted password so that you pass to ferent the correct ciphertext with correct margins. This can be done by simply adding --END OF PASSWORD-- after each encryption write to password file. Then during reading of passwords you can just split pass file on these margins and pass result to fernet.
NOTE: dont use this code as your password manager since although you encrypt your passwords you are leaving your master password in mykey.key unencrypted which makes this totally useless.
import random,string,os,sys
from cryptography.fernet import Fernet
import bcrypt
if os.path.isfile('salt.txt'):
#Gets the salt
with open('salt.txt','rb') as saltfile:
salt = saltfile.read()
else:
with open('salt.txt','wb')as saltfile:
salt = bcrypt.gensalt()
saltfile.write(salt)
#saltfile.close() # You dont need to close
#Hashes the item
def hashPass(item):
global passwordOut
hashed = bcrypt.hashpw(item,salt)
passwordOut = hashed
# return passwordOut
# Random Password Generator
def setPassword(length=30,char=string.ascii_letters+string.digits+string.punctuation):
global generatedPassword
generatedPassword= ''.join(random.choice(char) for x in range(length))
return generatedPassword
if os.path.isfile('mykey.key') == True:
#Opens the key
with open('mykey.key', 'rb') as mykey:
print('True')
key = mykey.read()
f = Fernet(key)
elif os.path.isfile('mykey.key')== False:
print('False')
# Generates a kay
key = Fernet.generate_key()
# Writes a new key
with open('mykey.key', 'wb') as mykey:
mykey.write(key)
f = Fernet(key)
#mykey.close() # with doesnt need file to be closed
#Sets the key
#Stating initalization
print("Hello and welcome to your password manager!")
while True:
#If there is a user file
if os.path.isfile('user.txt'):
#Read the user file
with open('user.txt','rb') as user_file:
file = user_file.read()
print("File ", file)
#Gets the inputs
getUser = input("Enter your username ").encode('utf-8')
getPass = input('Enter your password: ').encode('utf-8')
#Hashes the inputs through the hashing funcion
hashPass(item=getUser)
usr = passwordOut
hashPass(item=getPass)
passw = passwordOut
#If the users hashed input is the same in the users file it carries on with the procedure
if usr in file and passw in file:
while True:
print("""Pick from the list of what you want to do:
1. Generate a new password
2. See passwords
3. Quit""")
usrinput = int(input('Enter a number from the menu: '))
if usrinput == 1:
print("\nGenerating password...")
setPassword()
usrinput = input("What is the password for: ")
splitter = ': '
#
if os.path.isfile('passwordenc.txt'):
with open('passwordenc.txt','ab')as password_file:
var = usrinput + splitter + generatedPassword + '\n'
encrypted = f.encrypt(bytes(var.encode('utf-8')))
password_file.write(encrypted)
password_file.write(b"--END OF PASSWORD--")
print("Your new password for: "+usrinput)
print("And the password is: "+generatedPassword)
else:
with open('passwordenc.txt','wb')as password_file:
var = usrinput + splitter + generatedPassword + '\n'
encrypted = f.encrypt(bytes(var.encode('utf-8')))
password_file.write(encrypted)
password_file.write(b"--END OF PASSWORD--")
print("Your new password for: " + usrinput)
print("And the password is: " + generatedPassword)
if usrinput == 2:
if os.path.isfile('passwordenc.txt'):
with open('passwordenc.txt','r') as password_file:
whole_file = password_file.read()
password_list = whole_file.split("--END OF PASSWORD--")
for password in password_list:
if password:
decrypt = f.decrypt(bytes(password, encoding="utf-8"))
print("Decrypted pass: ", decrypt)
else:
print('File not found! Need to create a new file.')
if usrinput == 3:
quit()
#If not the same it loops back around
else:
print("\nUser not found!\n")
#If there is no file:
else:
#Gets a user input
username = input('Enter a username: ').encode('utf-8')
password = input('Enter a password, cannot be changed! ').encode('utf-8')
#Hashes the user input
hashPass(item=username)
usr = passwordOut
hashPass(item=password)
passw = passwordOut
#Writes the user input
with open('user.txt','wb') as user:
user.write(usr)
user.write(passw)
print('\nUser has been created!\n')

how to read a variable line by line from a text file and split it python

i'm trying to create a sign up menu where it takes your username and password then saves them onto a new line in a text text file so after making multiple accounts ill have multiple lines with one username and one password each. i then want to read the file back line by line and split the username and password into two variables (u and p), save u and p onto a database in sqlite3 then repeat for the next line until all lines have been saved to the database. however i cannot figure this out as no matter what i try there's an error with unpacking values either to many or to few. i think the \n at the end of each line may be the/one of the problems.
any help is appreciated thanks.
Here is the code:
import time
import sqlite3
import os
db2 = sqlite3.connect('pass.db')
cur = db2.cursor()
def sign_up():
global cur
details = '1'
with open('username','a') as user:
cur.execute('CREATE TABLE IF NOT EXISTS pass (username TEXT, password TEXT)')
username = input('please enter a username:')
username = username.title()
password = ''
password2 = '.'
while password != password2 or len(password) < 6 or password.isalnum() == False:
password = input('please enter a password with AT LEAST 6 CHARACTERS AND ONE NUMBER:')
password2 = input('please confirm your password:')
user.write(username + ',' + password + ',' + '\n')
with open('username','r') as user:
hello = ''.join(user.readlines())
print (hello)
for line in hello:
details = user.readline()
details = ''.join(details)
print (details)
u, p = details.split(',')
cur.execute('INSERT INTO pass (username, password) VALUES (?, ?)',(u, p,))
print(u)
print(p)
cur.execute('SELECT username FROM pass WHERE username = ?',(username,))
for row in cur:
print(row)
sign_up()
replace details = ''.join(details) code with follwing
details = details.strip()
if details != '':
u, p = details.split(',')
cur.execute('INSERT INTO pass (username, password) VALUES (?, ?)',(u., p,))
use strip() or lstrip() function which will remove '\n'
The problem is that you are joining the lines in hello. When you iterate, you are iterating the characters in a string, and of course you cannnot split a character.
thanks guys i know this is by no means the best way to store passwords or anything but for what its used for and i have looked on google to try and find something better but everything that came up was either far to basic or at a level i dont yet understand and the actual security of the password isnt too important for what im using them for.
i got it too work with this code:
import time
import sqlite3
import os
db2 = sqlite3.connect('pass.db')
cur = db2.cursor()
def sign_up():
global cur
details = '1'
with open('username','a') as user:
cur.execute('CREATE TABLE IF NOT EXISTS pass (username TEXT, password TEXT)')
username = input('please enter a username:')
username = username.title()
password = ''
password2 = '.'
while password != password2 or len(password) < 6 or password.isalnum() == False:
password = input('please enter a password with AT LEAST 6 CHARACTERS AND ONE NUMBER:')
password2 = input('please confirm your password:')
user.write(username + ',' + password + ',' + '\n')
with open('username','r') as user:
details = user.readline()
details = details.strip()
print(details)
while details != '':
if details != '':
u, p = details.split(',',1)
cur.execute('INSERT INTO pass (username, password) VALUES (?, ?)',(u, p,))
details = user.readline()
details = details.strip()
cur.execute('SELECT * FROM pass')
for row in cur:
print(row)
cur.execute('SELECT username FROM pass WHERE username = ?',(username,))
data = cur.fetchall()
if len(data) == 0:
sign_up()
sign_up()

Categories