Python33 - SQLite3 accounts with authentication - python

I am making a webserver+website with python and I am currently figuring out how to check if your login values are correct. Previously for testing I used the following code:
def checkUser(username, password): #<-- input values go in here
site_usernames = ["admin", "username1", "username2"]
site_passwords = ["admin", "password1", "password2"]
site_couples = {"admin":"admin", "username1":"password1", "username2":"password2"}
not_counter = 0
while True:
if username in site_usernames:
if password in site_passwords:
for key in site_couples:
if (username == key) and (password == site_couples[key]):
print("User %s logged in!" % username)
return True
else:
not_counter = not_counter + 1
if not_counter > 10:
print("User failed login with accountname: %s" % username)
return False
break
else:
continue
else:
pass_exists = False
break
else:
user_exists = False
break
As far as I have seen, You can not return two columns from a database as a dictionary. I have managed to get one column as a list, and I am planning to use that.
So in my new code, I have the following:
A list of usernames that are in the database
A list of encoded passwords in the database
I would like to make an authentication function that checks if:
If the username exists in the database:
If the password exists in the database:
If the input username:password couple exists in all existing username:password values in the database:
return True if all checks succeed
The problem is that I find it very difficult to manage such a thing. As you can see in my example code, I had two lists and a dict, all pre-defined. I would like to create those things on the fly, and the only one I actually need help with is how to create the username:password dictionary couples. How would I do such a thing? zip() makes tuples and not dictionaries.

In [1]: users = ["user1", "user2"]
In [2]: pws = ["password", "12354"]
In [3]: dict(zip(users, pws))
Out[3]: {'user1': 'password', 'user2': '12354'}

Related

Why does one of my login functions work and the other does not, despite the fact that they both have the identical code?

So I am trying a login system for my bank management project and I created two of the login system.
one for the admin system and the other for the customer. This is the code and text file for both. Why would my first function work and not the second? FYI I can't use any global function and dictionary and the error I been getting is ValueError: too many values to unpack (expected 2)
def LAdminAccount():
EnteredStaffAccountNumber = str(input("========== Please Type in Your Account Number:"))
EnteredStaffPassword = str(input("========== Please Type in Your Password:"))
A= open("AdminUser.txt","r")
for line in A.readlines():
us,pw = line.strip().split("|")
if (EnteredStaffAccountNumber == us ) and (EnteredStaffPassword == pw):
print ("Login successful")
A.close()
AdminMenu()
print ("Wrong username/password")
return
def LCustomerAccount():
EnteredID = str(input("========== Please Type in Your Account ID:"))
EnteredPassword = str(input("========== Please Type in Your Password:"))
B= open("Customerlogin.txt","r")
for line in B.readlines():
id,pw = line.split("|",1)
print (id)
print (pw)
if (EnteredID == id ) and (EnteredPassword == pw):
print ("Customer Login successful")
B.close()
CustomerMenu()
print ("Wrong Account Number/password")
menu()
AdminUser.txt
00001|1234
Customerlogin.txt
000403100865|3088
Output is:
000403100865
3088
Customer Login successful
Wrong Account Number/password
The error suggests that the problem is the following line:
id,pw = line.split("|")
If you have more than one "|" in your text your will not be able to split them this way.
To guarantee the string is split at most once try replacing with:
id,pw = line.split("|", 1)

flask - unable to run a variable to a list in for loop to store the sql database

I'm unable to loop through the "query" variable with the items list and push the code to database. but it is throughing an error ""ValueError: not enough values to unpack (expected 2, got 1)"", can someone check the code please?
#app.route('/', methods=['POST'])
def test():
if request.method == 'POST':
try:
query = request.form['url']
r = requests.get(query)
output = r.json()
items = output['result']
# # items = ['abc','bcd','cde','def'] # here items will be in list
for i in items:
user = User(listOfItems=items[i], query=query)
db.session.add(user)
db.session.commit()
responseBody = {'message': items}
return make_response(jsonify(responseBody))
except Exception, e:
return ('Oops!', e.__class__, 'occurred.')
else:
responseBody = {'message': 'failed'}
return make_response(jsonify(responseBody))
desired output in database:
listOfItems query time_stamp
abc example.com -date-
bcd example.com -date-
cde example.com -date-
def example.com -date-
xyz example1.com -datetime.now-
yza example1.com -datetime.now-
zab example1.com -datetime.now-
here,
query1: example.com returns ['abc','bcd','cde','def'] list items
query2: example1.com returns ['xyz','yza','zab'] list items
This part of the code has an issue. for i in items means the value at that index, not the index itself. So the first iteration will return 'abc' and so on.
for i in items:
user = User(listOfItems=items[i], query=query)
db.session.add(user)
db.session.commit()
Assuming that you want to have the values of the list and insert them, change the line to
user = User(listOfItems=i, query=query)
I found some problems:
you do not need the if request.method == 'POST' statement, you've already declared method in the route decorator.
for i in items returns each element from items, the i variable is not an index; so, user = User(listOfItems=items[i], query=query) is incorrect.
I'm not sure these will solve your problem or not; but if not, please show the output of items and output.

