Inserting valid email into a table in mysql - python

I want to write code to give username and password from a user and check the format of the email. Email's format is expression(string or number or both)#string.string. If the email's format is correct I must enter this email and password into a table in my database. Could you help me to write the correct code, my code does not work?
import re
import mysql.connector
cnx = mysql.connector.connect(user='root', password='',
host='127.0.0.1',
database='username_password')
cursor = cnx.cursor()
print("Enter email address: ")
email=input()
print("enter password: ")
password=input()
regex = '^[a-z0-9]+[\._]?[a-z0-9]+[#]\w+[.]\w{2,3}$'
def check(email):
if(re.search(regex,email)):
return("Valid Email")
else:
print("Invalid Email")
print("Enter correct format: expression#string.string")
print("Enter email address: ")
email=input()
if __name__ == '__main__' :
check(email)
if check(email)=="Valid Email":
cursor.execute("INSERT INTO _info Values (email,password)")
cnx.commit()

You need to have a method who's job is well defined, for now it can return a string, or input a new email, one option is that the method only return a vlaid email
Also check how to insert in db, you need to pass the values at some point
def get_valid_email():
regex = r'^[a-z0-9]+[\._]?[a-z0-9]+[#]\w+[.]\w{2,3}$'
email = input("Enter email address: ")
while not re.fullmatch(regex, email):
print("Invalid Email")
print("Enter correct format: expression#string.string")
email = input("Enter email address: ")
return email
if __name__ == '__main__':
cnx = mysql.connector.connect(user='root', password='',
host='127.0.0.1',
database='username_password')
cursor = cnx.cursor()
email = get_valid_email()
password = input("enter password: ")
cursor.execute("INSERT INTO _info Values (%s,%s)", (email, password))
cnx.commit()

Related

Python SQlite3 Update No Error But Does Not Updating

It shows no error and is able to run, but the data in the SQLite table doesn't update. However other update function similar to this work
def seller_edit():
while True:
sellername = str(input("Enter your username: "))
with sqlite3.connect(r"C:\Users\User\Desktop\HFSystem\Assginment\HFuserinfo.db") as connect:
cursor = connect.cursor()
check = "SELECT * FROM sellerinfo WHERE Username = ?"
cursor.execute(check,[sellername])
results = cursor.fetchall()
if results:
Phone = int(input("Enter New Phone No.: "))
Email = str(input("Enter New Email: "))
Address = str(input("Enter New Address: "))
updateseller ="""UPDATE sellerinfo SET Phone = ?, Email=?,Address=? WHERE Username=?"""
cursor.execute(updateseller,[sellername,Phone,Email,Address])
connect.commit()
print("Seller Info Edited!")
connect.close()
seller_info_menu()
break
else:
print("ProductID does not recognised")
option = input("Do you want to try again (y/n): ")
if option.lower() == "n":
seller_info_menu()
break
The order of the parameters inside the tuple of the 2nd argument of cursor.execute() must be the same as the order of the ? paceholders:
cursor.execute(updateseller, (Phone, Email, Address, sellername))

How can I compare a value from database to python input

So I am trying to create a login system kinda, normal python terminal. I made a register function but I am struggling with the login one. I am trying to compare my input to the username and password and when I get that done i will add the id's. But how can I do that, I tried everything.
When I run the code and enter the right details, it is telling me "Login failed, wrong username or password", which means that something is wrong with my if statement.
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password=""
)
mycursor = mydb.cursor(buffered=True)
def login():
mycursor.execute("USE logintest")
login_username = input("Please enter your username or email: ")
login_password = input("Please enter your password: ")
check_login = f"SELECT username FROM users WHERE username = '{login_username}'"
check_password = f"SELECT password FROM users WHERE password = '{login_password}'"
mycursor.execute(check_login)
username_result = mycursor.fetchall()
mycursor.execute(check_password)
password_result = mycursor.fetchall()
passwordr = password_result
usernamer = username_result
print(usernamer)
print(passwordr)
if login_password == passwordr and login_username == usernamer:
print("Logged in successfully")
else:
print("Login failed, wrong username or password")
def register():
mycursor.execute("USE logintest")
new_username = input("please pick a username: ")
new_email = input("please enter your email: ")
new_password = input("please pick a password: ")
insert_new_user = "INSERT INTO users (username, email, password) VALUES (%s, %s, %s)"
new_user = (new_username, new_email, new_password)
mycursor.execute(insert_new_user, new_user)
mydb.commit()
print("User successfully created! insert id:", mycursor.lastrowid)
def options():
print("1. login")
print("2. register")
options = input("please pick 1 or 2: ")
if "1" in options:
login()
elif "2" in options:
register()
else:
print("please only select 1 or 2")
options()
options()
Usually when you fetch data from a database in python, it returns a list of the data, and input in python is a string, so in other words, you are comparing a string with a list which will always be false.
you should create a function for verifying the login details. This is how to verify the login details, it should be inside the function:
try:
username = input("your username")
password = input("your password")
conn = (your connection code);
result = conn.execute("SELECT * FROM yourTable WHERE usernameColumnOfYourTable = ? AND passwordColumnOFyourTable = ?", (username, password))
print("connected to database")
if (len(result.fetchall()) > 0):
print("user found")
else:
print("user not found")
except Exception as err:
print("couldn't connect")
print("General error :: ", err)
Note: ? is the parameter marker for pyodbc module, if you're using mysql connector, replace the ? sign with %s
But if you're using a hashed (salted) password, the format will be a bit different.
Applying this logic to your codes:
def login():
connection = (establish your database connection here)
login_username = input("Please enter your username or email: ")
login_password = input("Please enter your password: ")
result = connection.execute("SELECT username FROM users WHERE username = ? AND password = ?",(login_username, login_password) )"
if (len(result.fetchall()) > 0):
print("Logged in successfully")
else:
print("Login failed, wrong username or password")

