Account management using json - python

Hi. I am trying to make a program that is able to create users and then log them in. Once you're logged in you can change your password. What I can't seem to figure out is how to get it to change your password after you logged in, using only your old password. I can get it to work by inputting your account name, but that's not the point.
Do any of you have any idea of how to fix this problem, I am open to suggestions :)
import json
with open("login_data.txt", "r") as login_file:
try:
users = json.load(login_file)
except:
users = {}
status = ""
def Display_Menu():
status = input("Are you a registered user? (y/n)? Press q to quit: ")
if status == "y":
Old_User()
elif status == "n":
New_User()
elif status == "passwd":
Change_Passwd()
elif status == "q":
skriva = open("login_data.txt", "w")
json.dump(users, skriva)
return status
def New_User():
Create_Login =input("Create login name: ")
if Create_Login in users:
print ("Login name already exist!")
else:
Create_Password =input("Create password: ")
users[Create_Login] = Create_Password
print("New User created!")
def Old_User():
login =input("Enter login name: ")
Password =input("Enter password: ")
if login in users and users[login] == Password:
print("Login successful!")
print(users[login])
status = input("Wanna quit, change pass, och logout?")
if status == "passwd":
Change_Passwd()
elif status == "logout":
Display_Menu()
elif status == "q":
skriva = open("login_data.txt", "w")
json.dump(users, skriva)
return status
else:
print("User doesn't exist or wrong password!")
def Change_Passwd():
oldpass =input("Old password: ")
if oldpass in users:
Create_Password =input("New password: ")
users[oldpass] = Create_Password
if Create_Password == input("Confirm password: "):
print("Password changed!")
else:
print("User authorization failure")
users[create_Login] = oldpass
else:
print ("No password match!")
while status != "q":
status = Display_Menu()
A example of a account file " { "halo": "molly"} "

The minimal change would be to save the currently logged in user to a global variable in Old_User(). Then, when Change_Passwd is called, you can go back to that variable to determine which user you're dealing with. Here's the changes you'd make to Old_User. I'll leave the changes to Change_Passwd up to you to implement.
current_user = None # Declare global variable for saving logged in user
def Old_User():
global current_user # Indicate that we're going to modify the global variable in the local scope
login =input("Enter login name: ")
Password =input("Enter password: ")
if login in users and users[login] == Password:
print("Login successful!")
print(users[login])
current_user = login # Save the logged in user.
...
I should also add that you'd be better served using classes for this. Trying to maintain state (like who the current user is) using global variables is not very scalable and can get confusing pretty quickly. Having classes representing users and active sessions would make things easier.

Related

The users who have already logged in cant login anymore

How can I stop the users who have already logged in cant login any more?
I tried to make a variable equal to True
when the user is logged in and make an if statement But it didnt work
if islogin == True:
print("You are already logged in!")
Heres my code
import json
def login():
user = input("Enter your user name: ")
passw = input("Enter your password: ")
with open("info.json") as f:
dct = json.load(f)
if user in dct and dct[user] == passw:
print("Login succesful!")
else:
print("Error! Incorrect username or password.")
return
while True:
demand = input("What do you want to do? ")
if demand == "login":
login()
elif demand == "exit":
break
else:
print("Error")
if you have a unique user try to create a global list for logged user somting like this:
import json
logged_user=[]
def login():
global logged_user
user = input("Enter your user name: ")
passw = input("Enter your password: ")
with open("info.json") as f:
dct = json.load(f)
if user in dct and dct[user] == passw and user not in logged_user:
print("Login succesful!")
logged_user.append(user)
else:
print("Error! Incorrect username or password or .....")
return
while True:
demand = input("What do you want to do? ")
if demand == "login":
login()
elif demand == "exit":
break
else:
print("Error")

Program keeps displaying None even after input