How to call and iterate through specific indexes of a dictionary?

I currently have code that prints out a username and their password by means of dictionary. The output is username:abc password:12345. Right now I have them all just printing out at the same time. My main goal is to be able to email these users based on their usernames, but of course I only want to include their username and password information. Not the whole list of information. So basically I want to be able to tell the specific user only their password. For example, I would want to send an email to user abc and that email should only contain their username and password. Then I would like to send an email to user xyz but that should only contain the password of user xyz. Is there a way I can make this happen?
I currently have everything from the dictionary printing. So all the usernames and passwords are being printed out. How can I iterate through these and send an email to each user with their password?
lines = []
User_Pass = {}
#Open output file and show only lines that contain 'Success'
with open("output.txt", "r") as f:
for line in f.readlines():
#Get rid of everything in line after 'Success'
if 'Success' in line:
lines.append(line[:line.find("Success")-1])
for element in lines:
parts = element.strip().split(":")
User_Pass.update({parts[0] : parts[1]})
for key, value in User_pass.items():
print('Username: ' + key + ' Password: ' + value)
I want to be able to email each username and tell them their password. I am really not sure how to go about this. Any help would be appreciated!
Assuming you have the dictionary constructed, you just ask it for the value associated with the key, which is the username:
user_pw = User_Pass.get(username)
this will return None if the username is not in the dictionary.
Suggest you research Python dictionaries for some examples. In your loop code, you have it a little backwards as well. Anytime you want to iterate through a dictionary (the right way) you want to do it with the keys, not the items, so to loop through all in your example:
for key in User_Pass.keys():
print (key, User_Pass.get(key) )
Only fill your User_Pass dictionary when you meet "username" or "password":
for element in lines:
key, value = element.strip().split(":")
if key in {"username", "password"}:
User_Pass.update({key: value})
A simple demonstration:
lines = [
"fullname:John Doe",
"username:jdoe",
"password:S3cRet",
"age:45",
]
User_Pass = {}
for element in lines:
key, value = element.strip().split(":")
if key in {"username", "password"}:
User_Pass.update({key: value})
print(User_Pass)
You get:
{'username': 'jdoe', 'password': 'S3cRet'}
Please, you should follow the naming conventions of the PEP8: "User_Pass" => "user_pass".

Django - checking if instance exists results in internal server error 500

I am trying to check if I have an entry in my database using this code:
def device_update(request):
json_data = json.loads(request.body)
email = json_data['email']
imei = json_data['imei']
sdk_version = json_data['sdk_version']
date = json_data['updateDate']
rule = json_data['ruleName']
group_name = json_data['group']
if Group.objects.filter(group=group_name).exists():
print("group does exists")
else:
print("group doesn't exists")
return HttpResponse("Successful")
However, when the code reaches the if statement to check if the group exists, it returns error 500.
I tried to check with two groups one that exists and another one that doesn't, in both cases I got error 500.
How can I fix this and why is this happening?
The logic for checking if a Group exists, i.e. the line:
if Group.objects.filter(group=group_name).exists()
is not throwing the error here. It is likely that json_data is missing one of the keys you expect it to have, for example, 'group'.
I'd recommend using the get method that dictionaries have. This provides default values when the specified key is not present in the dictionary. You should also have error handling for when the request body is not in valid JSON format.
Here's an example:
def device_update(request):
try:
json_data = json.loads(request.body)
except json.JSONDecodeError:
return HttpResponse('Request body must be in valid JSON format')
email = json_data.get('email', '')
imei = json_data.get('imei', '')
sdk_version = json_data.get('sdk_version', '')
date = json_data.get('updateDate', '')
rule = json_data.get('ruleName', '')
group_name = json_data.get('group', '')
if Group.objects.filter(group=group_name).exists():
print("group does exists")
else:
print("group doesn't exists")
return HttpResponse("Successful")
I set the defaults to the empty string '', but you may want to change that.
Your view doesn't have any error handling. Looking at it quickly, at least two things could go wrong. The request body might not be valid json, and if it is valid json, it might not contain the required keys.
def device_update(request):
try:
json_data = json.loads(request.body)
except ValueError:
return HttpResponse("Invalid json")
try:
email = json_data['email']
imei = json_data['imei']
sdk_version = json_data['sdk_version']
date = json_data['updateDate']
rule = json_data['ruleName']
group_name = json_data['group']
except KeyError as e:
return HttpResponse("Missing Key %s" % e[0])
...
Writing your own validation for a single view like this is ok. As it gets more complicated, you might want to look at django rest framework. It has serializers which will help you manage validation.
Alasdair/Keselme, looks that your view is correct.
Try to put the ipdb into your code in order to debug your code, and than you can print the request.data and see what is comming in the request.

