Issues with my Python login script. Invalid syntax on try - python

I am having issues with the current program that I am trying to write. I don't understand why it keeps saying this or why.
Also can this code be extended to cover IP logging and making sure multiple users can be logged in on the same IP in theory?
Here is the code:
import hashlib
import time
#cPickle is faster then pickle but not available in all python releases
#thats why i used a try/accept there
try: import cPickle as cp
#load the database if it exist, if not it create one
try:
f =(r"C:\Users\Owner\Desktop\python\database.data")
data = cp.load(f)
except IOError:
data = {}
#A simple function made to make data dumping easy
def easyDump(data_):
f = file(r"C:\Users\Owner\Desktop\python\database.data", "w")
cp.dump(data_, f)
f.close()
#Get's the date (We'll use this as the custom salt)
def getData():
return str(time.strftime("%d-%m-%Y"))
#A function which accepts two parameters, password and date.
#The date is the custom salt. It returns the sha512 hash excetpyion
def salt(password, date):
salted = hasglib.sha512(password + str(data)).hexdigest()
retun str(salted)
menu = """"
1.Login
2.Register
3.Exit
"""
while True:
print menu
choice = int(raw_input("Your choice please: "))
if choice ==1:
username = raw_input("Enter your username please: ")
password = raw.input("Enter your authentication code please: ")
#if the username is found on the database
if data.has_key(username):
#date is equal to our secured stored data
date = date[username][1]
#check of the given password + date is equal to what is stored on the database
#password
if salt(password, date) == date[username][0]:
print"Welcome %s!" % username
else:
print "Incorrect password"
else:
print "user %s not found, please register!" % username
elif choice == 2:
username = raw_input("Please enter yout username: !")
password = raw_input("Please enter your password: !")
#if username exists in the system already then the name is taken
if data.has_key(username):
print "user %s already registered, please put in another % username
else:
#in order words data = {username: hash, date}
data[username] = [salt(password, getData()), get Data()]
easyDump(data)
print "user %s successfully registereed!" %username
elif choice == 3:
print "goodbye!"
break
else:
print "invaid input or commands"

This code:
try: import cPickle as cp
is not followed by an except ... hence the syntax error

Your code contains many indenting, syntax errors and spelling mistakes. The following fixes these to allow it to at least run:
import hashlib
import time
#cPickle is faster then pickle but not available in all Python releases
#That is why I used a try/accept there
try:
import cPickle as cp
except:
import pickle as cp
#load the database if it exist, if not it create one
try:
f = open(r"C:\Users\Owner\Desktop\python\database.data")
data = cp.load(f)
except IOError:
data = {}
#A simple function made to make data dumping easy
def easyDump(data_):
f = file(r"C:\Users\Owner\Desktop\python\database.data", "w")
cp.dump(data_, f)
f.close()
#Get's the date (We'll use this as the custom salt)
def getData():
return str(time.strftime("%d-%m-%Y"))
#A function which accepts two parameters, password and date.
#The date is the custom salt. It returns the sha512 hash exception
def salt(password, date):
salted = hasglib.sha512(password + str(data)).hexdigest()
return str(salted)
menu = """"
1.Login
2.Register
3.Exit
"""
while True:
print menu
choice = int(raw_input("Your choice please: "))
if choice == 1:
username = raw_input("Enter your username please: ")
password = raw.input("Enter your authentication code please: ")
#if the username is found on the database
if data.has_key(username):
#date is equal to our secured stored data
date = date[username][1]
#check of the given password + date is equal to what is stored on the database
#password
if salt(password, date) == date[username][0]:
print"Welcome %s!" % username
else:
print "Incorrect password"
else:
print "user %s not found, please register!" % username
elif choice == 2:
username = raw_input("Please enter yout username: !")
password = raw_input("Please enter your password: !")
#if username exists in the system already then the name is taken
if data.has_key(username):
print "user %s already registered, please put in another" % username
else:
#in order words data = {username: hash, date}
data[username] = [salt(password, getData()), getData()]
easyDump(data)
print "user %s successfully registered!" % username
elif choice == 3:
print "goodbye!"
break
else:
print "invalid input or commands"
Indenting in Python is very important, getting it wrong can completely change the meaning of the code.

Related

Failing to print value