The code is meant to be a simple login code that saves the login information to a .txt file and then when logging in reads the text file to check the user details.
The code runs up until I create an account or try to login and put in my username and password then it comes back with None. I don't understand why it's coming back with None
def AskAccount():
account = input("\nDo you have an account setup
already? (Y/N)\n")
if account == "Y":
loginexisting()
elif account == "N":
createacc()
else:
print("please type Y or N")
AskAccount()
def loginexisting():
print("Your account already exists, please login\n")
username = input("Please enter your username:")
password = input("Please enter your password:")
f = open('accounts.txt', 'r')
info = f.read()
info = info.split()
if username in info:
index= info.index(username) +1
usr_password = info[index]
if usr_password == password:
return "Welcome Back," + username
else:
return "password entered is wrong"
else:
print("Username is not correct")
print(createacc())
def createacc():
print("Lets create an account for you\n")
username = input("Please input your username:\n")
password = input("please input your password\n")
f = open("accounts.txt",'r')
info = f.read()
if username in info:
return "Name Unavailable. Please Try Again"
f.close()
f = open("accounts.txt",'w')
info = info + " " + username + " " + password
f.write(info)
f.close()
print("Your account details have been saved\n")
print("please login\n")
print(AskAccount())
At the end of your file, you print(AskAccount()). This prints the return value of the function, but AskAccount does not have a return statement, thus it returns None. If you want it to print your desired output, you will need to add return statements.
def AskAccount():
account = input("\nDo you have an account setup
already? (Y/N)\n")
if account == "Y":
return loginexisting()
elif account == "N":
return createacc()
else:
print("please type Y or N")
return AskAccount()

How can I correct this python login system?

I am really new to programming and I am given an exercise on creating a login system using text files. The thing is I got really confused about my codes, the login system contains two roles which are admin and customers, and customers are divided into registered and unregistered customers. Admins and registered customers are supposed to directly login into the system whereas unregistered customers are required to create a new account. Also, we are not allowed to use global variables or imports. I apologize if the codes are absolute chaos.
Here is my code:
#Role selection
role = int(input("Select your role: [Admin = 1, Customer = 2]"))
#Admin login
def adminLogin():
if(role == 1):
adminUsername = input("Enter your username: ")
adminPassword = input("Enter your password: ")
for line in open("adminLoginDetails.txt","r").readlines():
login_info = line.split
if (adminUsername == login_info [0] ) and (adminPassword == login_info[1]):
print("You have successfully logged in!")
else:
print("Invalid username or password, please try again.")
#Customer registration
else:
def cusRegistration():
registration = input("Are you a registered customer? [Yes/No]")
if (registration == "No"):
cusUsername = input("Enter your username: ")
cusPassword = input("Enter your password: ")
file = open("customerDetails.txt","a")
file.write(cusUsername)
file.write(" ")
file.write(cusPassword)
file.write("\n")
file.close()
if cusRegistration():
print("You have successfully created an account!")
#Customer Login
def cusLogin():
if (registration == "Yes"):
cusUsername = input("Enter your username: ")
cusPassword = input("Enter your password: ")
for line in open("customerDetails.txt","r").readlines():
loginInfo = line.split()
if (cusUsername == loginInfo[0]) and (cusPassword == loginInfo[1]):
print ("You have successfully logged in!")
else:
print("Invalid username or password, please try again.")
You need to actually run your functions:
def do_something():
print('something')
Won't run. You need to also use this:
do_something()
In your case:
if role == 1:
adminLogin()
etc
In your code given above, you need to pull your check for roll outside the methods that use them. Currently, nothing is asking your methods to execute.
role = int(input("Select your role: [Admin = 1, Customer = 2]"))
if role == 1:
adminLogin()
if role == 2:
cusLogin()
# etc

imbedded if statement not working properly

his is my first time using this website, so i dont know how to use it properly... apologies if its difficult to read.
i have some code to make a login system for my project, and i have used if and else statements to let the user to log in. however, while it works as in there are no error messages its not doing what i would like it to do. when the user login is, it asks them for the username:
username = input("Enter login name: ")
if username in Users:
passw = input("Enter password: ")
if passw in Users:
print ("Login successful!")
however if the username is correct, the program moves onto " passw = input("Enter password: ") " but no matter if the password is correct or not, it goes back to the login menu... im not sure how to fix it.
#full code:
global number
global Users
global username
number = 1
Users = {}
status = ""
def newuser():
global number
print('To create your unique username, please answer these few questions: ')
first = input('Please type your first name: ')
second = input('Please type your surname/last name: ')
year = input('Please type your birth year: ')
part1 = (first[:3])
part2 = (second[:3])
part3 = (year[2:])
username = part1 + part2 + part3
username = str(part1[:3] + part2[:3] + part3[:2] + '' + str(number))
number = number + 1
print('')
print ('here is your unique username: ')
print (username)
print('')
print ('Make sure you know your username for when you login in next time!')
passw = input('please type in your password to login to your account with: ')
Users[username] = passw
print('')
print ('Your account is made! Taking you back to the menu... ')
print('')
def olduser():
global username
global passw
global Users
username = input("Enter login name: ")
if username in Users:
print (Users)
passw = input("Enter password: ")
if passw in Users:
print ("Login successful!")
mainmenu()
else:
print("User doesn't exist!")
def mainmenu():
print('test for main menu is ready')
while status != "q":
status = input("Are you a registered user? y/n? Press q to quit: ")
if status == "n":
newuser()
elif status == "y":
olduser()
else:
print('invalid input try again')

Hashing in python (encrypting)

i am trying to implement a encryption into my login program, i've looked for help in many places but i can't seem to understand any of it.
Im fairly new to python and im warming up for a university course in it.
im interested in if it is possible to implement it as a class in my already excisting program, any tips or explanations would be greatly appreciated
So basicly what im asking is, how would it look if i wanted the program to encrypt the passwords between runs and the decrypt them again so that the program can use them when it runs.
Program:
import json
with open("login_data.txt", "r") as login_file:
try:
users = json.load(login_file)
except:
users = {}
status = ""
def Display_Menu():
status = input("Are you a registered user? (y/n)? Press q to quit: ")
if status == "y":
Old_User()
elif status == "n":
New_User()
elif status == "passwd":
Change_Passwd()
elif status == "q":
skriva = open("login_data.txt", "w")
json.dump(users, skriva)
return status
def New_User():
Create_Login =input("Create login name: ")
if Create_Login in users:
print ("Login name already exist!")
else:
Create_Password =input("Create password: ")
users[Create_Login] = Create_Password
print("New User created!")
current_user = None
def Old_User():
global current_user
login =input("Enter login name: ")
Password =input("Enter password: ")
if login in users and users[login] == Password:
print("Login successful!")
current_user = login
status = input("Wanna quit, change pass, och logout?")
if status == "passwd":
Change_Passwd()
elif status == "logout":
Display_Menu()
elif status == "q":
skriva = open("login_data.txt", "w")
json.dump(users, skriva)
return status
else:
print("User doesn't exist or wrong password!")
def Change_Passwd():
oldpass =input("Old password: ")
if current_user in users and users[current_user] == oldpass:
Create_Password = input("New password: ")
users[current_user] = Create_Password
if Create_Password == input("Confirm password: "):
print("Password changed!")
else:
print("User authorization failure")
users[current_user] = oldpass
else:
print ("No password match!")
while status != "q":
status = Display_Menu()
MD5 is a really simple hashing algorithm, this is some sample usage:
>>> hashlib.md5("String you want to encrypt").hexdigest()
'096a773d70e934d03ae3dd8022deed5e'
MD5 is by no means secure, but it is sufficient to illustrate some points. You could for instance store usernames and hashed passwords in some format of your choosing, ie.:
username1, hash1
username2, hash2
This (Difference between Hashing a Password and Encrypting it) could be a relevant read.
bcrypt is a library you should have a look at.
import bcrypt
password = b"super secret password"
# Hash a password for the first time, with a randomly-generated salt
hashed = bcrypt.hashpw(password, bcrypt.gensalt())
# Check that a unhashed password matches one that has previously been
# hashed
if bcrypt.hashpw(password, hashed) == hashed:
print("It Matches!")
else:
print("It Does not Match :(")

Categories

Resources