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.'
Related
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")
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 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
I am creating a login system that asks a user for a username and password when registering. I used a function for checking to see if the username was valid, then to see if the password was valid according to the requirements.(username could not already be in use and must contain letters)(password must contain capitals, lower-case and numbers). the username function works perfectly, but for some reason in the password function I receive the error: AttributeError: 'builtin_function_or_method' object has no attribute 'isdigit' Does anyone know what I am doing differently between the two functions that makes one functional and the other not. Thanks.
def Username(user_name):
user_names = open('Username list.txt', 'r+')
uname_list = user_names.readlines()
char_user = [user_name]
for i in range(len(uname_list)):
uname_list[i] = uname_list[i].strip('\n')
for i in range(len(uname_list)):
if uname_list[i] == user_name:
return 'username already taken'
for i in range(len(char_user)):
if char_user[i].isspace() == True:
return 'username cannot contain spaces'
if user_name.isdigit() == True:
return 'username must contain letters'
elif len(user_name) < 4 or len(user_name) > 12:
return 'username must be between 4 and 12 characters'
else:
user_names.write(str(user_name + '\n'))
file.close(user_names)
return True
def Password(password, p2):
passwords = open('Password list.txt', 'r+')
if password != p2:
return 'you did not enter the same password twice'
elif password.isdigit() == True:
return 'username must contain letters'
elif password.islower() == True:
return 'username must contain a capital letter'
elif password.isupper() == True:
return 'username must contain a lower case letter'
elif password.isalpha() == True:
return 'username must contain a number'
elif len(user_name) < 4 or len(user_name) > 12:
return 'username must be between 4 and 12 characters'
else:
passwords.write(str(password + '\n'))
return True
print 'What would you like your username to be?'
print 'Your username must be between 4 and 12 characters, contain letters and not contain any spaces'
user_name = raw_input()
valid = Username(user_name)
while valid != True:
print valid
user_name = raw_input()
valid = Username(user_name)
print 'enter your password twice below for validication'
password = raw_input()
password2 = raw_input()
valid = Password(password,password2)
while valid != True:
print valid
print 'enter your password twice below'
password = raw_input
password2 = raw_input
valid = Password(password,password2)
What happens when program is run.
'''What would you like your username to be?
Your username must be between 4 and 12 characters, contain letters and not contain any spaces
Test
enter your password twice below for validication
Your password must include capital letters, lowercase letters, numbers and be betweeen 4 and 12 characters
testing
testing
username must contain a capital letter
enter your password twice below
AttributeError: 'builtin_function_or_method' object has no attribute 'isdigit'''
You only reverence raw_input but don't call it in the last two lines.
Your Password-check is buggy. All Lower + digit or All upper + digit are valid passwords.
When you call a function, you need parentheses () around it:
>>> password = raw_input
>>> password.isdigit()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'builtin_function_or_method' object has no attribute 'isdigit'
>>> password = raw_input()
67
>>> password.isdigit()
True
>>>
Here is your updated code:
def Username(user_name):
user_names = open('Username list.txt', 'r+')
uname_list = user_names.readlines()
char_user = [user_name]
for i in range(len(uname_list)):
uname_list[i] = uname_list[i].strip('\n')
for i in range(len(uname_list)):
if uname_list[i] == user_name:
return 'username already taken'
for i in range(len(char_user)):
if char_user[i].isspace() == True:
return 'username cannot contain spaces'
if user_name.isdigit() == True:
return 'username must contain letters'
elif len(user_name) < 4 or len(user_name) > 12:
return 'username must be between 4 and 12 characters'
else:
user_names.write(str(user_name + '\n'))
file.close(user_names)
return True
def Password(password, p2):
passwords = open('Password list.txt', 'r+')
if password != p2:
return 'you did not enter the same password twice'
elif password.isdigit() == True:
return 'username must contain letters'
elif password.islower() == True:
return 'username must contain a capital letter'
elif password.isupper() == True:
return 'username must contain a lower case letter'
elif password.isalpha() == True:
return 'username must contain a number'
elif len(user_name) < 4 or len(user_name) > 12:
return 'username must be between 4 and 12 characters'
else:
passwords.write(str(password + '\n'))
return True
print 'What would you like your username to be?'
print 'Your username must be between 4 and 12 characters, contain letters and not contain any spaces'
user_name = raw_input()
valid = Username(user_name)
while valid != True:
print valid
user_name = raw_input()
valid = Username(user_name)
print 'enter your password twice below for validication'
password = raw_input()
password2 = raw_input()
valid = Password(password,password2)
while valid != True:
print valid
print 'enter your password twice below'
password = raw_input()
password2 = raw_input()
valid = Password(password,password2)
In the middle of your file you correctly call raw_input(), but you forget at the end. Simple python mistake, almost as common as using == instead of = or the other way around :)