I'm new to python, an I decided to write a simple password manager to learn. I'm having trouble retrieving one of the values out of the dictionary.
The function add_password write a key with 2 values (user, and password (encrypted))
And the function get_password read the key and supposed to get the values.
I can't get it to pull the value of user.
I have tried multiple methods, but so far no luck.
https://github.com/ae3erdion/Password_Manager/blob/main/main.py
import base64
import os
import string
import random
from unittest import TestCase
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
characters = list(string.ascii_letters + string.digits + "!##$%^&*()")
site = ""
user = ""
password = ""
password_file = {}
encrypted = ""
# Generate key for encryption
def generate_key():
password = input ("Enter password: ")
password = bytes(password, 'utf-8')
salt = b'\xceN\x01s\xabE\x15\x02\xd9pz(1\t\xbc4'
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=salt,
iterations=390000,
)
global key
key = base64.urlsafe_b64encode(kdf.derive(password))
# Check for the encryption key hash file exists and validate if the key is the same
if os.path.exists('password.hash'):
with open('password.hash', 'rb') as f:
key_validation = f.read()
if key_validation == key:
print("What would you like to do: ")
menu()
else:
print("Wrong password ")
exit
# If key hash file doesnt exist it create the file and write the encryption key hash to it
else:
with open('password.hash', 'wb') as f:
f.write(key)
with open('password.encode', 'wb') as f:
print("What would you like to do: ")
menu()
# Randon password generator
def generate_password():
length = int(16)
random.shuffle(characters)
random_password = []
for i in range(length):
random_password.append(random.choice(characters))
random.shuffle(random_password)
random_password = ("".join(random_password))
print(random_password)
# Write a new password to the pasword file
def add_password(site, user, password_site):
password_file[site] = password_site
with open('password.encode', 'a+') as f:
encrypted = Fernet(key).encrypt(password_site.encode())
f.write(site + " " + user + ":" + encrypted.decode() + "\n")
# Read password file and get the password
def get_password(site):
with open('password.encode', 'r') as f:
for line in f:
site, encrypted = line. split (":")
password_file[site] = Fernet(key).decrypt(encrypted.encode()).decode()
return password_file[site]
# Check for all files.
def main():
if os.path.exists('password.hash') & os.path.exists('password.encode'):
print ("Welcome Back!")
generate_key()
else:
print ("""
Welcome!
Create password""")
generate_key()
# Menu of options
def menu():
print("""
(1) Generate random password
(2) Add new password
(3) Get login information
(q) Quit""")
done = False
while not done:
choice = input("Enter choice: ")
if choice == "1":
generate_password()
elif choice == "2":
site = input("Enter the site: ")
user = input("Enter User: ")
password = input("Enter the password: ")
add_password(site, user, password)
elif choice == "3":
site = input("Enter site: ")
print(f"Your login information for {site} is ({get_password(site)})")
elif choice == "q":
done = True
print("Bye!")
else:
print("Invalid Choice")
if __name__== "__main__":
main()
If you change you get_password function to:
def get_password(site):
with open('password.encode', 'r') as f:
for line in f:
site, encrypted = line.split (":")
site, user = site.split()
password_file[site] = (user, Fernet(key).decrypt(encrypted.encode()).decode())
return password_file[site]
and change option 3 in your menu function
elif choice == "3":
site = input("Enter site: ")
user, passwd = get_password(site)
print(f"Your login information for {user}#{site} is ({passwd})")
You will still want to implement some error checking but that should will at least get you started.

python json keeps appending same key and value

import json
def write_json(data, file='users.json'):
with open(file, 'w') as f:
json.dump(data, f, indent=4)
while True:
user = {'name':[], 'password':[]}
choice = int(input('1) Register, 2) Login\n>> '))
if choice == 1:
username = input('Enter username: ')
password = input('Enter password: ')
user['name'] = username
user['password'] = password
print('Registered successfully')
with open('users.json') as json_file:
data = json.load(json_file)
users = data['users']
for user in users:
if user['name'] == username:
print(f'User "{username}" already exists')
break
new_user = user
users.append(new_user)
write_json(data)
if choice == 2:
username = input('Enter username: ')
password = input('Enter password: ')
with open('users.json', 'r') as f:
data = json.load(f)
for user in data['users']:
if user['name'] == username and user['password'] == password:
print('Logged in succesfully')
I am trying to make a simple login/register system, but when the user registers for the 2nd time, its gets overridden by the 1st key/value every time, I tried user.clear() but it doesnt seem to have an effect
The issue is that you are using a single dict item for all your users. The way you've set it up only allows for one user to exist.
You need to restructure your dict. You could do a list of dict items, but I would suggest using the username as the key in your dict. Since usernames are supposed to be unique, this makes sense IMHO.
In case you want to use the simpler list of dict items metioned above, you would structure it as follows:
[
{'Edo': 'mypassword'},
{'Iso': 'yourpassword'}
]
I've added some comments on the adjusted code below...
import json
def write_json(data, file="users.json"):
with open(file, "w") as outfile:
json.dump(data, outfile, indent=4)
def load_json(file="users.json"):
# try block in case file doesn't exist
try:
with open(file) as infile:
result = json.load(infile)
return result
except Exception as e:
# just printing out the error
print(e)
# should only be file not found error
# returning an empty dict
return {}
while True:
# you need to load before actually doing anything.
# if you don't you might overwrite the file
userlist = load_json()
# newlines for each option
choice = int(input("1) Register\n2) Login\n>> "))
if choice == 1:
username = input("Enter username: ")
# check if user already exists before requesting password
# since usernames are supposed to be unique, you can just
# create a dict with the key being username.
# you could use the value directly for password, but
# if you need to store more values for a user, I advice
# you use another dict as the value.
if username in userlist:
print(f"User {username} already exists")
# do some other magic here to handle this scenario
# continue makes the while loop go to the next iteration
continue
password = input("Enter password: ")
userlist[username] = {"password": password, "someotheruserdate": "dunno?"}
write_json(userlist)
# only print the success **after** you've actually
# completed all relevant logic.
print("Registered successfully")
# change this to elif instead of a second if statement
elif choice == 2:
username = input("Enter username: ")
password = input("Enter password: ")
if username in userlist and userlist[username]["password"] == password:
print("Logged in succesfully")
else:
# handle wrong username/password
# here you need to check after getting both username&password
print("Incorrect username/password combination")

