python nested dictionaries to store usernames and passwords - python-2.7

What I'm trying to create is a dictionary that stores hashed usernames and passwords from user input... Now admittedly I don't think I fully understand how nested dictionaries work but here is the code of my function so far:
users = {}
def addUser():
print """"
########
Add user
########
"""
while True:
username = hashlib.sha512(raw_input("Enter username: ")).hexdigest()
passwd = hashlib.sha512(raw_input("Enter password: ")).hexdigest()
uid = int(username[:5], 16) % 32
users[username + passwd] = {
'User hash':username,
'Password hash':passwd,
}
print users
cont = raw_input("Press 'X/x' to exit and start the server or ANY other key to continue adding users: ")
if cont in ['X', 'x']:
break
What I want to do is use the uid variable to generate a unique identifier for each user and store it in a nested dictionary that will look something like this:
users = { 'uid': 28 { 'User hash': 'BFCDF3E6CA6CEF45543BFBB57509C92AEC9A39FB', 'Password hash': '9D989E8D27DC9E0EC3389FC855F142C3D40F0C50'},'uid': 10 { 'User hash': '8C4947E96C7C9F770AA386582E32CE7CE1B96E69', 'Password hash': '266F83D202FA3DA4A075CEA751B4B8D6A30DA1A8'}
}

Answered my own question after doing some reading and playing around with the code.
Here's the solved code if anyone else is having a similar issue
import hashlib
users = {}
def addUser()
print """"
########
Add user
########
"""
while True:
username = hashlib.sha512(raw_input("Enter username: ")).hexdigest() #use SHA512 to hash username from raw input
uid = int(username[:5], 16) % 32 #generate uid from hashed username, using math simliar to the chord algorithm but with SHA512 instead of SHA1
passwd = hashlib.sha512(raw_input("Enter password: ")).hexdigest() #use SHA512 to hash password from raw input
users[uid] = { #store username and password in dictionary
'User hash':username,
'Password hash':passwd,
}
print users
cont = raw_input("Press 'X/x' to exit and start the server or ANY other key to continue adding users: ")
if cont in ['X', 'x']:
break
I figured it out by looking at what the print users call actually did and it printed a combination of the two hashes, so replacing users[username + passwd] with users[uid] solved the issue!
Moral of the story: If it doesn't work... Do some research, have a play around & Try harder! ;)

Related

Python Django prevent password reuse

