My question is, how would I compare a username and password two a whole document to find if it is in there. so far I have this:
regorlog = raw_input("press 1 to register, press 2 to log in! \n")
if regorlog == "1":
uname = raw_input("what is your desired username?\n")
pwd = raw_input("what is your desired password?\n")
pwd2 = raw_input("please retype your password\n")
if (pwd == pwd2):
file = open("userlog.txt", "a")
file.write(uname + " || " + pwd + "\n")
file.close()
else:
print 'sorry, those passwords do not match'
elif regorlog == "2":
loguname = raw_input("what is your username? \n")
logpwd = raw_input("what is your password? \n")
file = open("userlog.txt", "r")
#here, I need to read the file userlog.txt, and look and see if the username and password combination exists in the file somewhere.
file.close()
I am having trouble reading the whole file, and looking for the username and password combo. any help would be much appreciated.
I just figured it out. here is what I ended up doing!
regorlog = raw_input("press 1 to register, press 2 to log in! \n")
if regorlog == "1":
uname = raw_input("what is your desired username?\n")
pwd = raw_input("what is your desired password?\n")
pwd2 = raw_input("please retype your password\n")
if (pwd == pwd2):
file = open("userlog.txt", "a")
file.write(uname + " || " + pwd + "\n")
file.close()
else:
print 'sorry, those passwords do not match'
elif regorlog == "2":
loguname = raw_input("what is your username? \n")
logpwd = raw_input("what is your password? \n")
file = open("userlog.txt", "r")
if loguname + " || " + logpwd in open('userlog.txt').read():
print "true"
file.close()
I suggest using a built-in module to do this for you:
import shelve
regorlog = raw_input("press 1 to register, press 2 to log in! \n")
if regorlog == "1":
uname = raw_input("what is your desired username?\n")
pwd = raw_input("what is your desired password?\n")
pwd2 = raw_input("please retype your password\n")
if pwd == pwd2:
shelf = shelve.open("userlog.txt", "c")
shelf[uname] = pwd
shelf.close()
else:
print 'sorry, those passwords do not match'
elif regorlog == "2":
loguname = raw_input("what is your username? \n")
logpwd = raw_input("what is your password? \n")
shelf = shelve.open("userlog.txt", "c")
try:
matched = shelf[loguname] == logpwd
except KeyError:
matched = False
shelf.close()
print 'Matched: ', matched
Edit: fixed. I suggest changing the name of the file, though
change the last part in what you have to:
# ...
elif regorlog == "2":
loguname = raw_input("what is your username? \n")
logpwd = raw_input("what is your password? \n")
login_info = loguname + " || " + logpwd
with open("userlog.txt", "r") as users_file: # closes the file automatically
if any(login_info == line.rstrip() for line in users_file):
# if any line in the file matches
print "true"
But for the love of security please don't store passwords as plaintext
https://crackstation.net/hashing-security.htm
Related
import hashlib
def signup():
email = input("Enter an email address: ")
pwd = input("Enter a password: ")
conf_pwd = input("Confirm your password: ")
if conf_pwd == pwd:
enc = conf_pwd.encode()
hash1 = hashlib.sha256(enc).hexdigest()
with open(r'D:\Python Programs\Login\database.txt', "a") as f:
f.write(email + "\n")
f.write(hash1 + "\n")
f.close()
print("You have registered successfully!")
else:
print("Password is not same as above! \nPlease try again")
signup()
def login():
email = input("Enter email: ")
pwd = input("Enter password: ")
auth = pwd.encode()
auth_hash = hashlib.sha256(auth).hexdigest()
with open(r'D:\Python Programs\Login\database.txt', "r") as f:
stored_email, stored_pwd = f.read().split("\n")
f.close()
if email == stored_email and auth_hash == stored_pwd:
print("Logged in Successfully!")
else:
print("Login failed! \nPlease try again")
login()
def welcome():
print("Welcome to the [Insert Game Name Here]")
HaveAccount = input("Have you made an account before? (Y/N): ")
if HaveAccount == ("Y"):
login()
elif HaveAccount == ("N"):
signup()
else:
print("Please enter either 'Y' or 'N'")
welcome()
welcome()
It is specifically line 23 and it has a ValueError: too many values to unpack (expected 2) whenever I try and log in with an email and password. I need to add some extra text in because my post is mostly code and I don't know what else to say so here is some random typing to make more characters in my post. Any help is appreciated. Thanks
I need help, I don't know hot wo change the value of a cell and save it to the file. I just want to make it so when the user has verified the o changes to 1 in the verified column. The information looks weird because it is encrypted. All of the code for verification and cell stuff can be found in the Verify() function.
The csv file:
The whole code:
import pandas as pd
import re
import csv
import smtplib
import math
import random
from email.message import EmailMessage
#====================================================================================================#
def Register():
firstname = input("Enter your first name: ").lower()
surname = input("Enter your surname: ").lower()
age = input("Enter your age: ")
if not str.isdecimal(age):
print("Age must be a number. Please try again.")
age = input("Enter your age: ")
email = input("Enter your email: ").lower()
regex = "^[a-z0-9]+[\._]?[a-z0-9]+[#]\w+[.]\w{2,3}$"
if not re.search(regex, email):
print("Invalid email please try again.")
email = input("Enter your email: ").lower()
password = input("Enter a strong password: ")
if len(password) < 6:
print("Password should be between 6 to 18 characters long.")
password = input("Enter a strong password: ")
username = firstname[:1] + surname + age
username.lower()
print("\nYour username is: " + username + "\nYour email is: " + email + "\nYour password is: " + password + "\nYour firstname is: " + firstname + "\nYour surname is: " + surname + "\nYour age is: " + age)
encryptedFirstname = "".join(chr(ord(char)+3) for char in firstname)
encryptedSurname = "".join(chr(ord(char)+3) for char in surname)
encryptedAge = "".join(chr(ord(char)+3) for char in age)
encryptedEmail = "".join(chr(ord(char)+3) for char in email)
encryptedPassword = "".join(chr(ord(char)+3) for char in password)
encryptedUsername = "".join(chr(ord(char)+3) for char in username)
verified = "0"
AccountInfo = [encryptedFirstname, encryptedSurname, encryptedAge, encryptedEmail, encryptedPassword, encryptedUsername, verified]
if not str.isdecimal(age) or len(password) < 6 or not re.search(regex, email):
print("Error occured, please make sure all your details are valid.")
MainMenu()
else:
try:
open("Accounts.csv", "x")
with open("Accounts.csv", "a", newline = "") as file:
writer = csv.writer(file)
writer.writerow(["Firstname", "Surname", "Age", "Email", "Password", "Username, Verified"])
writer.writerow(AccountInfo)
file.close()
print("Account successfully made. Please verify your email now.")
MainMenu()
except:
with open("Accounts.csv", "a", newline = "") as file:
writer = csv.writer(file)
writer.writerow(AccountInfo)
file.close()
print("Account successfully made. Please verify your email now.")
MainMenu()
#====================================================================================================#
def Login():
User0 = input("Username: ").lower()
Pass0 = input("Password: ")
encryptedPassword = "".join(chr(ord(char)+3) for char in Pass0)
encryptedUsername = "".join(chr(ord(char)+3) for char in User0)
try:
file = open("Accounts.csv", "r")
except:
print("Account doesn't exist. Please register an account.")
MainMenu()
detailsList = []
line = 0
for line in file:
detailsList.append(line.rstrip('\n').split(","))
loggedIn = 0
for details in detailsList:
if encryptedUsername == details[5] and encryptedPassword == details[4] and details[6] == "0":
loggedIn = 1
break
if encryptedUsername == details[5] and encryptedPassword == details[4] and details[6] == "1":
loggedIn = 2
break
if loggedIn == 1:
print("You need to verify your account.")
MainMenu()
if loggedIn == 2:
print("Successfully logged in.")
MainMenu()
elif loggedIn == 0:
print("Incorrect details.")
MainMenu()
#====================================================================================================#
def Verify():
User1 = input("Username: ").lower()
Pass1 = input("Password: ")
encryptedUsername1 = "".join(chr(ord(char)+3) for char in User1)
encryptedPassword1 = "".join(chr(ord(char)+3) for char in Pass1)
try:
file = open("Accounts.csv", "r")
except:
print("Account doesn't exist. Please register an account.")
MainMenu()
detailsList = []
line = 0
for line in file:
detailsList.append(line.split(","))
loggedIn = False
for details in detailsList:
if encryptedUsername1 == details[5] and encryptedPassword1 == details[4]:
decryptedEmail = "".join(chr(ord(char)-3) for char in details[3])
loggedIn = True
UserEmail = decryptedEmail
break
LineNumber = 0
with open("Accounts.csv", 'r') as file:
for line in file:
LineNumber += 1
if encryptedUsername1 in line:
break
if loggedIn == True:
print("Verifying Email Address...")
digits = "0123456789"
CODE = ""
msg = EmailMessage()
smtp = smtplib.SMTP("smtp.gmail.com", 587)
for i in range(6):
CODE += digits[math.floor(random.random()*10)]
msg.set_content(f"Your code is: {CODE}\nThis code expires in 5 minutes.")
msg["Subject"] = "PyDatabase: Verification"
msg["From"] = "me#gmail.com"
msg["To"] = UserEmail
smtp.starttls()
smtp.login("me#gmail.com", "password")
smtp.send_message(msg)
smtp.quit()
InputedCode = input("Enter Your Code >>> ")
if InputedCode == CODE:
print("Verified!")
LineNumber = LineNumber - 1
DataFrame = pd.read_csv("Accounts.csv")
Pos = DataFrame.loc[LineNumber, "Verified"]
print(Pos)
else:
print("Wrong code, try again!")
MainMenu()
else:
print("Incorrect password or username. Please try again.")
MainMenu()
#====================================================================================================#
def MainMenu():
print("#------------------#" + "\n| 1 - Register |" + "\n| 2 - Login |" + "\n| 3 - Verify |" + "\n#------------------#")
choice = input(">>> ")
if choice == "1":
Register()
elif choice == "2":
Login()
elif choice == "3":
Verify()
else:
print("Invalid choice.")
#====================================================================================================#
MainMenu()
Use df.loc[desired_row, desired_column] = specified_value to set the value, and use pd.to_excel(desired_file_name) to save the file.
I fix it just had to subtract 2 from the line number to get to the right line in the verify function.
LineNumber -= 2
I've been making a program that allows the user to create an account which saves to a txt file, and allows them to login. The text now saves to the file (which I was unable to make work earlier due to using w+ instead of a+) but I am not quite sure I understand how split() works. When I try to use the info saved to the txt file the program returns that the username cannot be found. If anyone could fix this code id appreciate it.
I began a few weeks ago so a lot of this is new to me.
AccountsFile = open("AccountProj.txt", "a+")
AccountList = [line.split('\n') for line in AccountsFile.readlines()]
#Creates an account
def createaccount():
while True:
newname = (input("Please create a username: "))
if newname in AccountsFile:
print("Username already in use.")
continue
elif newname not in AccountsFile:
newpassword = input("Please create a password: ")
checkpassword = input("Re-enter password: ")
if checkpassword == newpassword:
print("Account Sucessesfuly created!")
AccountsFile.write(newname + '\n')
AccountsFile.write(checkpassword + '\n')
AccountsFile.close()
break
elif checkpassword != newpassword:
print("Passwords do not match")
continue
#Logs into an account
def loginaccount():
while True:
username_entry = input("Enter username: ")
if username_entry not in AccountList:
print("Username not found. Please enter a valid name")
continue
if username_entry in AccountList:
password_entry = input("Enter password: ")
if password_entry in AccountList[AccountList.index(username_entry) + 1]:
print("Login sucessful!")
AccountsFile.close()
break
if password_entry not in AccountList[AccountList.index(username_entry) + 1]:
print("Username and password do not match. Please try again.")
AccountsFile.close()
continue
while True:
#Asks if user wants to create or login to an account
loginchoice = input("Would you like to login? (Y/N) ")
if loginchoice in ('Y', 'N'):
if loginchoice == 'Y':
loginaccount()
if loginchoice == 'N':
createchoice = str(input("Would you like to create an account? (Y/N) "))
if createchoice in ('Y', 'N'):
if createchoice == 'Y':
createaccount()
if createchoice == 'N':
pass
break
else:
print("Invalid Input")
def CreateAccount():
Username = input("Username: ") #Enter Username
Username.replace(" ", "") #Removes spaces (Optional)
AppValid = True #Default value that changes if duplicate account found
File = open("Accounts.txt","r") #Checking if username already exits
for Line in File:
Account = Line.split(",")
if Account[0] == Application:
print("There is already an Account with this Username")
AppValid = False #Changing value if username exits
File.close()
if AppValid == True: #If username not found, carries on
Password = input("Password: ") #Asks for Password
CheckPassword = input("Password: ")
if Password == CheckPassword:
print("Password's Match!") #Password Match
else:
print("No match")
File = open("Accounts.txt","a") #Writing new account to File
File.write(Username + "," + Password + "\n")
File.close()
def ViewAccount(Username, Password):
File = open("Accounts.txt","r")
Data = File.readlines()
File.close()
if len(Data) == 0:
print("You have no Accounts") #Account not found since no accounts
else:
AccountFound = false
for X in Data: #Looping through account data
if X[0] == Username: #Username match
if X[1] == Password:
AccountFound = true
print("Account Found")
if AccountFound = false:
print("Account not FOUND")
Theres some code i threw together (JK my hand hurts from typing that and my keyboard is screaming) but back to the point .split(" ") would split a string into a list based on spaces for that example, eg:
String = "Hello There"
String = String.split(" ") #Or String.split() only owrks for spaces by default
print("Output:", String[0]) #Output: Hello
print("Output:", String[1]) #Output: There
String = "Word1, Word2"
String = String.split(", ") #Splits string by inserted value
print("Output:", String[0]) #Output: Word1
print("Output:", String[1]) #Output: Word2
String = "abcdefghijklmnop"
String = String.split("jk") #Splits string by inserted value
print("Output:", String[0]) #Output: abcdefghi
print("Output:", String[1]) #Output: lmnop
Check AccountList - both split() and readlines() create a list for you, so you have a list of lists and your username_entry check can't work that way.
I cannot see a reason why my program isnt able to compare the users input and such. My program is a Username/Password program for a OS i am working on i am not sure why it isnt working it always fires back with incorrect even when it is correct?
import os
isuserempty = os.stat("Username.txt").st_size == 0
ispassempty = os.stat("Password.txt").st_size == 0
if isuserempty or ispassempty == True:
print("Hello, new user create a username and password.")
newusername = input("Enter your new username: ")
NewUser = open("Username.txt" , "a")
NewUser.write(newusername)
NewUser.close()
newpassword = input("Enter your new password: ")
NewPass = open("Password.txt" , "a")
NewPass.write(newpassword)
NewPass.close()
print("You now have a new Username and Password!")
print("You are now logged in!")
elif isuserempty or ispassempty == False:
truePass = open("Password.txt", "r")
trueUser = open("Username.txt", "r")
print("Enter your Username.")
userUserName = input("Enter:")
print("Enter your password.")
userPass = input("Enter:")
if userUserName == trueUser and userPass == truePass:
print("Correct! Logging in...")
if userUserName != trueUser or userPass != truePass:
print("Incorrect!")
Your truePass and trueUser are variables of type TextIOWrapper (files) which you currently compare to strings. In your elif block, read the contents of your files like this before doing the comparison.
pass_file = open("Password.txt", "r")
truePass=pass_file.read()
user_file = open("Username.txt", "r")
trueUser = user_file.read()
print("Welcome to English, please enter your name,age,and password.")
print("If you have previously signed in, enter using the same name,age,and password")
name = input("Please enter your name: ")
age = input("Now please enter you age: ")
username = name[0:3] + age
password = input("Now please create a password: ")
userpass = (username+","+password)
check = open("logins.txt")
string = check.read().strip().split()
if userpass in string:
print("You have logged in as",username,"The questions will now start. \n")
else:
newlog = input("Looks like you dont have an account with those details, Would you like to create a new one? Y/N: ")
if newlog == "Y" or newlog == "y" or newlog == "yes" or newlog == "Yes":
f = open("logins.txt","a+")
chosen = f.write(username+","+password+"\n")
print("The username",username,"and password",password,"have now been saved, the questions will now start \n")
f.close()
else:
print("Please either sign in or log in and try again.")
welcome()
import random
f = open("English.txt","r")
points = 0
for line in f:
currentLine = line.split(",")
q = currentLine[0]
answer = currentLine[1]
questions = currentLine[1:-1]
random.shuffle(questions)
print(q)
for i in range(len(questions)):
print (i+1,":",questions[i])
userAnswer = int(input("Make a selection :"))
if answer == questions[userAnswer-1]:
points = (points+1)
print ("CORRECT, You have",points,"points")
str(points)
else:
print ("INCORRECT")
f.close()
f = open("scores.txt","a+")
score = f.write(username+","+password+","+points+"\n") #It is giving a type error about this line and I cant seem to understand why
f.close()
The error shown is:
line 193, in english
score = (username+","+password+","+points+"\n")
TypeError: must be str, not int
Please let me know if you have a better way of writing the scores into a text file. THank you.
Replace the error line with: score = f.write(username+","+password+","+str(points)+"\n")