Python : Referencing Data from JSON file in python - python

I'm currently making a username + password login system and have a file containing the usernames and passwords of previously signed up users. The side of the programme that signs up users works perfectly, but I have tried to implement a system to check the data from the file and sign the user in if they input the right data.
Edit: One combination from the database, it's all structured like this; [["ExampleUsername", "BadPasswrdo14130"]]
This is the code:
# Login Interface using files as a 'login database' of sorts?
import json
def autoSave():
with open("Accounts.json", "w") as outfile:
json.dump(accounts, outfile)
def loadUsers():
with open("Accounts.json") as infile:
return json.load(infile)
def existingUser():
eUsername = input("Your Username » ")
ePassword = input("Your Password » ")
for index, item in (accounts):
if item[1] == eUsername and item[2] == ePassword:
print("Logged in")
else:
print("Login failed")
def createUser():
global accounts
nUsername = input("Create Username » ")
nPassword = input("Create Password » ")
entry = [nUsername, nPassword]
accounts.append(entry)
accounts = accounts[:500000]
autoSave()
accounts = loadUsers()
How would I retrieve data from the database file and check that data with the data that the user inputted?
I've tried already but it does not work, always says login failed, which is this bit of the code:
def existingUser():
eUsername = input("Your Username » ")
ePassword = input("Your Password » ")
for index, item in (accounts):
if item[1] == eUsername and item[2] == ePassword:
print("Logged in")
else:
print("Login failed")

In your code accounts is a list. When you're iterating over it, you get sublists. You should iterate over the sublists to get the username and password.
So you can do:
def existingUser():
eUsername = input("Your Username » ")
ePassword = input("Your Password » ")
for item in accounts: #no need for braces
if item[0] == eUsername and item[1] == ePassword:
return "Logged in"
else:
return "Login failed"
print existingUser()
In your current code you seem to have forgotten that in Python list indexes start with 0.

#ForceBru
This is the code I tried to prevent dup accounts, it doesent allow you to dupe accounts but when making a new account, it says its already created when its not, but creates it anyway.
def createUser():
global accounts
nUsername = input("Create Username » ")
nPassword = input("Create Password » ")
for item in accounts:
if item[0] == nUsername:
return "Account Username already exists, try again"
else:
entry = [nUsername, nPassword]
accounts.append(entry)
accounts = accounts[:500000]
autoSave()

Related

How to check the username in text file or not and then ask for the password?

loginUsername = input("Enter Username: ")
loginPassword = input("Enter PASSWORD: ")
data=open('database.txt', 'r')
accounts = data.readlines()
for line in data:
accounts = line.split(",")
if (loginUsername == accounts[0] and loginPassword == accounts[1]):
print("LOGGED IN")
else:
print("Login FAILED")
print(accounts)
I want to make a text login system, which will ask for the username first. After checking the text file which stored username and password, the system will ask for password. But I don't know how to read the first column (which is username, the structure of the text file is "username, password"). If i use readlines() and split(","). But there is "n" at the end of the password.
# You should always use CamelCase for class names and snake_case
# for everything else in Python as recommended in PEP8.
username = input("Enter Username: ")
password = input("Enter Password: ")
# You can use a list to store the database's credentials.
credentials = []
# You can use context manager that will automatically
# close the file for you, when you are done with it.
with open("database.txt") as data:
for line in data:
line = line.strip("\n")
credentials.append(line.split(","))
authorized = False
for credential in credentials:
db_username = credential[0]
db_password = credential[1]
if username == db_username and password == db_password:
authorized = True
if authorized:
print("Login Succeeded.")
else:
print("Login Failed.")
The "n" at the end of the password is probably the newline character \n. In order to remove it, you can use the rstrip() function:
mystring = "password\n"
print(mystring.rstrip())
>>> 'password'

How do I load the username from a csv file?