Login with python using database

Im trying to make the user log in whereas if they type the correct username and password they will be able to do so but I keep getting an error when I enter the login details
def login(self):
global con
if self.txt_user.get() == "" or self.txt_pass.get() == "":
messagebox.showerror("Error", "Please fill up all fields!")
else:
try :
con=pymysql.connect(host="localhost",user="root",password="",database="employee")
cur=con.cursor()
cur.execute("select * from employeelist where username=%s",self.txt_user.get())
row=cur.rowcount
print(row)
if row != None :
cur.execute("select password from employeelist where username=%s", self.txt_pass.get())
row1 = cur.rowcount
print(row1)
if(row1 != None):
messagebox.showinfo("Success", "Login Successful", parent=self.root)
m = menu
m.Menu(root)
else:
messagebox.showerror("Error", "Wrong Password. Please try again!")
else:
messagebox.showerror("Error, Wrong Username or Password. Please try again!")
except Exception as ex:
con.close()
messagebox.showerror("Error",f"Error due to: {str(ex)}",parent=self.root)
There are following issues:
rowcount will be a number, never be None, so if row != None will be always True
used self.txt_pass.get() in SELECT ... WHERE username=%s is incorrect, should use self.txt_user.get() instead
Under security consideration, normally we don't tell the user whether username or password is incorrect. That will expose user information to hackers under brute force attack. Just tell them either successful or failed is enough. Also do not store plain text password in database. Password should be encrypted.
Also you can use single SELECT to check the credentials:
def login(self):
user = self.txt_user.get().strip()
passwd = self.txt_pass.get().strip()
if user == "" or passwd == "":
messagebox.showerror("Error", "Please fill up all fields!")
else:
try :
con = pymysql.connect(host="localhost", user="root", password="", database="employee")
cur = con.cursor()
cur.execute("SELECT 1 from employeelist WHERE username = %s and password = %s", (user, passwd))
if cur.rowcount == 1:
messagebox.showinfo("Success", "Login Successful", parent=self.root)
else:
messagebox.showerror("Error", "Invalid credentials. Please try again!")
except Exception as ex:
messagebox.showerror("Error", f"Error due to: {str(ex)}", parent=self.root)
finally:
con.close()
cur.execute(
"select password from employeelist where username=%s",
self.txt_pass.get()
)
You are using password (i.e. self.txt_pass.get()) to find username, so it wont find any records hence you're getting error all the time.ez fix
You can also use the callproc option.
import pymysql
try:
conn = pymysql.Connect(
host='localhost',
user='root',
passwd = '',
db='testing'
#,autocommit=True
)
#pymysql.cursors.DictCursor
cur = conn.cursor()
params = ('official',1)
cur.callproc('getlogindetails',args=params)
# cur.execute("call getlogindetails(?,?)", params)
ls = list(cur.fetchall())
#your logic here based on the list value
finally:
conn.close()
Procedure:
DELIMITER $$
DROP PROCEDURE IF EXISTS `testing`.`getlogindetails` $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `getlogindetails`(in inusername
varchar(100),in inloginid integer)
BEGIN
select fname,id,lname from details where id < 10;
END $$
DELIMITER ;

