I want to store userid in a variable after the users logged in and I am not sure how to do that. I used getpass.getuser(), but it gives me the username from my computer system. Does session work in tkinter? Can somebody give me an idea how should I approach this?
The user id is increased automatically for new user
class data:
def checks(name, password):
conn = sqlite3.connect('login.db')
cur = conn.cursor()
if cur.execute('SELECT * FROM user WHERE name = ? AND password = ?', (name, password)):
if cur.fetchone():
window.destroy()
login_backend.back()
else:
messagebox.showinfo('error', 'Username and password is wrong')
def login_student(self):
if len(self.namee.get()) == 0 or len(self.password1e.get()) == 0:
messagebox.showinfo("ERROR", "Mandatory Field is empty")
else:
data.checks(self.namee_text.get(), self.password1e_text.get())
Do you want to get a password and user name on the command line? If so, the secure way to do this is with getpass.getpass(). This will prompt the user. getpass.getuser(), as you discovered, is for the system user.
https://docs.python.org/2/library/getpass.html
You don't want to print the password on the command line because of the security risk. Generally, you want to consume the sensitive credentials only as long as needed to access the resource.
Related
I am writing a small python script as a learning project (very new to writing code) that request a user to input login information and compares it with a connected SQlite database but I cant seem to get the queried password to properly work with the 'if password == pin:' part. I get 'Password Incorrect' even if the correct one has been entered.
If the password is 1234 and I print(pin) I get the correct password but it returns as (1234,). Entering the password as (1234,) doesnt work either.
I have tried to find a resoution but I'm not sure that I am asking the right question. Any guidance would be grealty appreciated.
import sqlite3
#Connects to database and creates object
connection = sqlite3.connect('/path/to/db')
cursor = connection.cursor()
#Selects the password from the dabase that corresponds to the name input.
name = input('Enter your name: ')
cursor.execute("SELECT password FROM users WHERE name = ?",(name,))
pin=cursor.fetchone()
#Compares the user entered password with the selected password from the database and should exit if a match.
while True:
password = input('Enter Your Password: ')
if password == pin:
print('Welcome ' + (name))
break
else:
print('Password Incorrect.')
Thank you aj7amigo and Alberto Hanna! Both solutiuons were needed to fix this.
I needed to change password input to int(input('Enter your password: ') to convert string input to interger.
I also needed to change the comparison to if password == pin[0]: to get just the interger "1234" from the database.
Thanks again!
I am currently working on a database application using Python and SQLite3, alongside Tkinter to create the user interface. The application has a login function, where the user inputs their StaffID and password, and the program authenticates the user by searching a login table for the data input. I am trying to add a type check validation to the StaffID, where it can only be an integer, however, upon running the program, it seems to get stuck in a loop displaying the following output:
I have attached a snippet of the code below:
def UserLogin(self): #Login function for staff members
while True:
try:
staffid = int(self.Entry1.get())
password = self.Entry2.get()
with sqlite3.connect("LeeOpt.db") as db: #Connects to the database file
cursor = db.cursor()
find_user = ('SELECT * FROM Login WHERE StaffID = ? AND Password = ?')
cursor.execute(find_user, [(staffid),(password)])
results = cursor.fetchall()
if results:
for i in results:
self.Access()
MainMenu.create_Toplevel1(root)
self.quit()
else:
tkinter.messagebox.showerror("Error", "The staffID or password is incorrect, please try again.")
time.sleep(1)
return("exit")
break
except:
tkinter.messagebox.showerror("Validation Error","Please enter the correct data type for StaffID")
self.ClearEntries()
I am relatively new to Python, so any help is really appreciated, even if it is just to improve my code in general. Thanks in advance :)
I'm trying to create a login system where I have coded it so that when the user creates a new username and password it stores these into a database.
When the user logs in, I want to be able to check whether the users input matches the data that is in the database and if not, show an error message box. How do I do this?
So far I have made this function that gets all info from the database and an if statement that compares what the user typed in with the info already in the database. I want the user to make as many usernames and passwords and still allow the user to log in.
def login():
data = sqlite3.connect("account.db")
c = data.cursor()
c.execute("SELECT * FROM accounts")
records = c.fetchall()
for record in records:
recorded = record
if recorded != entry_username.get():
message = messagebox.showerror("Error", "Incorrect Username or Password")
elif recorded != entry_password.get():
message = messagebox.showerror("Error", "Incorrect Username or Password")
data.commit()
data.close()
This is what my database looks like:
from tkinter import *
import sqlite3
root = Tk()
root.title("Database")
data = sqlite3.connect("account.db")
c = data.cursor()
c.execute("""CREATE TABLE accounts (
username text,
password text
)""")
data.commit()
data.close()
Thanks for the help
I like to create a secure login with Python but need to check the user table from a database, so that multiple users can log in with their own password.
Mainly like this, works like a charm but not secured of course.
while True:
USER = input("User: ")
PASSWORD = getpass.getpass()
db = sqlite3.connect("test.db")
c = db.cursor()
login = c.execute("SELECT * from LOGIN WHERE USER = ? AND PASSWORD = ?", (USER, PASSWORD))
if (len(login.fetchall()) > 0):
print()
print("Welcome")
break
else:
print("Login Failed")
continue
So then I tried hashing the password, work also of course, but then I can't store it on the database to check, so there is no check at all.
from passlib.hash import sha256_crypt
password = input("Password: ")
hash1 = sha256_crypt.encrypt( password )
hash2 = sha256_crypt.encrypt( password )
print(hash1)
print(hash2)
import getpass
from passlib.hash import sha256_crypt
passwd = getpass.getpass("Please enter the secret password: ")
if sha256_crypt.verify( passwd, hash ):
print("Everything worked!")
else:
print("Try again :(")
I tried like this so that the password hash would be taken from the database but with no success:
USER = input("User: ")
db = sqlite3.connect("test.db")
c = db.cursor()
hash = "SELECT HASH FROM LOGIN WHERE USER = %s"%USER
print(hash)
passwd = getpass.getpass("Password: ")
if sha256_crypt.verify( passwd, hash ):
print("Everything worked!")
else:
print("Try again :(")
So my question is, what is the best way to create a secure login for my program? And I do need different logins for different users as stated in the user table. I did it on MySQL before but for testing purpose I'm now trying on sql3. So that doesn't matter. As long as I know how to approach this.
Really you should avoid doing this yourself at all. There are plenty of libraries that correctly implement this kind of authentication.
Nevertheless, the pattern to follow is like this:
Don't store the plain password in the database at all. When the user account is created, hash the password immediately and store that.
When the user logs in, hash the value they enter for the password, then compare that against the value stored in the database already.
(Note that for decent security, you not only need to use a modern hash algorithm but should also use a salt).
I'm having a problem when trying to verify credentials ( I will post the code below ). I was wondering if it's happening because I stored username and password as a string within the database, should I have stored it as an integer?
The problem: I think it's easier to simply give an example of what the problem is, maybe it's easier to understand.
Information that is correct ( username = something and password = testing )
Example 1: You input "something" as username and "password" as password - that's fine it works, HOWEVER the next example is where things go wrong.
Example 2: You input the username "somethingfpsadadoia" and the password "testing" - the program will say it's correct as long as the password is correct. So as long as you have part of the username under username entry then the password works, but anything after that is not taken in consideration to say it's actually wrong.
Much appreciated if anyone can help !
"""
def Is_Valid():
UsernameValidity=UserName_Entry.get()
PasswordValidity=Password_Entry.get()
cursor.execute('''SELECT password FROM users WHERE username = ?''', (UsernameValidity,))
cursor.execute('''SELECT username FROM users WHERE password = ?''', (PasswordValidity,))
LogInAttempt = cursor.fetchone()
print (Is_Valid) # Testing to see if it works on shell
if LogInAttempt:
print (" One of the accounts have successfully logged in ")
IsValidText.config(text=" You have logged in! ", fg="black", highlightthickness=1)
myGUI.after(1000, CoreContent) # Ignore this one for now.
else:
print (" One of the accounts inputted the wrong credentials! ")
IsValidText.config(text=" Invalid username or Password! ", fg="black", highlightthickness=1)
"""
You are executing two entirely independent queries. The second call to execute throws away any results from the first one; what you fetch from cursor is the result of the second query.
You have to tell the database to check both values when looking at each row:
cursor.execute('SELECT 1 FROM users WHERE username = ? AND password = ?',
[UsernameValidity, PasswordValidity])
LogInAttempt = cursor.fetchone()