I'm currently trying to prevent users from using their old passwords (configurable, like say last 5 passwords)
I have the following Infos:
User passwort in cleartext from the form during validation (form.cleaned_data['new_password1'])
Their current hashed Password (pwd_before_change)
Their last x passwords also hashed (pws)
Funnily enough my code works for the current password, but not for my old ones:
pwd_before_change = user_to_change.password
....
old_pws = Passwords.objects.filter(username=user_to_change).order_by('-password_changed')[:allowed_reuse].values_list('password', flat=True)
....
if old_pws:
for pws in old_pws:
if check_password(form.cleaned_data['new_password1'], pws) or \
check_password(form.cleaned_data['new_password1'], pwd_before_change)
messages.error(request,
f'You are not allowed a password which was already used in the last '
f'{allowed_reuse + 1} iterations')
return render(request, 'registration/password_change.html', {
'form': form
})
Any ideas what the issue may be? (additional info, I'm using Argon2).
Do I really need to encode the cleartext password again with all possible "salt" in the old passwords and check? (this would make the method depending on the hasher function which would not be ideal + I thought the check passwort function was exactly for scenarios like this?)
Ok, not sure what exactly was the issue, but I split up the "if" and now it works:
logger_user.info("User {} is attempting a password change".format(username))
if form.is_valid():
# Get the allowed Password counter from the settings, reduce by 1 as the current password is also checked!
allowed_reuse = settings.PASSWORD_REUSE - 1
logger_user.info(f"Allowed PWs: {allowed_reuse +1 }")
if check_password(form.cleaned_data['new_password1'], pwd_before_change):
messages.error(request, f'You are not allowed to re-use your current password')
return render(request, 'registration/password_change.html', {
'form': form
})
# Retrieve the last x passwords according to the Password Reuse Setting
old_pws = Passwords.objects.filter(username=user_to_change).order_by('-password_changed')[:allowed_reuse].values_list('password', flat=True)
# Compare the new Passwort with the old passwords
if old_pws:
for pw in old_pws:
if check_password(form.cleaned_data['new_password1'], pw):
messages.error(request,
f'You are not allowed a password which was already used in the last '
f'{allowed_reuse + 1} iterations')
return render(request, 'registration/password_change.html', {
'form': form
})

Python Why can my list only recognize one set of login details?

I tried making a login detail storing program that stores usernames and passwords. I managed to make it work partially where the login manages to recognise the 1st set of login details, however, my login() function cannot seem to recognise the 2nd set of login details that has been appended to the list. Basically, if I append some passwords to the vault list e.g "qwerty", "123456", "2017", it will only accept the 1st password and not the 2nd or 3rd. How do I get the program to accept more login details, not only just one set? Any help would be appreciated.
vault = []
appvault = []
passvault = []
def menu():
mode = input("""Hello {}, below are the modes that you can choose from:\n
##########################################################################
a) Login with username and password
b) Register as a new user
To select a mode, enter the corresponding letter of the mode below
##########################################################################\n
> """).strip()
return mode
def login():
if len(vault) > 0 : #user has to append usernames and passwords before it asks for login details
print("Welcome to the login console")
while True:
username = input ("Enter Username: ")
if username == "":
print("User Name Not entered, try again!")
continue
password = input ("Enter Password: ")
if password == "":
print("Password Not entered, try again!")
continue
try:
for i in vault:
if i[username] == password:
print("Username matches!")
print("Password matches!")
logged() #jumps to logged function and tells the user they are logged on
break
except KeyError: #the except keyerror recognises the existence of the username and password in the list
print("The entered username or password is not found!")
else:
print("You have no usernames and passwords stored!")
def register(): #example where the username is appended. Same applies for the password
print("Please create a username and password into the password vault.\n")
while True:
validname = True
while validname:
username = input("Please enter a username you would like to add to the password vault. NOTE: Your username must be at least 3 characters long: ").strip().lower()
if not username.isalnum():
print("Your username cannot be null, contain spaces or contain symbols \n")
elif len(username) < 3:
print("Your username must be at least 3 characters long \n")
elif len(username) > 30:
print("Your username cannot be over 30 characters \n")
else:
validname = False
validpass = True
while validpass:
password = input("Please enter a password you would like to add to the password vault. NOTE: Your password must be at least 8 characters long: ").strip().lower()
if not password.isalnum():
print("Your password cannot be null, contain spaces or contain symbols \n")
elif len(password) < 8:
print("Your password must be at least 8 characters long \n")
elif len(password) > 20:
print("Your password cannot be over 20 characters long \n")
else:
validpass = False #The validpass has to be True to stay in the function, otherwise if it is false, it will execute another action, in this case the password is appended.
vault.append({username:password})
validinput = True
while validinput:
exit = input("\nEnter 'end' to exit or any key to continue to add more username and passwords:\n> ")
if exit in ["end", "End", "END"]:
break
else:
validinput = False
register()
return register
def logged():
print("----------------------------------------------------------------------\n")
print("You are logged on.")
while True:
chosen_option = menu() #a custom variable is created that puts the menu function into the while loop
if chosen_option in ["a", "A"]:
login()
if chosen_option in ["b", "B"]:
register()
else:
print("""That was not a valid option, please try again:\n """)
You are looping through a list of dicts. Change vault to a dict, and get rid of the for loop:
vault = {}
def login():
if len(vault) > 0 : #user has to append usernames and passwords before it asks for login details
print("Welcome to the login console")
while True:
username = input ("Enter Username: ")
if username == "":
print("User Name Not entered, try again!")
continue
password = input ("Enter Password: ")
if password == "":
print("Password Not entered, try again!")
continue
try:
if vault[username] == password:
print("Username matches!")
print("Password matches!")
logged() #jumps to logged function and tells the user they are logged on
break
except KeyError: #the except keyerror recognises the existence of the username and password in the list
print("The entered username or password is not found!")
else:
print("You have no usernames and passwords stored!")
And you will have to replace the append in register() from
vault.append({username:password})
to
vault[username] = password
On another note, I would suggest not to store the actual passwords, but rather the hashes. Take a look here.

RPCError: dictionary update sequence element #0 has length 1; 2 is required on python

i wanted to insert new data into porstgresql using odooRPc i am having error like below
RPCError: dictionary update sequence element #0 has length 1; 2 is required
my python script code is :
def POST(self):
data = []
web.header('Access-Control-Allow-Origin', '*')
web.header('Access-Control-Allow-Credentials', 'true')
web.header('Content-Type', 'application/json')
auth = web.input()
print("auth")
print(auth)
name=auth['username']
pwd=auth['password']
city=auth['city']
eml=auth['eml']
mobile=auth['phone']
state_id=auth['state']
country_id=auth['country']
# print(type(auth['country']))
# country_id=auth.get('Country').get('id')
# country_id=auth['country'].get('id')
# print(country_id)
# state_id=auth['state']
# print(state_id)
odoo = odoorpc.ODOO('field.holisticbs.com',port=8069)
odoo.login('field.holisticbs.com','info#holisticbs.com','admin')
# Customer = odoo.execute_kw('res.partner','create',{'name':name,' email':eml,'mobile':mobile,' country_id':country_id,'state_id':state_id})
Customer = odoo.execute_kw('res.partner','create',{'name':name,' email':eml,'mobile':mobile})
print(Customer)
# Users = odoo.env['res.partner']
# user = Users.browse([int(idu)])
# print(user)
# Customer = odoo.execute_kw('res.user','create',{'login':eml,' password':pwd})
return json.dumps(Customer)
I have made my comments as below , kindly request you to find it as below it will help in your case:
Well there are many RPC Library (Python) for connecting with the API of Odoo/OpenERP:
xmlrpclib
odoorpc
erppeek
oerplib
openerplib..
In Your case You have chose the odoorpc.
Here is the code snippet for using it odoorpc:
import odoorpc
import json
domain ='localhost' #the domain
port=8069 #the active port
username = 'username' #the user name
password = 'password' #the user password
dbname = 'database_name' #the database
#Validate the credentials
odoo = odoorpc.ODOO(domain, port=port)
odoo.login(dbname, username, password)
#Login User details
user = odoo.env.user
print(user.name) # user name
print(user.company_id.name) # user company name
#Create a partner
user_data = odoo.execute('res.partner', 'create',
{'name':"PRAKASH",'
email':" prakashsharmacs24#gmail.com",
'mobile':"7859884833"})
print(user_data)
But i have also find you are using the method execute_kw so please use xmlrpclib if you want to use method execute_kw
Here is the code snippet for using it xmlrpclib:
import xmlrpclib
domain ='localhost' #the domain
port=8069 #the active port
username = 'username' #the user name
password = 'password' #the user password
dbname = 'database_name' #the database
#Validate the credentials
url='http://{domain}:{port}'.format(domain=domain,port=port)
login_url='{url}/xmlrpc/2/common'.format(url=url)
sock_common = xmlrpclib.ServerProxy(login_url)
uid = sock_common.login(dbname, username, password)
print sock_common.version()
print uid
models = xmlrpclib.ServerProxy('{}/xmlrpc/2/object'.format(url))
#Validate the access rights
print models.execute_kw(dbname, uid, password,
'res.partner', 'check_access_rights',
['read'], {'raise_exception': False})
#Execute the query
print models.execute_kw(dbname, uid, password,
'res.partner', 'search',
[[['is_company', '=', True], ['customer', '=', True]]])
You can also refer this Link for knowing the difference between the RPC library
I hope this will help you ..

Python 2.7.6 telnetlib HardCode Password

I have made a script which is used to run an APP on MACOS
It basically controls camera using and IP address
My problem is it required a password
I am using the http://docs.python.org/2/library/telnetlib.html#telnetlib.Telnet example from here but it is not working
I do not want it to prompt the user for the password, I simply want to HardCode it everytime the app runs.
if ip:
self.conn = telnetlib.Telnet(ip, 24)
self.consume_telnet()
else:
self.conn = None
def telnet_send(self, s):
passCode = '********'
password = getpass.getpass()
if self.conn:
self.conn.write(s + '\r\n')
if password:
self.conn.read_until('Password: ')
self.conn.write(password.strip() + '\n')
else:
print s
Password is prompted by getpass.getpass() call. This method always asks user for the password. Check this doc page: http://docs.python.org/2/library/getpass.html
I am assuming you are doing initialization outside telnet_send method. Simply setup your password inside this initialization code --- something like self.password = getpass.getpass() and then use this password elsewhere.
self.password = getpass.getpass()
def telnet_send(self, s):
passCode = '********'
if self.conn:
self.conn.write(s + '\r\n')
if self.password:
self.conn.read_until('Password: ')
self.conn.write(self.password.strip() + '\n')
else:
print s

Why is it continuing to repeat the while True even though I have broken it?

...
elif error.lower() == 'create':
while True:
try:
username = raw_input('What would you like your username to be? ')
username2 = raw_input('Please enter the same username again: ')
while not pickle.load(open("%s.p"%username, "rb"))[1]:
break
break
else:
pickle.load(open("","rb"))
except IOError:
print 'The username is not available. Please try a different one.'
pword = getpass('What would you like your password to be? ')
pword2 = getpass('Please enter the same password again: ')
while pword != pword2:
print 'The passwords do not match.'
pword = getpass('What would you like your password to be? ')
pword2 = getpass('Please enter the same password again: ')
money_left = 0
isguest = False
print 'Your username is %s, and your password is %s. You have $%d ingame money.' % (username, pword, money_left)
...
When I am trying to create an account in my while True, I am making sure the username is available before registering it. It works and asks me again if the username is not available, but even if it is, it still keeps asking. Can you help me?
The break statement(s) break out of the while not... statement, not the while True loop. I suspect that you meant to write:
if not pickle.load(open("%s.p"%username, "rb"))[1]:
break
The documentation on break is here.
I made some adjustments to your code. See if this works for you:
import os.path
while True:
username = raw_input('What would you like your username to be? ')
if os.path.exists("%s.p" % username):
print 'The username "%s" is not available. Please try a different one.' % (username,)
continue
username2 = raw_input('Please enter the same username again: ')
if username == username2:
break
else:
print "The usernames don't match. Try again."
while True:
pword = raw_input('What would you like your password to be? ')
pword2 = raw_input('Please enter the same password again: ')
if pword == pword2:
break
else:
print 'The passwords do not match. Try again.'
money_left = 0
isguest = False
print 'Your username is %s, and your password is %s. You have $%d ingame money.' % (username, pword, money_left)