How do I store user data on an external file to login? (Very basic plz, don't want to use SQL, hashing etc...)

I want to make a login system with a username and password for each user. How do I save their data when they login? I don't know how to do it using .csv and don't wanna get into any of that SQL business as this is for a school project and I have a very limited deadline.
Here is a snippet from my code:
import getpass
#Function to add new users, still don't know how I'll save it. grrrrr!
def signUp()
print("\nTo make a new account you must create your own unique username and password\n\n***\n\n")
while True:
newUsername = str(input("Enter your username:\n"))
newPassword = getpass.getpass(prompt = "Enter your password: ", stream = None)
passConfirm = getpass.getpass(prompt = "Confirm your password: ", stream = None)
if passConfirm == newPassword:
print("\n Great! Your data has been confirmed and will now be saved to the database. To play the game restart the program then login.")
#Here the user data should be saved some way that makes sure it is not deleted and can be retrieved when restarting program
else:
print("Please re-enter your credentials.")
If you have 0 security concern you could just store the data as json file.
Everything is explained there if you want to use json.
Create a dictionary and store it in a file like this:
import json
credentials = {"username1": "password1", "username2": "password2"} #and so on
with open('data.json', 'w') as fp:
json.dump(credentials, fp)
Then to open this file and extract the dictionary use:
with open('data.json', 'r') as fp:
credentials = json.load(fp)
And you can access any password using a username like this:
password = credentials[username]
json is a built-in library so no compatibility issue and probably correct for your teacher.
I programmed it with ALL the security because you shall do thing right from the start.
Here the code:
import getpass
import hashlib
import sqlite3
import os
# init new db
try:
os.mkdir("./saves")
except FileExistsError: pass
con = sqlite3.connect('saves/db.sqlite')
cur = con.cursor()
try:
cur.execute('''CREATE TABLE auth
(username text, password text, salt text)''')
except: pass
con.commit()
con.close()
# static Password Salt: appendet to each password before hashing, from os.urandom(64)
static_passwd_salt = b'%\x89\x08-\x82\xb9\xdf\x07\xbd\xbb\x88]\xa2q\x08\x90\xfb\x97\xa7R\xd5\xfc\xfda\x8b\xdd\xcb\x1c\x00\x84\x0e\xdc\xc4\xc0|1\x02-\xb0y\xff`0!gn\xa7\xdf)=\xba.w\x9f\x0b\x9a\xe6n\x9c\xa6\xc5S\xa0\xa0'
# return user or not found
def Query_user(user):
con = sqlite3.connect('saves/db.sqlite')
cur = con.cursor()
db = [i for i in cur.execute("SELECT * FROM auth")]
dbpasswd_hash = None
for i in range(len(db)):
if db[i][0] == user:
return db[i]
return "nf"
# Initialising peppers against bruteforce attacks
peppers = []
for i in range(256):
peppers.append(chr(i))
# generate a random pepper for new user
def rand_pepper():
bits = bin(ord(os.urandom(1))).replace("0b", "")
while len(bits) <= 7:
bits += "0"
return peppers[int(bits, 2)]
# Check password of user
def check_passwd(user, raw_passwd):
uq = Query_user(user)
if uq == "nf":
return "nf"
dbpasswd_hash = uq[1]
usersalt = uq[2]
for i in peppers:
passwd = raw_passwd + i
if hashlib.scrypt(password=passwd.encode("UTF-8"), salt=static_passwd_salt+usersalt, n=16, r=16, p=16).hex() == dbpasswd_hash:
return True
return False
#Function to add new users
def signUp():
print("\nTo make a new account you must create your own unique username and password\n\n***\n\n")
cont = True
while cont:
newUsername = str(input("Enter your username:\n"))
newPassword = getpass.getpass(prompt = "Enter your password: ", stream = None)
passConfirm = getpass.getpass(prompt = "Confirm your password: ", stream = None)
if passConfirm == newPassword:
print("\n Great! Your data has been confirmed and will now be saved to the database. To play the game restart the program then login.")
con = sqlite3.connect('saves/db.sqlite')
otsalt = os.urandom(63)
passwd = newPassword + rand_pepper()
cur = con.cursor()
if Query_user(newUsername) == "nf":
cur.execute("INSERT INTO auth VALUES (:user, :passwd, :salt)", {"user":newUsername, "passwd":hashlib.scrypt(password=passwd.encode("UTF-8"), salt=static_passwd_salt + otsalt, n=16, r=16, p=16).hex(), "salt":otsalt})
else:
print("User already exists")
con.commit()
con.close()
cont = False
else:
print("Please re-enter your credentials.")
# log the user in
def LogIn():
Username = str(input("Username:\n\n"))
if Query_user(Username) == "nf":
print("That User doesn't exist")
else:
Password = getpass.getpass(prompt = "Enter your password: ", stream = None)
if check_passwd(Username, Password) == True:
print("You're logged in")
else:
print("Incorrect Password")
#signUp()
#LogIn()
Or WITHOUT any security (use at own risk):
import getpass
import sqlite3
import os
# init new db
try:
os.mkdir("./saves")
except FileExistsError: pass
con = sqlite3.connect('saves/db.sqlite')
cur = con.cursor()
try:
cur.execute('''CREATE TABLE auth
(username text, password text)''')
except: pass
con.commit()
con.close()
def Query_user(user):
con = sqlite3.connect('saves/db.sqlite')
cur = con.cursor()
db = [i for i in cur.execute("SELECT * FROM auth")]
for i in range(len(db)):
if db[i][0] == user:
return db[i]
return "nf"
def check_passwd(user, raw_passwd):
uq = Query_user(user)
if uq == "nf":
return "nf"
passwd = uq[1]
if raw_passwd == passwd:
return True
return False
#Function to add new users
def signUp():
print("\nTo make a new account you must create your own unique username and password\n\n***\n\n")
cont = True
while cont:
newUsername = str(input("Enter your username:\n"))
newPassword = getpass.getpass(prompt = "Enter your password: ", stream = None)
passConfirm = getpass.getpass(prompt = "Confirm your password: ", stream = None)
if passConfirm == newPassword:
print("\n Great! Your data has been confirmed and will now be saved to the database. To play the game restart the program then login.")
con = sqlite3.connect('saves/db.sqlite')
cur = con.cursor()
if Query_user(newUsername) == "nf":
cur.execute("INSERT INTO auth VALUES (:user, :passwd)", {"user":newUsername, "passwd":newPassword})
else:
print("User already exists")
con.commit()
con.close()
cont = False
else:
print("Please re-enter your credentials.")
# log the user in
def LogIn():
Username = str(input("Username:\n\n"))
if Query_user(Username) == "nf":
print("That User doesn't exist")
else:
Password = getpass.getpass(prompt = "Enter your password: ", stream = None)
if check_passwd(Username, Password) == True:
print("You're logged in")
else:
print("Incorrect Password")
#signUp()
#LogIn()
And SQL isn't that bad is it?

How do I use the text from my database to authenticate as usernames and passwords?

My userpass.txt is like this:
gabiel,bab
sabiel,pont
mabiel,blont
instead of using bonjovi as username, and isagod as password, how do I use the left column of the text file associated with the words on the right column of the text file to access? It's such basic code because I'm 15 and in school.
import time
import sqlite3
conn = sqlite3.connect("UserPass.db")
cursor = conn.cursor()
print("*"*50)
print("Authentication Database")
print("*"*50)
cursor.execute("""
CREATE TABLE tblUserPass
(
usernames TEXT,
passwords TEXT,
primary key (usernames)
)"""
)
print("tblUserPass created in UserPass.db")
def readTextFile(userFile):
numRecs = 0
userDBRec = []
userTextRec = userFile.readline()
while userTextRec != "":
numRecs += 1
field = userTextRec.split(",")
usernames = field[0]
passwords = field[1]
print(usernames, passwords)
userDBRec.append(usernames)
userDBRec.append(passwords)
cursor.execute ("insert into tblUserPass VALUES (?,?)", userDBRec)
conn.commit()
userDBRec = []
userTextRec = userFile.readline()
return numRecs
userFile = open("UserPass.txt", "r")
numRecs = readTextFile(userFile)
print("\n",numRecs, "records transferred")
userFile.close()
for rows in cursor.execute('SELECT * FROM tblUserPass'):
print(rows[1])
username=input("enter user")
password=input("enter pass")
while username!='bonjovi' or password!='isagod':
print("one of 'em incorrect")
time.sleep(1)
print("go again")
username=input("ENTER USER AGAIN")
password=input("ENTER PASS AGIAN")
print("hento and welcom")
First you should never store password as clear text in your database, hash it then store it.
This is actually a simple db query,
username=input("enter user")
password=input("enter pass")
while cursor.execute(f"SELECT * FROM tblUserPass where usernames='{username}' AND passwords='{password}'").fetchone() is None:
print("one of 'em incorrect")
time.sleep(1)
print("go again")
username=input("ENTER USER AGAIN")
password=input("ENTER PASS AGIAN")
print("hento and welcom")
the query is to search for the row which matches both username and password.
Finally, welcome to SO and bravo taking the initiative to write things from scratch.
EDIT
Prior of this, this is a small problem when you initialize your database, when you do userTextRec = userFile.readline() there is actually a newline character at the end, therefore all your password (except for the last line) is suffixed with \n. To remove it, do field = userTextRec.split('\n')[0].split(",").

Categories

Resources