I am trying to loop to ask a password until the user enters a valid password then break out of it.
How do I implement this method with a try/except? Is there a better way of doing this? I am a beginning so any help is appreciated!
def is_secure(s):
# This function will check if the passed string s is a valid password
# Return true if string is valid password
# Returns false if string is not a valid password
min_len = 6
max_len = 15
if len(s) < min_len or len(s) > max_len:
return False
else:
return True
while True:
try:
password = str(input("Enter new password:"))
if is_secure(password):
print("Password is secure")
break
except ValueError:
print("False")
else:
print("Password is insecure")
This code should work:
while True:
password = str(input("Enter new password:"))
if is_secure(password):
break
print("Invalid password")
print("Password is secure")
You are trying to handle exceptions that are not thrown anywhere. Another solution would be to throw the exception, instead of printing "invalid password":
raise Exception("Invalid password")
Something like this should hopefully work.
class InsecurePasswordError(Exception):
def __init__(self, message):
super().__init__(message)
class Password:
def __init__(self, pwd: str):
self.pwd = pwd
#property
def pwd(self):
return self._pwd
#pwd.setter
def pwd(self, value):
if len(value) <= 8:
raise InsecurePasswordError('The length of the password is not sufficient!')
elif .....: # Add more conditions
....
else:
self._pwd = value
# And now in your code....
while True:
try:
i = input("Enter new password:")
password = Password(i)
except InsecurePasswordException as e:
print(e)
else:
print("Password is secure")
Related
what i want is if the user enter the email address in a wrong format, it should trigger the except, print the error and head back to try.
x = True
while x==True:
try:
email = (input("Enter Email: "))
if re.fullmatch(regex,email):
x = False
except:
print("Email is inValid. Please type in this format: email#email.com")
the code works fine if you correctly input the email, but when you do it wrong, it will head back to try without triggering the except
Your code does not raise any exception. Just use a good old "if/else" statement instead, as follows:
x = True
while x==True:
email = (input("Enter Email: "))
if re.fullmatch(regex,email):
x = False
else:
print("Email is inValid. Please type in this format: email#email.com")
And it could be a little shorter, as follows:
while True:
email = input("Enter Email: ")
if re.fullmatch(regex, email):
break
print("Email is inValid. Please type in this format: email#email.com")
You can use the assert statement if you prefer the flow of raising and catching an exception:
while True:
try:
email = input("Enter Email: ")
assert re.fullmatch(regex, email)
break
except AssertionError:
print("Email is inValid. Please type in this format: email#email.com")
i'm trying to implement login attempt system to my current code, but i don't know where i should tick it. Can someone suggest anything? I would like to give three attempts to login, if user fails to login, system will lock user out. I just dont know where to position the code properly.
granted = False
def grant():
global granted
granted = True
def login(name,password):
success = False
file = open("user_details.txt","r")
for i in file:
a,b = i.split(",")
b = b.strip()
if(a==name and b==password):
success=True
break
file.close()
if(success):
print("Login Succesful")
grant()
else:
print("wrong username or password")
The better way to do this problem is by having a JSON file instead of a txt file. You can have the file in this format:
{
"username": {
"password": "",
"attempts": 0,
}
}
In the login() function increment and write the count of attempts if the password is wrong.
And before the function begins read the JSON and check if the attempts value is greater than 3. If it is greater send an appropriate message else to continue the login action and ask for the password.
Your code had some minor errors which I have handled here:
import re
granted = False
def grant():
global granted
granted = True
def login(name,password):
success = False
file = open("user_details.txt","r")
for i in file:
if i.count(',') > 0: # check whether i has at least one ','
a,b = i.split(",")
b = b.strip()
if(a==name and b==password):
success=True
break
file.close()
if(success):
print("Login Succesful")
grant()
else:
print("wrong username or password")
def register(name,password):
file = open("user_details.txt","a")
file.write( "\n"+name[0]+","+password) # name is an array so only the first element is stored.
file.close()
grant()
def access(option):
global name
if(option=="login"):
name = input("Enter your name: ")
password = input("enter your password: ")
login(name,password)
else:
print("Enter yor name and password to register")
name = input("Please enter your name: ").lower().split()
if len(name) > 1:
first_letter = name[0][0]
three_letters_surname = name[-1][:3].rjust(3, 'x')
name = '{}{}'.format(first_letter, three_letters_surname)
print(name)
while True:
password = input("Enter a password: ")
if len(password) < 8:
print("Make sure your password is at lest 8 letters")
elif re.search('[0-9]',password) is None:
print("Make sure your password has a number in it")
elif re.search('[A-Z]',password) is None:
print("Make sure your password has a capital letter in it")
else:
print("Your password seems fine")
break
register (name,password)
def begin():
global option
print("Welcome to Main Menu")
option = input("Login or Register (login,reg): ")
if(option!="login" and option!="reg"):
begin()
begin()
access(option)
if(granted):
print("Welcome to main hub")
print("#### Details ###")
print("Username:",name)
I'm working on a mini python project for registering and checking validation of name, mail, username, etc. btw, I used regex for most times. in the name validation function, I don't really know the issue, but its output is:
The output should write that a problem has occurred (don't look at my writing issues :D) and then show what is the actual problem.
This is the code:
import re
def register():
# all registering and checking proccess.
name = input('Name: ')
username = input('Username: ')
password = input('Please select password: ')
mail = input('Mail: ')
mail_check_return = mail_check(mail)
password_check_return = password_check(password)
name_check_return = name_check(name)
if password_check_return == True and name_check_return == True and len(username) > 1 and
mail_check_return == True:
print(f'{name}, you have been registerd sucsessfully!')
else:
print('\na problem has occurred!')
if mail_check_return == False:
print('The entered mail is invalid.')
if password_check_return != True:
print(password_check_return)
if len(username) <= 1:
print('The entered username is invaild.')
register()
return name, username, mail
def menu():
print('Hello! what do you want to do?')
name, username, mail = register()
def match(entered_password, entered_username):
pass
# not finished.
def mail_check(mail_c):
if '#' in mail_c and len(mail_c) > 6:
return True
else:
return False
def password_check(password):
if len(password) >= 6:
if re.search('[0-9]', password):
if re.search('[A-Za-z]', password):
return True
else:
return 'Your password must contain numbers.'
else:
return 'Your password must contain english characters.'
else:
return 'Your password must contain at least 6 characters.'
def name_check(name):
if len(name) <= 2:
if re.search('[0-9]', name):
return 'Your name can\'t contain numbers!'
else:
if re.search('[A-Za-z]', name):
return True
else:
return 'The name is invalid.'
def match(entered_password, entered_username):
pass
def sign_in(username): # 4 lined to un(note). VVV
# not finished.
pass
menu()
Thanks for any help :)
The first judgement for name length should be wrong, and it return None !!!
def name_check(name):
if len(name) <= 2: # <<<------- Here, name should greater than 2, return None
if re.search('[0-9]', name):
return 'Your name can\'t contain numbers!'
else:
if re.search('[A-Za-z]', name):
return True
else:
return 'The name is invalid.'
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 have created a script that uses a function called "authenticateuser", when I enter the wrong user name and password the program correctly works, but when I enter the correct credentials it still returns failed. Tried moving things around but could not find the solution. Are things not in the right place or am I missing some final code?
loggedin = False
wrongcount = 0
def authenticateuser(theusername, thepassword):
theusername = "homerjsimpson"
thepassword = "marge"
def main():
username = ""
password = ""
while loggedin == False and wrongcount < 5:
username = input("Please enter username: ")
password = input("Please enter password: ")
if password == authenticateuser and username == authenticateuser:
loggedin = True
else:
print("Authentication Failed")
wrongcount = wrongcount + 1
loggedin = False
if(loggedin == True):
print("Welcome to the program!")
else:
print("Locked Out")
main()
authenticateuser must do something with the input parameters, and return True if the username/passord match, otherwise it must return False.
We can write it many different ways, e.g. version 1:
def authenticateuser(theusername, thepassword):
if theusername == "homerjsimpson" and thepassword == "marge":
return True
else:
return False
version 2 (better):
def authenticateuser(theusername, thepassword):
return theusername == "homerjsimpson" and thepassword == "marge"
version 3 (even better):
def authenticateuser(theusername, thepassword):
authentication_db = {
# username # password
'homerjsimpson': 'marge',
}
return authentication_db.get(theusername) == thepassword
Usually when we're logging someone in we'll need to keep track of their logged in status. Let's create a simple class (Session for this purpose):
class Session:
def __init__(self, username=None, loggedin=False):
self.username = username
self.loggedin = loggedin
The login function can now ask for username and password, and call authenticateuser to see if they are correct. If they're not correct we increment the wrongcount counter.
In either case we return a Session containing the username and whether the user is logged in:
def login():
loggedin = False
wrongcount = 0
while not loggedin:
username = input("Please enter username: ")
password = input("Please enter password: ")
if authenticateuser(username, password):
return Session(username, True)
wrongcount += 1
if wrongcount > 5:
return Session(username, False)
Now main can call login() and get back a session object. This object can be checked for .loggedin and the appropriate message can be printed. Since we've recorded the username we can also personalize the message:
def main():
session = login()
if session.loggedin:
print("Welcome to the program!", session.username)
else:
print(session.username, "you've been locked out!")
main()
You're checking if the password and username are a function, which obviously they will not be. I believe you actually want authenticateuser to return a dictionary containing theusername and thepassword. Something like this:
def authenticate_user(username, password):
return {"username": username, "password": password}
...
credentials = authenticate_user("homerjsimpson", "marge")
while logged_in == False and wrong_count < 5:
username = input("Please enter username: ")
password = input("Please enter password: ")
if password == credentials["password"] and username == credentials["username"]:
logged_in = True
else:
print("Authentication Failed")
wrong_count = wrong_count + 1
loggedin = False
(as a side note, you should use _ to separate words in variable and function names)
You aren't properly calling authenticateuser. Something like this would do what you intend:
loggedin = False
wrongcount = 0
def authenticateuser(theusername, thepassword):
if theusername == "homerjsimpson" and thepassword == "marge":
return True
else:
return False
def main():
username = ""
password = ""
while loggedin == False and wrongcount < 5:
username = input("Please enter username: ")
password = input("Please enter password: ")
if authenticateuser(username, password):
loggedin = True
else:
print("Authentication Failed")
wrongcount = wrongcount + 1
loggedin = False
if(loggedin == True):
print("Welcome to the program!")
else:
print("Locked Out")
main()
Edit: Also you main call isn't doing anything. python code evaluates line by line so your "main" loop is actually where you do the "while loggedin == False". By the time you call the function main, your program has basically finished everything and the main just sets the username and password to empty string but does nothing further with those values