How can I compare a value from database to python input - python

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")

Related

Checking Tuples in a list

So i am working on a program that is and I am stuck.
I have a login and signup system that saves new signups in a mysql database.
At the start of the program I take the passwords and names and put them together in a tuple.
Then i put that tuple in a list.
If i wanna login it cant check a tuple in that list.
Here is my code:
Login:
def login():
userKnown = input("Hallo, heeft u al een account? y/n ")
if userKnown == "y":
user = input("username: ")
passw = input("password: ")
userjoin = (user,passw)
if userjoin in bigdata:
print("login succesful")
else:
print("try again")
UploadData:
def uploadData():
print("Bezig met uploaden.")
mycursor.execute("SELECT name, password FROM userData")
data = mycursor.fetchall()
bigdata.append(data)
print("Upload worked. \n")
I hope someone can help me.
A fix to the login system.
I solved it thanks to Georg Richter.
I used the Where function in select and that worked
Here is the code:
def login():
userKnown = input("Hallo, heeft u al een account? y/n ")
if userKnown == "y":
user = input("username: ")
passw = input("password: ")
userB = (user, passw)
query = 'SELECT name, password FROM userData WHERE name =%s'
name = (user,)
mycursor.execute(query, name)
userA = mycursor.fetchone()
print(userA)
if userA == userB:
print("succes")
else:
print("failed")
I think the error is that bigdata does not exist into your login function.
Try this: def login(bigdata) and call the function in this way: login(bigdata)
Try using try block to find the user its easier this way.
try:
pass
#code to search database
except Exception as e:
print(e)
SELECT has a WHERE clause where you can specify user and password to optimize your application.

Inserting valid email into a table in mysql

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()

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?

im trying to add a post to the posts table and allow the user to be able to edit the post. while other users can view the post and like it

I don't know how to add a post to the posts table and allow the user to be able to edit the post. while other users can view the post and like it
import sqlite3, datetime
conn = sqlite3.connect("test.db")
conn.execute('''CREATE TABLE IF NOT EXISTS Users
(username PRIMARY KEY,
name TEXT NOT NULL,
email TEXT NOT NULL,
time DATETIME NOT NULL,
password INT NOT NULL); ''')
conn.execute('''CREATE TABLE IF NOT EXISTS Posts
(username PRIMARY KEY ,
post TEXT NOT NULL,
time DATETIME NOT NULL); ''')
now = datetime.datetime.now()
current = now.strftime("%d-%m-%Y %H:%M:%S")
print(current)
def signUp():
while True:
username = input("Enter a username: ")
if 0 < len(username) < 16:
check = conn.execute("SELECT name FROM Users WHERE username = ?",(username,)).fetchone()
if check == None:
break
else:
print('username taken')
while True:
name = input("Enter your full name: ")
if 0 < len(name) < 16 and ' ' in name:
break
while True:
email = input("enter your email: ")
if '#' in email:
break
while True:
password = input("Enter your password as long as its less than 8 characters: ")
if len(password) < 8:
break
conn.execute("INSERT INTO Users(username,name,email,time,password) VALUES(?,?,?,?,?)" , (username, name, email, current, password))
conn.commit()
print("your details have been saved\n")
details = conn.execute('SELECT * FROM Users WHERE username = ?', (username,)).fetchall()
print('your info:', details)
return username
def signIn():
while True:
usernameInput = input("Enter your username: ")
check = conn.execute("SELECT name FROM Users WHERE username = ?",(usernameInput,)).fetchone()
if check != None:
break
else:
print('no user found by that name')
while True:
passwordInput = input('enter your password: ')
check = conn.execute("SELECT name FROM Users WHERE password = ? AND username = ?",(passwordInput, usernameInput)).fetchone()
if check != None:
break
else:
print('incorrect password')
details = conn.execute("SELECT * FROM Users WHERE username = ?",(usernameInput,)).fetchone()
print('your info:', details)
return usernameInput
def menuOption():
print("Do you want to:\n1)Sign up\n2)Sign in")
while True:
userResponse = input(">>> ")
if userResponse == '1' or userResponse == '2':
break
else:
print('you must choose 1 or 2')
if(userResponse == "1"):
usr = signUp()
elif(userResponse == "2"):
usr = signIn()
wpost(usr)
def get_all():
print('\nall user info:\n')
allusers = conn.execute('SELECT * FROM Users').fetchall()
for i in allusers:
print(i)
def post(username):
while True:
yourpost = input("This is your post, type whatever you want: ")
if len(yourpost) < 300:
conn.execute("INSERT INTO Posts(username,post,time) VALUES(?,?,?)" , (username, post, current))
conn.commit()
allposts = conn.execute('SELECT * FROM Posts').fetchall()
for x in allposts:
print(x)
break
elif len(yourpost) > 300:
print('your post is longer than 300 characters')
break
def wpost(username):
print("Do you want to: \n(Y)create a post\n(N)not")
while True:
userResponse2 = input(">>> ")
if userResponse2 == "Y" or userResponse2 == 'N':
break
else:
print("you must choose Y OR N")
if(userResponse2 == "Y"):
post(username)
if(userResponse2 == "N"):
get_all()
menuOption()
conn.close()
this is the error im currently getting:
Traceback (most recent call last):
File "main.py", line 126, in <module>
menuOption()
File "main.py", line 83, in menuOption
wpost(usr)
File "main.py", line 119, in wpost
post(username)
File "main.py", line 95, in post
conn.execute("INSERT INTO Posts(username,post,time) VALUES(?,?,?)" , (username, post, current))
sqlite3.InterfaceError: Error binding parameter 1 - probably unsupported type.
I don't know how to add a post to the posts table and allow the user to be able to edit the post. while other users can view the post and like it.
You are passing post variable to SQL INSERT statement while post has type function in your code.
You should pass yourpost string instead of post to make your code work.

Categories

Resources