How to append to csv file before script is done running?

I am currently making a log in system which stores usernames and passwords in a text file.
This is my code:
import csv
Brugere = open("D:\Filer\Programmering/Profiles.txt","r+",newline="\n")
writer = csv.writer(Brugere, delimiter=",")
print("Welcome to the chat app!")
Brugernavn = "" //means username
Kodeord = "" // means password
def Signup(j,k):
print("Welcome to sign up!\n Please enter your Username")
j = input("")
if j not in Brugere:
print("Hello, " + j + ", please enter a password:")
k = input("")
line1 = [j,k]
writer.writerow(line1)
print("Great! Now you can sign in")
Signin(Brugernavn, Kodeord)
else:
print("Username already taken! try again")
Signup(Brugernavn, Kodeord)
def Signin(U,P):
print("Welcome to sign in!")
print("Do you already have an account?[y/n]")
ans = input("")
if ans == "n":
print("You will now be redirected to sign up")
Signup(Brugernavn, Kodeord)
elif ans == "y":
U = input("Username: ")
if U in Brugere:
P = input("Password: ")
print("WELCOME")
else:
print("Invalid username, try again")
Signin(Brugernavn, Kodeord)
else:
print("Please write 'y' or 'n'")
Signin(Brugernavn, Kodeord)
Signin(Brugernavn, Kodeord)
Brugere.close()
When I run it, the signup function works as it should, but when the signin function is called, it can't find the username and password from the text file. I think it's because they only get appended after the script is done running. However, 'Im not sure.
I've been struggling for a long time with this csv file thing. I want to have it like
this where each line is a list where I can find the username and password
I've heard people calling it "comma seperated values", however I have no idea how to do it.
TL;DR:
I suspect the simplest solution is:
...
if j not in brugere:
...
writer.writerow(line1)
brugere.flush() # Flush pending changes to file.
...
...
However, I've noticed a few things worthy of consideration:
Python help. You can get help on Python things within an interactive Python session:
python
> import csv
> help(csv)
CSV for this sort of usecase isn't a good idea. If it's production grade use a proper DB, if you're just playing around locally to get a feel for Python use a dict() and store as JSON. I.e.:
import json
username = "myuser"
password = "password"
filename = "data.json"
# Reads data. Requires file `data.json` to exist, with content `{}`.
with open(filename, "r") as data_stream:
data = json.load(data_stream)
if username in data:
print(f"User {username} exists.")
else:
data[username] = password # You'd usually hash and salt a password. It's a separate topic.
# Writes data to disk.
with open(filename, "w") as data_stream:
data_stream.write(json.dumps(data, indent=2)) # Makes it look pretty on disk.
Note that open() returns a stream wrapped in class io.TextIOWrapper (see python -c "import io; help(io.TextIOWrapper)"). It's basically an interface to get the data you want, not the data itself. Try open("test.txt").readlines() to actually read data from stream, for example. Note that streams are consumables.
When you call in on the stream Brugere you're calling the __contains__() dunder method on class io.TextIOWrapper which isn't implemented. But Python being Python it returns False (it's not meaningful).
The CSV interfaces are pretty straightforward:
import csv
filename = "test.txt"
f = open(filename, "w")
writer = csv.writer(f)
writer.write(["myuser", "password"])
# Flushes lines to file.
f.flush()
...
f.close()
Creating a CSV is as simple as writing a string with each value separated by a designated character, often a comma as the name implies. You don't really need the csv library for that.
Your Signup method would then look as follows:
def Signup(j,k):
print("Welcome to sign up!\n Please enter your Username")
j = input("")
if j not in Brugere:
print("Hello, " + j + ", please enter a password:")
k = input("")
line1 = [j,k]
# Write a string with a comma between the values
Brugere.write("{}, {}\n".format(j, k))
print("Great! Now you can sign in")
Signin(Brugernavn, Kodeord)
else:
print("Username already taken! try again")
Signup(Brugernavn, Kodeord)
With that being said, using CSVs to store operational data in a an application does not make all that much sense to me. Please see below for a modified version of signup using SQLite, which is much more robust and still simple to use:
import sqlite3
con = sqlite3.connect('brugere.db')
cur = con.cursor()
# Create a user table with bruger and kodeord
# I added an extra field for when the user was created as well
# which defaults to the date and time the user was created
cur.execute("""create table if not exists brugere
(brugernavn text,
kodeord text,
dato_oprettet TIMESTAMP DEFAULT CURRENT_TIMESTAMP)""")
con.close()
def signup():
con = sqlite3.connect('brugere.db')
cur = con.cursor()
with con:
print("Please enter your Username")
bruger = input()
cur.execute("select brugernavn from brugere where brugernavn =?", [bruger])
bruger_eksisterer = cur.fetchone()
if bruger_eksisterer:
print("Username already taken! Try again")
# Signup(Brugernavn, Kodeord)
else:
print("Hello, " + bruger + ", please enter a password:")
kodeord = input()
try:
cur.execute("insert into brugere (brugernavn, kodeord) values (?, ?)", (bruger, kodeord))
print("Great! Now you can sign in")
except sqlite3.Error as Err:
print("Couldn't add user.\nError: {}".format(Err))
# Signin(Brugernavn, Kodeord)
con.close()
signup()
Modifying the signin should be straighforward, but I'll leave that part up to you.

Python Login and Register System using text files

Hey I am trying to create a system using text files where a user can sign up and log in. All the data will be stored in plain text in a text file called User_Data.txt. My code works but I would like to know if there is anything I missed or If I could improve it in any way. Sorry for the Bad code Formatting in advance.
def choices():
print("Please choose what you would like to do.")
choice = int(input("For Sigining Up Type 1 and For Signing in Type 2: "))
if choice == 1:
return getdetails()
elif choice == 2:
return checkdetails()
else:
raise TypeError
def getdetails():
print("Please Provide")
name = str(input("Name: "))
password = str(input("Password: "))
f = open("User_Data.txt",'r')
info = f.read()
if name in info:
return "Name Unavailable. Please Try Again"
f.close()
f = open("User_Data.txt",'w')
info = info + " " +name + " " + password
f.write(info)
def checkdetails():
print("Please Provide")
name = str(input("Name: "))
password = str(input("Password: "))
f = open("User_Data.txt",'r')
info = f.read()
info = info.split()
if name in info:
index = info.index(name) + 1
usr_password = info[index]
if usr_password == password:
return "Welcome Back, " + name
else:
return "Password entered is wrong"
else:
return "Name not found. Please Sign Up."
print(choices())
There is a lot of improvements You could do.
First of all, split functionality to smaller function.
PASSWORD_FNAME = "User_Data.txt"
def get_existing_users():
with open("r", PASSWORD_FNAME ) as fp:
for line in fp.readlines():
# This expects each line of a file to be (name, pass) seperated by whitespace
username, password = line.split()
yield username, password
def is_authorized(username, password):
return any((user == (username, password) for user in get_existing_users())
def user_exists(username):
return any((usr_name == username) for usr_name, _ in get_existing_users())
# above is equivalent of:
#
# for usr_name, _ in get_existing_users():
# if usr_name == username:
# return True
# return False
def ask_user_credentials():
print("Please Provide")
name = str(input("Name: "))
password = str(input("Password: "))
return name, password
def checkdetails():
name, password = ask_user_credentials()
if is_authorized(name, password):
return "Welcome Back, " + name
if user_exists(name):
return "Password entered is wrong"
return "Name not found. Please Sign Up."
def getdetails():
name, password = ask_user_credentials()
if not user_exists(name):
return "Name Unavailable. Please Try Again"
# Not sure tho what would You like to do here
It's always good to remember to always close your file if you read it.
So if you do something like:
f = open("r", "file.txt") remember to always call f.close() later.
If you use context manager and do it like:
with open("r", "file.txt") as fp:
print(fp.read())
it will automatically close the file for you at the end.
Firstly, fix the spelling error at int(input("For Sigining Up Type 1") Other than that I would add some kind of purpose, for example storing secret numbers or something.
For example you can extend your script with a simple password recovery system.
I think it could be useful to learn...
You can implement a sort of a simple hashing system in order to avoid saving the password as plain text.
If you want to add a GUI, please consider using Tkinter.
https://docs.python.org/3/library/tkinter.html
Let we know.
Good Luck and Keep Coding with <3

Python - how to read through text file for keyword

**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"

Categories