How to test if a dictionary (in an external file) contains the user inputted username (Python3 )?

I am building a Flea Market program. I have an external file hosting all the usernames and passwords of employees. I am trying to test the login section, asking for username then password. It tests if the UN is in the dictionary contained in the readline().
Here is the external file with the usernames and passwords. :
managers = {"manager":"password", "owner":"apple"}
employees = {"jane":"none", "john":"banana"}
And here is the code.:
print("Welcome to Flea Master 2000...\n")
read_employee_file = open('employees_list.txt', 'r')
managers = read_employee_file.readline(0)
employees = read_employee_file.readline(1)
print(managers)
read_employee_file.close()
user_id = input("User ID:\n")
user_password = input('Password:\n')
if user_id in managers[:]:
if managers[user_id] == user_password:
print("Welcome, {0}.".format (user_id))
user_status='manager'
if user_id in employees:
if employees[user_id] == user_password:
print("Welcome, {0}".format (user_id))
user_status = 'staff'
if user_status == 'manager':
action_manager = int(input("Options: (Input number to select...)\n1) Add employee.\n2) Remove employee.\n"))
if action_manager == 1:
employee_addition_type=input("What kind of employee is he/she? ('manager' or 'staff')")
if employee_addition_type == 'manager':
new_manager_username = input("Enter the new manager's username...\n")
new_manager_password = input("Enter the new manager's password...\n")
managers[new_manager_username] = new_manager_password
else:
new_staff_username = input("Enter the new staff member's username...\n")
new_staff_password = input("Enter the new staff member's password...\n")
employees[new_staff_username]=new_staff_password
if action_manager == 2:
print("The list of current employees is: \n")
for key in all_staff:
print(key)
print('\n')
which_remove = input("Now, which do you want to remove? Enter the username exactly.\n")
if which_remove in managers:
del managers[which_remove]
else:
del employees[which_remove]
print("\nDone. Updated roster is:\n")
all_staff = dict(managers, **employees)
for key in all_staff:
print(key
)
Your readline lines are a bit incorrect. The argument to readlines is the maximum number of bytes it will read. So readlines(6) doesn't mean "read the sixth line", it means "read no more than six characters from the current line". I suggest just doing read_employee_file.readline(), with no argument.
managers = read_employee_file.readline()
employees = read_employee_file.readline()
Now you have the full contents of each line, but both variables are still strings. However, you could use the json module to load those dictionaries.
import json
line = 'managers = {"manager":"password", "owner":"apple"}'
#chop off the left part of the string containing "managers = "
line = line.partition(" = ")[2]
d = json.loads(line)
print "the owner's password is", d["owner"]
if "bob" not in d:
print "can't find bob's password in managers dictionary!"
Result:
the owner's password is apple
can't find bob's password in managers dictionary!
There are several ways to read and parse your input file. Assuming your file is the way you specified and you are willing to handle the exceptions, here is one sample method for you. You need to handle exceptions approriately.
try:
#This will read your in.conf which contains user/pwds in the dictionary format you specified.
#Read documentation on exec here:
# https://docs.python.org/3.0/library/functions.html#exec
with open('in.conf') as fh:
for line in fh:
exec(line)
user_id = input("User ID:\n")
user_password = input('Password:\n')
if user_id in managers and user_password == managers[user_id]:
print("Welcome, {0}.".format (user_id))
user_status='manager'
elif user_id in employees and user_password == employees[user_id]:
print("Welcome, {0}.".format (user_id))
user_status='staff'
else:
print "invalid credentials"
except NameError:
#catch situations where your file doesn't contain managers or employees dictionary
#I just raise it so you can see what it would print
raise
except:
#other exceptions as you see appropriate to handle ....
#I just raise it so you can see what it would print
raise

Categories