Hello I'm trying to create a web registration form with the flask module. What is the easiest way/module to check if a username contains a certain amount of characters, has numbers, and uppercase letters and how do I loop a form input until a valid username in this case is entered?
#app.route('/register', methods=['POST', 'GET'])
def register():
if request.method == "POST":
username = request.form["username"]
password = request.form["password"]
error = None
if not username:
error = "Username is required."
elif not password:
error = "Password is required."
flash(error)
if error is None:
with open('data.txt', 'a', encoding='utf8') as file:
encoded_password = password.encode()
hash_password = hashlib.sha256(encoded_password).hexdigest()
file.write(username + ' ' + hash_password + '\n')
return redirect(url_for("login"))
return render_template('register.html')
call another function like this (just an example only worrying about the username) and expand the logic as you see fit - determine if they should stay on the registration page based on whether process_registration is True
def verify_user_registration_credentials(username, password):
if not username:
flash_message = "Please enter a username"
process_registration = False
elif len(username) <= 5:
flash_message = "Please enter a username greater than 5 characters"
process_registration = False
else:
for character in username:
if character.isdigit() or character.isupper():
break
process_registration = True # assuming you want them to have either a number or an upper case letter in their username
Related
In my password manager prroject, I am trying to code a login function.
In this functtion, if the user's username and password match an account stored in this dictionary, it allows access to their object which has the following attributes: username, password, password_coll.
(The password_coll is a dictionary/collection of the users passwords as values to the website of use as keys).
So as a little stem from my original question, how would I also reference my
This is my first time using OOP approach and it is really frying my brain hahaha.
So I thought of using usernames as keys and the object as the value. But how do I structure this in code?
Any examples would be greatly appreciated.
I did try checking existing questions but they didn't answer my question closely enough. So here we are haha:)
The code block at the bottom is my attempt at testing the output of those methods to see if they return the data in the object. But the result was this message:
"<bound method User.return_pass of <main.User object at 0x0000023419597940>>"
import random
import secrets
import string
class User:
def __init__(self, username, password, password_dict=None) -> None:
self.username = username
self.password = password
self.password_dict = {}
def return_pass(self, password):
return self.password
def __str__(self, password) -> str:
return self.password
def get_creds(self, username, password):
usern = input('Enter username: ')
pwd = input('Enter password: ')
self.username = usern
self.password = pwd
def passGen(self, password_dict): # random password generator
n = int(input('Define password length. Longer passwords are safer.'))
source = string.ascii_letters + string.digits
password = ''.join((secrets.choice(source)) for i in range(n))
print('Password has been generated!')
print('Would you like to save this password? Type y or n: ')
yon = input()
if yon == 'y':
site = input('Please enter the site password is to be used:')
self.password_dict[site] = password
return self.password_dict
u1 = User('dave', 'pass', {})
user_logins = {'dave': u1}
print(user_logins['dave'].return_pass)
User.return_pass is a function, it has to be called:
print(user_logins['dave'].return_pass("password")) where the text "password" is the arg required in the function.
Hope this helps
def login(username, password, user_logins):
if username in user_logins:
user = user_logins[username]
if user.password == password:
return user.password_dict
else:
return "Incorrect password"
else:
return "Username not found"
print(login('dave', 'pass', user_logins))
In your code, you're trying to print the output of a function, but you forgot to actually run the function by adding parentheses at the end. So instead of just printing the function, you need to run it by adding () at the end. Also, the str method in the User class should not take any input, and it should return the value of self.password instead of just 'password'
print(user_logins['dave'].return_pass())
I am geting an error when trying to check a password using the bcrypt library. The issue seems to be that the hashed variable should be a plain string without "quotation marks". I've attempted to remove the quotation marks multiple times but the error persists. I am seeking assistance in removing the quotation marks from the "hashed" variable in order to make the bcrypt checkpw function work properly.
#----------------------------------------------------------------
#----------------------------------------------------------------
# import module to dencrypt password
#----------------------------------------------------------------
#----------------------------------------------------------------
import bcrypt
def Log_in():
# Print separator line
print("-"*70)
# Prompt user for email or username and password
msg0 = "Enter your username or your email address"
msg1 = "Enter your password"
user_input = input(f"{msg0:45}| ")
user_pasword = input(f"{msg1:45}| ")
print("-"*70)
# Open and read the text file where the user database is stored
db = open("database.txt",'r')
contant = db.readlines()
email_list = []
username_list = []
password_list=[]
# Check if there's content in the database
if contant == None:
pass
else:
# Split each line of the content by '| ' and append the parts to their corresponding lists
for i in contant:
a, b, c, d = i.split("| ")
email_list.append(a.strip())
username_list.append(b.strip())
password_list.append(d.strip())
# Close the file
db.close()
# Check if the entered email or username exists in the email_list or username_list
if user_input in username_list or user_input in email_list:
x = None
y = None
# Try to get the index of the entered email or username in the email_list and username_list
try:
x = username_list.index(user_input)
except:
pass
try:
y = email_list.index(user_input)
except:
pass
if x != None and y == None:
# If the entered username exists in the username_list
# Strip the 'b' character, encode the string to utf-8 and compare it with the entered password
hashed = password_list[x].strip('b')
# hashed = hashed.replace("'","")
hashed = hashed.encode('utf-8')
if bcrypt.checkpw(user_pasword.encode('utf-8'), hashed):
print("Welcome")
else:
print("incorrect password")
Log_in()
elif y != None or x == None:
# If the entered email exists in the email_list
# Remove the double quotes and compare it with the entered password
hashed = password_list[y][:-1]
hashed = hashed.replace('"','')
# hashed1 = hashed.replace(b"\n", b"")
if bcrypt.checkpw((user_pasword.encode("utf-8")),hashed): #error happening here
print("Welcome")
else:
print("incorrect password")
Log_in()
else:
print("incorrect password")
Log_in()
else:
# If the entered email or username doesn't exist in the email_list or username_list
print("This username or the email does not exist")
Log_in()
# main function
if __name__ == "__main__":
Log_in()
import re
from getpass import getpass
#Using Regex for more security for user
username_regex = re.compile(r'^[A-Za-z0-9]{4,10}$')
password_regex = re.compile(r"^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$")
#check if password is valid with regex
def validate_password(password: str) -> bool:
if re.fullmatch(password_regex, password):
return True
else:
return False
#store the password to the text file
def store_username_password() -> bool:
"""function to store the username and password"""
username = input("Enter the username: ")
password = input("Enter the password: ")
if not username_regex.search(username):
print("Invalid username")
return False
if not validate_password(password):
print("Invalid password")
return False
with open('username_password.txt', 'w') as f:
f.write(f'Username: {username}\n')
f.write(f'Password: {password}\n')
print("Succesfully registered! ")
return True
# test the function
print(store_username_password())
i dont know how to im a beginner oops im trying to do login page i cant understand how to load data .
So i'm trying to make a login and register program in Python i already made the register part, but now i'm struggling with the login part.
and a self made simple database, using classes to store the data.
there are two files:
one for database and register and login program and the register and login program reads database.
This is the current login code:
username = input("Enter your username: ")
if username == "(acc_info." + username + ".username)":
print("Valid username")
But it didn't work of course
and acc.info is the data base
This is the database
class Accounts:
def __init__(self, username, pw, is_admin):
self.username = username
self.pw = pw
self.is_admin = is_admin
def full_info(self):
return '{} {} {}'.format(self.username, self.pw, self.is_admin)
admin = Accounts('admin', '5555', True)
I was expecting the input called username gets a username like admin and when i press enter it runs (acc_info.admin.username) and the output would be admin and if the input is same as the output it would send me to the next part which is passwords but if i know how to do the username i can do the password part too.
but now the output is (acc.info.admin.username)
and the program checks if the input (which is admin) is the same as (acc.info.admin.username). and it doesnt work because the output (acc.info.admin.username) should run and give me a output of admin
The check if username == "(acc_info." + username + ".username)" is never going to pass. This is asking if the string entered by the user is the same string you get when you concatenate "(acc_info.", what the user entered, and ".username)". So if the user types in "bob" for example, it compares the strings "bob" and "(acc_info.bob.username)". Those two strings are obviously different.
It's not entirely clear to me how your "database" and "(acc_info ..." is supposed to fit into what you're trying to do. But here's a working example of doing some login and checks:
class Accounts:
def __init__(self, username, pw, is_admin):
self.username = username
self.pw = pw
self.is_admin = is_admin
def full_info(self):
return '{} {} {}'.format(self.username, self.pw, self.is_admin)
def __eq__(self, other):
return (self.username == other.username and self.pw == other.pw)
def check_account(entered, account_list):
for account in account_list:
if entered == account:
return account
return False
accounts = [ Accounts('admin', '5555', True),
Accounts('bob', '1234', False),
Accounts('jill', '4321', False),
Accounts('hacker', '123', False)]
entered_username = input("Enter your username: ")
entered_password = input("and your password: ")
entered_account = Accounts(entered_username, entered_password, None)
matched_account = check_account(entered_account, accounts)
if matched_account:
print("Welcome, %s" % matched_account.username)
if matched_account.is_admin:
print("And I see you're an actual admin! Wow!")
else:
print("Invalid username/password.")
Granted, this isn't the complete sort of approach I'd use in real life (e.g., some of these steps are not only insecure but not the most memory-efficient). But again, it's at least something that seems to fit what you're asking for.
So I'm back working on old project and I cant find whats wrong.
This is the part where the password is first time created, this is from the main script:
def first():
if os.path.isfile("secret.txt"):
folder()
else:
os.system("echo > secret.txt")
password = getpass.getpass("Set your password please --> ")
while len(password) < 4:
print("Password must have more then 4 characters!")
else:
password1 = getpass.getpass("repeat your password please --> ")
while password1 != password:
print("Password don't match")
password1 = getpass.getpass("repeat your password please --> ")
if password1 == password:
a = open('secret.txt', 'w').close()
f = open('secret.txt', 'w')
hashed_password = pbkdf2_sha256.hash(password)
f.write(hashed_password)
os.system("attrib +h secret.txt")
folder()
This is the login script and from here is password checked:
def log_in():
f = open("secret.txt", "r")
Password = f.read()
x = 0
while x < 5:
getPass = getpass.getpass("Password:")
if not pbkdf2_sha256.verify("getPass", Password):
print("Password is invalid")
x = x + 1
else:
f.close()
os.system('cls')
print("Welcome back sir\n")
x = 10
time.sleep(2)
if x == 5:
print("acces denied")
time.sleep(5)
os.system("nothing.bat")
So the problem is when I try to verify the password it says its not correct but the password is the same. In doc it says:
Note that since each call generates a new salt, the contents of the resulting hash will differ between calls (despite using the same password as input):
If this is the problem at .verify() then what should I do?
I'm not sure if this is enough info, if not I will post whole source code
I am probably missing some stupid thing but I just cant seem to find it..
I think the problem is:
if not pbkdf2_sha256.verify("getPass", Password):
Change it to:
if not pbkdf2_sha256.verify(getPass, Password):
You have called a str "getPass" not the password that user input.