I learned about creating files using python in computer science at school. I have created a piece of code where you can create a username and password and then it saves to a csv file. There is also another option where you can log in. It asks you to enter the username and if it is wrong it says "Username not found". Whatever I enter (even though it is correct) it says Username not found.
This is the main part of the code:
Log = input("Enter Choice here: ")
if Log == "Log In" or Log == "log in" or Log == "Log in" or Log == "log In":
Data = open("F:\\'Filename'.csv", "r")
SavedUser = Data.readline()
Username = input("Username: ")
if Username == SavedUser:
print("Welcome", Username, "!")
Password = input("Password: ")
if Password == Data.readline():
print("It works")
Thank you for all your help.
Your CSV file is probably not being read correctly. Python has a csv library to parse CSV files correctly. What you can do is read the CSV file to a dictionary and then compare username and password.
import csv
action = input("Enter Choice here: ")
if action.lower() == "Log In".lower(): #Convert both strings two lowercase and then compare
reader = csv.reader(open('demo.csv', 'r')) #parsing the csv file correctly
user_dict = dict(reader) #converting iterable reader directly to a dictionary
#{'abc': 'abc123', 'username': 'password'}
username_input = input("Username:")
if username_input in user_dict: #check if username exists as a key in the dictionary
print("Welcome", username_input, "!")
password_input = input("Password: ")
if password_input == user_dict[username_input]:
print("It works")

How do I loop my password/username login page and read the password/username from an external file?

I'm aware of the multiple posts and sources regarding how to loop and read from a text file. I'm sorry to be that guy but I'm a recent noob at Python and I'm writing this at 1:00 in the morning.
As the title suggests, how do I loop my login page so that if the user enters details incorrectly then they get another chance to try, until they have entered details correctly. The password/username also needs to be read from an external file.
My code:
print ("\nEnter details to access wallet...\n")
username = 'Janupedia'
password = '12345'
userInput = input("What is your username?\n")
if userInput == username:
userInput = input("Password?\n")
if userInput == password:
print("Welcome!")
print('\n--------------------------------------------------------\n')
print ("BTN = 0.10")
print ("= £315.37")
else:
print("That is the wrong password.")
else:
print("That is the wrong username.")
print('\n--------------------------------------------------------\n')
Let's say your text file (credentials.txt) reads:
Janupedia
12345
Maybe something like this will work for you. I've commented the code that I added. You probably want to name the credentials file something else.
print ("\nEnter details to access wallet...\n")
"""
Open File
"""
with open("Credentials.txt", "r") as f:
array = []
for line in f:
array.append(line) #stores username and password
username = array[0]
password = array[1]
login = 0 #initial login status
while login == 0: #as long as login status = 0 loop repeats
userInput = input("Username?")
if username.strip(' \n') == userInput.strip(' \n'):
userInput = input("Password?")
if password.strip(' \n') == userInput.strip(' \n'):
login = 1 #login successful set login status to 1 thus breaking loop
else:
print("Incorrect")
else:
print("Incorrect")
print('\n--------------------------------------------------------\n')
# Login successful loop finished
print("Welcome!")
print('\n--------------------------------------------------------\n')
print ("BTN = 0.10")
print ("= 315.37")
So you want to loop it. Where would a good place for that be? How about when we ask for a question.
Now, look at the condition where we get the right username and password. We don't want to handle it inside the loop. The loop is only there to get the correct username and password.
print("\nEnter details to access wallet...\n")
username = "Janupedia"
password = "12345"
userInput = ""
while userInput != password:
userInput = input("What is your username?\n")
if userInput == username:
userInput = input("Password?\n")
if userInput == password:
break
else:
print("That is the wrong password.")
else:
print("That is the wrong username.")
print("Welcome!")
print("\n--------------------------------------------------------\n")
print("BTN = 0.10")
print("= £315.37")
todo_list = open("Credentials", "a")
todo_list.write("Username = Janupedia + Password = 12345")
todo_list.close()
print("\n--------------------------------------------------------\n")
Now to read your username/password from a file. Let's make it simple. The first line is the username and the second line is the password. There are no other items.
Now create a proper function.
def read_credentials_from_file(filename):
"""Read the file and return (username, password).
File contents are first line username and second line password.
"""
# Using the `with` statement is current best practice.
with open(filepath, "rt") as user:
username = user.readline().strip()
password = user.readline().strip()
return username, password
Now fix your code to use the function.
username, password = read_credentials_from_file(...)
Note in the function we strip line endings. If you are using Python 3.7, use the breakpoint function to step through the code and watch what it is doing.
do something like this:
password = "password"
username = "username"
theirUsername = input("What is your username")
theirPassword = input("What is your password")
while theirUsername != username or theirPassword != password:
print("incorrect")
theirUsername = input("What is your username")
theirPassword = input("What is your password")
print("correct")
You can read from an external file with file = open("externalfile.txt","r") then do text = file.read() and if the file is formatted as
username
password
do text = text.split("\n") and then username = text[0] and password = text[1]
this is what it should look like with an explanation:
file = open("password.txt","r") #this opens the file and saves it to the variable file
text = file.read() #this reads what is in the file and saves it to the variable text
text = text.split("\n") #this makes the text into a list by splitting it at every enter
username = text[0] #this sets the username variable to the first item in the list (the first line in the file). Note that python starts counting at 0
password = text[1] #this sets the password variable to the second item in the list (the second line in the file)
theirUsername = input("What is your username") #gets username input
theirPassword = input("What is your password") #get password input
while theirUsername != username or theirPassword != password: #repeats the code inside while theirUsername is not equeal to username or theirPassword is not equal to password
print("incorrect") #notifies them of being wrong
theirUsername = input("What is your username") #gets new username input
theirPassword = input("What is your password") #gets new password input
print("correct") #tells them they are corrected after the looping is done and the password and username are correct

