Can you tell me the input so that the check statement is passed along with the try..except of the input pin
#!/usr/bin/python
# Secure Pin system
import sys
users = {'admin': '<REDACTED>'}
def register(username, password):
if username in users:
return "User already exits."
users[username] = password
return "Registered Successfully."
def login(username, password):
if username not in users:
return "Wrong pin/password"
if password != users[username]:
return "Wrong pin/password"
if username == "admin":
return "The FLAG is what you entered in the \"Pin\" field to get here!"
return "You must login as admin to get the flag"
def handle_command(command):
if command not in ["REG", "LOGIN"]:
return "Invalid Command!"
print "Username:",
sys.stdout.flush()
username = raw_input()
try:
print "Pin ([0-9]+):",
sys.stdout.flush()
password = input() # we only support numbers in password
except:
return "Please enter a valid password. Pin can only contain digits."
if command == 'REG':
return register(username, password)
if command == 'LOGIN':
return login(username, password)
if __name__=="__main__":
print "Hey welcome to the admin panel"
print "Commands: REG, LOGIN"
try:
print ">",
sys.stdout.flush()
command = raw_input()
print handle_command(command)
sys.stdout.flush()
except:
pass
The code is all right but the only thing is to bypass the input check
There is a bug that is to be identified
If you want to check whether the input from user only has numbers, then you can use the method - str.isnumeric() , to check whether the string only contains numbers.
Example -
>>> "123".isnumeric()
True
>>> "123.21".isnumeric()
False
>>> "abcd".isnumeric()
False
You can do this check instead of a try/except block (since you do not really use the password as a number after this block).
To ensure the user enters a number, you could convert the script to use a function as follows:
def get_input_number(prompt):
while True:
try:
user_num = int(raw_input(prompt))
return user_num
except ValueError:
print "Please enter a valid password. Pin can only contain digits."
password = get_input_number("Pin ([0-9]+): ")
This would then keep prompting until a number is entered.
Related
Loging in with jack works fine but I cant login with jake even thought he exists in the array. It just skips the whole for loop "for i in storedusername". An help would be grateful.
Here's the code:
import pygame
import sys
import random
storedusername = ["jack","jack","jack","jake","jack","jack","jack",] # The place where the username is stored
storedpass = ["abcde","abcde","abcde","12345","abcde","abcde","abcde",] # The current place where the password is stored
Login = False
def login(): # Function used to login
global Login # Global the logins fucntion
Login = False # Sets Login to false
user = input("Enter Username: ") # User enters the username that they would like to login with
print(user)
for i in storedusername: # Loops through the items in the list
if i == user: # Compares the items in the list with the username that the user has entered
print("user found") # If the user was found then the program will tell the user that
pos = int(storedusername.index(user)) # Finds the position where the username is stored
print(pos)
for j in range(0,10): # Has 10 tries to do this loop
password = input("Enter Password: ") # The user enters the password which they think matches with the username.
#for i in range(0,10):
if password == storedpass[pos]: # Goes to the position where the password matches the username is stored and compares the values.
print("password match username") # Program returns if the username and password match
Login = True # Turns login to True
return Login # Returnes Login
break
else:
print("Pasword does not match try again") # If the password does not match then the program will notify it.
print("too many attempts close the program") # If there are too many attempts than it will close.
else:
print("not found") # If the username is not found than it will be promted that it is not found.
return Login # Returns login.
login()
You are using the variable i both for outer and inner loop, so it is changed inside.
It must be:
for i in ... :
...
for j in ... :
...
You were right to think that the indentation wasn't correct. As you had it before, if you entered a username not present in the list, you would still be asked for the password ten times for each user in storedusername (a total of 70 times!). Moving the block from for i in range(0,10) one indentation further fixes it.
for i in storedusername: ############ It skips this loop
if i == user:
print("user found")
pos = int(storedusername.index(user))
print(pos) ########### All the way up to here
# >>>> indent here
for i in range(0,10): # Has 10 tries to do this loop
password = input("Enter Password: ") # The user enters the password which they think matches with the username.
#for i in range(0,10):
if password == storedpass[pos]: # Goes to the position where the password matches the username is stored and compares the values.
print("password match username") # Program returns if the username and password match
Login = True # Turns login to True
return Login # Returnes Login
break
else:
print("Pasword does not match try again") # If the password does not match then the program will notify it.
# >>>>>
print("too many attempts close the program") # If there are too many attempts than it will close.
else:
print("not found") # If the username is not found than it will be promted that it is not found.
You may see that not working because of wrong indentation of that
else:
print(
"Pasword does not match try again") # If the password does not match then the program will notify it.
print(
"too many attempts close the program") # If there are too many attempts than it will close.
block.
Please move it to to left, and it should be better.
That modified version
storedusername = ["jack", "jack", "jack", "jake", "jack", "jack",
"jack", ] # The place where the username is stored
storedpass = ["abcde", "abcde", "abcde", "12345", "abcde", "abcde",
"abcde", ] # The current place where the password is stored
(width, height) = (644, 412)
Login = False
def login(): # Function used to login
global Login # Global the logins fucntion
Login = False # Sets Login to false
user = input(
"Enter Username: ") # User enters the username that they would like to login with
print(user)
for i in storedusername: ############ It skips this loop
if i == user:
print("user found")
pos = int(storedusername.index(user))
print(pos) ########### All the way up to here
for i in range(0, 10): # Has 10 tries to do this loop
password = input(
"Enter Password: ") # The user enters the password which they think matches with the username.
# for i in range(0,10):
if password == storedpass[
pos]: # Goes to the position where the password matches the username is stored and compares the values.
print(
"password match username") # Program returns if the username and password match
Login = True # Turns login to True
return Login # Returnes Login
break
# --> wrong indentation
else:
print(
"Pasword does not match try again") # If the password does not match then the program will notify it.
print(
"too many attempts close the program") # If there are too many attempts than it will close.
# <-- wrong indentation
else:
print(
"not found") # If the username is not found than it will be promted that it is not found.
return Login # Returns login.
# register()
login()
allows for
Enter Username: jack
jack
user found
0
Enter Password: abde
Pasword does not match try again
Enter Password: abcde
password match username
Process finished with exit code 0
I'm not going to modify the flow of your solution, but I'd suggest to write comments before the line, not in it. Also you should avoid variables shadowing (using the same variable like i in different scopes). The last thing is that you got slightly wrong indent for password checking - it was run even wihtout matched name. I allowed myself to propose version with all these modifiactions. Please take a look on that:
def login():
""" Function used to login"""
# Global the logins fucntion
global Login
Login = False
# User enters the username that they would like to login with
user = input("Enter Username: ")
print(user)
for stored_user_name in stored_user_names:
if stored_user_name == user:
print("user found")
pos = int(stored_user_names.index(user))
# Has 10 tries to do this loop
for try_attempt in range(0, 10):
# The user enters the password which they think matches with the username.
password = input("Enter Password: ")
# Goes to the position where the password matches the username is stored and compares the values.
if password == storedpasswords[pos]:
# Program returns if the username and password match
print("password match username")
Login = True # Turns login to True
return Login # Returnss Login
else:
# If the password does not match then the program will notify it.
print("Password does not match try again")
# If there are too many attempts than it will close.
print("too many attempts close the program")
else:
# If the username is not found than it will be promted that it is not found.
print("not found")
return Login
This is a login system where the user types in their details and then this code verifies if the user exists
counter = 0
def validation():
global counter
print("Sorry, this username or password does not exist please try again")
counter += 1
if counter == 3:
print("----------------------------------------------------")
print("You have been locked out please restart to try again")
sys.exit()
def verify_login(username, password, login_data):
for line in login_data:
if ("username: " + username + " password: " + password) == line.strip():
return True
return False
check_failed = True
while check_failed:
with open("accountfile.txt","r") as username_finder:
print("Could player 1 enter their username and password")
username1=input("Please enter your username ")
password1=input("Please enter your password ")
if verify_login(username1, password1, username_finder):
print("you are logged in")
Right now the code looks in the text file for this format:
username: (username) password: (password)
But now I want to add a hash code for every user so the format in the file looks like this:
49ad2322f9a401e9e3c4ae7694b6b1f1 username: (username) password: (password)
How would I change the verfiy_login to make it look for a random 32
characters at the beginning of every user?
Instead of reconstructing the line using "username: " + username + " password: " + password then comparing it to the line from the text file, you can parse it by first splitting the string then unpacking the tokens. By splitting the line, you get access to the hash, username, and password individually as variables.
def verify_login(username, password, login_data):
for line in login_data:
hsh, _, username_from_file, _, password_from_file = line.strip().split()
if len(hsh) == 32 and username == username_from_file and password == password_from_file:
return True
return False
Unpacking a token into _ is a convention saying that "we will dump this value".
I need to make a program where I once input username and password, It will verify the input by asking for my username and password again and making me repeat it if it doesn't match. I am stuck on the code below and have no idea how to fix it. Help!
import time
complete = False
user = [["username",""],["password",""]]
def Access():
for n in range (len(user)):
user[n][1] = input(user[n][0])
while not complete:
Access()
username = input("What is the username?")
password = input("What is the password?")
if username == user[n][0]:
print("Good!")
else:
print("Input username again!")
if password == user[n][1]:
print("User has been identified, Welcome",username)
else:
print("Input password again")
Your user isn't stored in the best way possible, try using a dict instead. You can try something like this instead: (fixed some mistakes and made improvements )
# I believe this is what you're trying to do
complete = False
user = {"some username" : "some password", "more username" : "more password"}
while not complete:
username = input("What is the username?")
password = input("What is the password?")
conf_username = input("Repeat the username?")
conf_password = input("Repeat the password?")
# since in your question you said you wanted to ask the user to repeat
if username != conf_username or password != conf_password:
print("username or password does not match") # print a message if different inputs
continue # restarts
if not username in user: # check to see if user does not exists
print("Input username again!")
continue
if password == user[username]: # check to see if password match
print("User has been identified, Welcome",username)
complete = True
else:
print("Input password again")
n is only defined in the Access() function, in your while loop, the program won't know what n is.
in the while section, try if username == user[0][0] and if password == user[1][1]
The code should be like this,n is not defined in while loop:
if username == user[0][0]:
print("Good!")
else:
print("Input username again!")
if password == user[1][1]:
print("User has been identified, Welcome", username)
complete = True
By the way,I suggest you use dictionary structure:
user_pass = {}
while True:
user = input("Your name")
pwd = input("Your password")
if user in user_pass and pwd == user_pass[user]:
print("Welcome", user)
break
else:
user_pass[user]=pwd
print("registration completed,please login")
You are in an infinite while loop because complete is never set to true. Futher you want to match the user name and then password. I made it so you can have a database with names and passwords and compare it with the new input. You can of course also use it with just one username and password. Hope it gives some ideas.
import time
complete = False
user = [["username","password"],["username2","password2"]]
while not complete:
username = input("What is the username?")
password = input("What is the password?")
for n in len(user):
if username == user[n][0]:
print("Good!")
if password == user[n][1]:
print("User has been identified, Welcome",username)
complete = True
else:
break
print("Input password again")
if not complete:
print("Input username again!")
https://github.com/soumilshah1995/UserName-and-Password-Validation-Python
#!/usr/bin/env python3
__author__ = "Soumil Nitin Shah"
__copyright__ = "Copyright 2007, The Cogent Project"
__credits__ = ["Rob Knight"]
__license__ = "GPL"
__version__ = "1.0.1"
__maintainer__ = "Soumilshah"
__email__ = "soushah#my.bridgeport.edu"
__status__ = "Testing"
from flask_bcrypt import Bcrypt
class Authentication(object):
def __init__(self, username = ''):
self.username = username
def __lower(self):
lower = any(c.islower() for c in self.username)
return lower
def __upper(self):
upper = any(c.isupper() for c in self.username)
return upper
def __digit(self):
digit = any(c.isdigit() for c in self.username)
return digit
def validate(self):
lower = self.__lower()
upper = self.__upper()
digit = self.__digit()
length = len(self.username)
report = lower and upper and digit and length >= 6
if report:
print("Username passed all checks ")
return True
elif not lower:
print("You didnt use Lower case letter")
return False
elif not upper:
print("You didnt userUpper case letter")
return False
elif length <6:
print("username should Atleast have 6 character")
return False
elif not digit:
print("You didnt use Digit")
return False
else:
pass
enter username = "Youtu1221"
password = "SuperSecret123"
C = Authentication(username=username)
data = C.validate()
bcrypt = Bcrypt()
if (data):
hash = bcrypt.generate_password_hash(username)
print(hash)
else:
pass
check = bcrypt.check_password_hash(hash, "Youtudd1221")
print(check)
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()
If I first enter data that is valid it works fine, but if I enter invalid data, then valid data, None is returned. Here is an example of the problem:
code:
def passwordLength(password):
if (len(password) < 4) or (len(password) > 15):
print("Error from server: Your password must be at least four and at most fifteen characters long.")
enterPasswords()
else:
return True
def passwordMatch(password, password2):
if password != password2:
print("Error from server: Your passwords don't match.")
enterPasswords()
else:
return True
def enterPasswords():
password = input("Message from server: Please enter your desired password: ")
if passwordLength(password):
password2 = input("Message from server: Please re-enter your password: ")
print(password, password2)
if passwordMatch(password, password2):
print(password)
return password
password = enterPasswords()
print(password)
Your problem is that you are not using recursion properly. Take the example of non-matching passwords: hello and hello1.
Your function will be fine until if passwordMatch(password, password2):. At this point, passwordMatch returns None. That is because in passwordMatch you do not say return enterPasswords(), so the return value defaults to None, NOT the return value of the new call to enterPasswords.
if password != password2:
print("Error from server: Your passwords don't match.")
enterPasswords() # Doesn't return anything, so it defaults to None
If you were to use the function like so then you wouldn't have an issue.
def passwordMatch(password, password2):
if password != password2:
print("Error from server: Your passwords don't match.")
return enterPasswords()
else:
return True
Please notice that you have the same problem in passwordLength.
So what happens is that if you first enter invalid data (let's say an invalid password length), you call enterPasswords() again from the passwordLength() function. That prompts you for another password. This time you enter valid input. You get down to where you should return the password, and you return it. The problem is, on the stack, you are returning to where you called enterPasswords() from the passwordLength() function. That is where you are returning the valid password to. It doesn't do anything with it, execution is returned to the original call to enterPasswords() (where the input was invalid) and you're going to return None from there.
A visualization:
enterPasswords() called
prompted for input, give string of length 3
passwordLength(password) called
Invalid string length, print an error and then call enterPasswords()
prompted for input, give valid string
passwordLength(password) called
valid length, return true
prompted for input for second password
passwordMatch(password, password2) called
passwords match, return True
print password
return password to the first passwordLength() call
nothing else to do here, pop the stack and return to the first enterPasswords()
nothing else to do here, pop the stack
print(password), but password is None here