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)
Related
I need help with some code id been writing randomly about a passwor keeper
I'd appreciate it so much if the help is beginner friendly.
I tried searching for some ways to merge dicts and the entire app isn't working.
User_password_dict = {" " : " "}
def merge_lists(username, password):
dict_append = {}
dict_append[username] = password
User_password_dict.update
def user_info_collection():
while True:
username = input (f"What is would you like your'e username to be ?\n\t:")
if username in User_password_dict:
print ("you need to change your'e username")
break
else:
password = input(f"Type a password\n\t:")
password_check = input(f"Type your password again \n\t: ")
if password_check != password:
print("you have not input the correct password")
break
else:
User_info = merge_lists(username, password)
return User_info
user_info_collection()
print(User_password_dict)
Okay, so you made a good effort but overcomplicated the dict part.
The merge_lists function is not needed as appending a dict is much simpler than that !!
The key line of code that i added was this:
user_password_dict[username] = password
and i removed a couple of unnecessary parts.
So, this will work:
user_password_dict = {}
def user_info_collection():
while True:
username = input (f"What is would you like your'e username to be ?\n\t:")
if username in user_password_dict:
print ("you need to change your'e username")
break
else:
password = input(f"Type a password\n\t:")
password_check = input(f"Type your password again \n\t: ")
if password_check != password:
print("you have not input the correct password")
break
else:
user_password_dict[username] = password
return
user_info_collection()
print(user_password_dict)
here is the result:
What is would you like your'e username to be ?
:test
Type a password
:blah
Type your password again
: blah
{'test': 'blah'}
No matter what I do, the code always reverts to the first username or password is incorrect statement. Here is the code:
lines = []
usernames = []
passwords = []
foundU = False
foundP = False
counter = 0
with open("login_project/logins.txt", "r+") as f:
lines = f.readlines()
f.close()
for element in lines:
if counter % 2 == 0:
usernames.append(element.strip())
else:
passwords.append(element.strip())
counter += 1
def Search(lista, val, found):
for i in range(0, len(lista)):
if lista[i] == val:
found = True
else:
pass
return found
def login():
username = input("Please enter your username: ")
password = input("Please enter your password: ")
Search(usernames, username, foundU)
Search(passwords, password, foundP)
if foundU == False or foundP == False:
print("Username or password is incorrect")
elif usernames.index(username) != passwords.index(password):
print("Username or password is incorrect 2")
else:
print("Login succesful")
login()
The error occurs here mainly:
if foundU == False or foundP == False:
print("Username or password is incorrect")
elif usernames.index(username) != passwords.index(password):
print("Username or password is incorrect 2")
else:
print("Login succesful")
Would appreciate any help, only doing this at a GCSE level so I am still quite a begginer.
edit: also in the file is just:
User01
password
User02
password2
Search never changes foundU or foundP. Passing a variable to a function in Python doesn't necessarily mean that if you change the variable in the function, that it will change the original. You just need to do something like foundU = Search(usernames, username). In addition, since foundU and foundP are globals, if you want to change their values globally, you have to declare them as globals:
...
def login():
global foundU
global foundP
username = input("Please enter your username: ")
password = input("Please enter your password: ")
foundU = Search(usernames, username, foundU)
foundP = Search(passwords, password, foundP)
...
However, Search is unnecessary, since Python's in operator does what you want. So you could just do:
foundU = username in usernames
foundP = password in passwords
You have global variables foundU and foundP - these are not being modified inside your function when you call search. Even if they were - your function would simply create a local copy unless you "tell" your code not to.
def login():
global foundU # to modify a global from local scope
global foundP
username = input("Please enter your username: ")
password = input("Please enter your password: ")
# set var using returned val from call to function
foundU = Search(usernames, username, foundU)
foundP = Search(passwords, password, foundP)
If you were to have your login routine return an indicator of login (a bool perhaps) to where it is called, you may be better to remove the global vars and just use two locals.
After posting this, I noticed another problem with using the search function as implemented, and with using the "in" keyword as suggested.. neither will ensure that the username and password match... any username with any password would get authenticated.... so, here is a version that seems to work but it does not need the global vars
lines = []
usernames = []
passwords = []
counter = 0
with open("login_project/logins.txt", "r+") as f:
lines = f.readlines()
f.close()
# ensure there is a password for each user
assert len(usernames) == len(passwords), "Error reading file"
for element in lines:
if counter % 2 == 0:
usernames.append(element.strip())
else:
passwords.append(element.strip())
counter += 1
def validate(u_name, password):
'''Check that user and p/w are at same indices
in each of the lists'''
for i in range(0, len(usernames)):
if usernames[i] == u_name:
if passwords[i] == password:
return True
return False
def login():
username = input("Please enter your username: ")
password = input("Please enter your password: ")
found = validate(username, password)
if found:
print("Login successful")
return True
else:
print("Username or password is incorrect")
return False
login()
A better data structure may be to use a dict for usernames (keys) and passwords(values) and write these to a json file which looks very similar with the caveat that all the data is stored as str.
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 am trying to create a login system. I could make the system without implementing class and just functions. I would like to make each steps into specific methods without writing all into one function.
My question is how to revert back into login asking username and password if the character length is > 5 or wrong password.
If the username and password not in the list how do i revert it back or do i need to code again?
class LoginSystem:
def __init__(self):
self.user_id = input("Please enter your user id: ")
self.user_password = input("Please enter your password: ")
def login(self):
username = self.user_id
password = self.user_password
if len(username) <= 5 and len(password) <= 5:
print("Logging In")
else:
print("Error! Max Length is 5 chars.") #return back to
login system
def check_system(self):
registered_user = {
"test#gmail.com": "test"
}
if self.user_id in registered_user:
print("Successful")
else:
new_user = input("Id not found! Are you are new user?\n [Y]es or [N]o\n")
new_user = new_user.lower()
if new_user == "Y":
return back to login system
elif new_user == "N": #how to return back to main login system
new_username = input("Please enter your user id: ")
new_userpassword = input("Please enter your password: ")
else:
return #back to login system
Your LoginSystem treats the wrong data as its instance attributes. The set of registered users is constant across method calls; the login method itself should be prompting for the user id and password.
class LoginSystem:
def __init__(self):
self.users = {"test#gmail.com": "test"}
def login(self):
while True:
username = input("Please enter your user id: ")
password = input("Please enter your password: ")
if len(username) <= 5 and len(password) <= 5 and self.check_system(username, password):
print("Logging In")
break
else:
# TODO Disallow infinite retries to get it right
print("Error! Max Length is 5 chars.")
def check_system(self, name, password):
try:
expected_password = self.registered_user[name]
except KeyError:
# Or try to add a new user to the system here
return False
if password != expected_password:
return False
return True
A separate method can be added to add a new user to the system where necessary.
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