Password - Login not working Python

I just finished Coursera's Python for Everybody 1st course.
To practice my skills, I decided to make a password and username login. Whenever I create a username, I get my user set error which says 'Invalid credentials'. Here is my code.
import time
import datetime
print ('storingData')
print("Current date and time: ", datetime.datetime.now())
while True:
usernames = ['Admin']
passwords = ['Admin']
username = input ('Please enter your username, to create one, type in create: ')
if username == 'create':
newname = input('Enter your chosen username: ')
usernames.append(newname)
newpassword = input('Please the password you would like to use: ' )
passwords.append(newpassword)
print ('Temporary account created')
continue
elif username in usernames :
dataNum = usernames.index (username)
cpasscode = passwords[dataNum]
else:
print ('Wrong credentials, please try again')
continue
password = input ('Please enter your password: ')
if password == cpasscode:
print ('Welcome ', username)
The code as it appears in my editor
In your code, you have initialized your usernames array right after the while statement. This means that every time it loops back to the beginning, it re-initializes, losing anything that your previously appended. If you move the array initialization outside of the loop, it should work as expected.
This works for python 3. for python 2 you must take input differently refer: Python 2.7 getting user input and manipulating as string without quotations
import time
import datetime
names = ['Admin']
pwds = ['Admin']
while True:
name = input('Name/create: ')
if name == "create":
name = input('New Name: ')
pwd = input('New Pwd : ')
names.append(name)
pwds.append(pwd)
continue
elif name in names:
curpwdindex = names.index(name)
print(names)
curpwd = pwds[curpwdindex]
givenpwd = input('Password: ')
if givenpwd == curpwd:
print("Welcome")
break
else:
print("Inavlid Credential")
else:
print("Wrong Choice")
continue

Simple username and password application in Python

I'm trying to build a simple login and password application using a dictionary. It works fine except the part where it checks if the login matches the password (in the bottom where it says "Login successful!").
If I were to create login 'a' and password 'b', and then create login 'b' and password 'a', it would log me in if I tried to log in with login 'a' and password 'a'. It just checks if those characters exist somewhere in the dictionary, but not if they are a pair.
Any suggestions how to fix this?
users = {}
status = ""
while status != "q":
status = raw_input("Are you a registered user? y/n? Press q to quit: ")
if status == "n": #create new login
createLogin = raw_input("Create login name: ")
if createLogin in users: # check if login name exist in the dictionary
print "Login name already exist!\n"
else:
createPassw = raw_input("Create password: ")
users[createLogin] = createPassw # add login and password
print("\nUser created!\n")
elif status == "y": #login the user
login = raw_input("Enter login name: ")
if login in users:
passw = raw_input("Enter password: ")
print
if login in users and passw in users: # login matches password
print "Login successful!\n"
else:
print
print("User doesn't exist!\n")
Edit
Now that this is working, I'm trying to divide the application to three functions, for readability purposes. It works, except that I get infinite loop.
Any suggestions why?
users = {}
status = ""
def displayMenu():
status = raw_input("Are you a registered user? y/n? Press q to quit: ")
if status == "y":
oldUser()
elif status == "n":
newUser()
def newUser():
createLogin = raw_input("Create login name: ")
if createLogin in users: # check if login name exists
print "\nLogin name already exist!\n"
else:
createPassw = raw_input("Create password: ")
users[createLogin] = createPassw # add login and password
print("\nUser created!\n")
def oldUser():
login = raw_input("Enter login name: ")
passw = raw_input("Enter password: ")
# check if user exists and login matches password
if login in users and users[login] == passw:
print "\nLogin successful!\n"
else:
print "\nUser doesn't exist or wrong password!\n"
while status != "q":
displayMenu()
Right now you are checking if the given password, passw, matches any keys in users (not right). You need to see if the password entered matches that particular user's password. Since you have already checked if the username exists in the dictionary's keys you don't have to check again, so try something like:
if passw == users[login]:
print "Login successful!\n"
EDIT:
For your updated code, I'm going to assume by "infinite loop" you mean that you cannot use q to exit the program. It's because when you're inside displayMenu, you save user input in a local variable named status. This local variable does not refer to the same status where you are checking,
while status != "q":
In other words, you are using the variable status in two different scopes (changing the inner scope does not change the outer).
There are many ways to fix this, one of which would be changing,
while status != "q":
status = displayMenu()
And adding a return statement at the end of displayMenu like so,
return status
By doing this, you are saving the new value of status from local scope of displayMenu to global scope of your script so that the while loop can work properly.
Another way would be to add this line to the beginning of displayMenu,
global status
This tells Python that status within displayMenu refers to the global scoped status variable and not a new local scoped one.
change
if login in users and passw in users: # login matches password
to
if users[login] == passw: # login matches password
Besides, you should not tell the hackers that "User doesn't exist!". A better solution is to tell a generall reason like: "User doesn't exist or password error!"
Please encrypt you passwords in database if you go put this online.
Good work.
import md5
import sys
# i already made an md5 hash of the password: PASSWORD
password = "319f4d26e3c536b5dd871bb2c52e3178"
def checkPassword():
for key in range(3):
#get the key
p = raw_input("Enter the password >>")
#make an md5 object
mdpass = md5.new(p)
#hexdigest returns a string of the encrypted password
if mdpass.hexdigest() == password:
#password correct
return True
else:
print 'wrong password, try again'
print 'you have failed'
return False
def main():
if checkPassword():
print "Your in"
#continue to do stuff
else:
sys.exit()
if __name__ == '__main__':
main()
usrname = raw_input('username : ')
if usrname == 'username' :
print 'Now type password '
else :
print 'please try another user name .this user name is incorrect'
pasword = raw_input ('password : ')
if pasword == 'password' :
print ' accesses granted '
print ' accesses granted '
print ' accesses granted '
print ' accesses granted '
print 'this service is temporarily unavailable'
else :
print 'INTRUDER ALERT !!!!' , 'SYSTEM LOCKED'
print 'INTRUDER ALERT !!!!' , 'SYSTEM LOCKED'
print 'INTRUDER ALERT !!!!' , 'SYSTEM LOCKED'
exit()
This is a very simple one based on the one earlier for a single user with improved grammar and bug fixes:
print("Steam Security Software ©")
print("-------------------------")
print("<<<<<<<<<Welcome>>>>>>>>>")
username = input("Username:")
if username == "username" :
print ("Now type password")
else :
print ("please try another user name. This user name is incorrect")
password = input ("Password:")
if password == "password" :
print ("ACCESS GRANTED")
print ("<<Welcome Admin>>")
#continue for thins like opening webpages or hidden files for access
else :
print ("INTRUDER ALERT !!!!" , "SYSTEM LOCKED")
exit()

Categories

Resources