I want to create a login page script with the username and password as the data account from db. n then when my input is doesn't match the else didn't execute while username and password is did not exist in db. so what should i do to fix this. any somebody help me please
def logindb():
print ("=="*15+"\nPlease insert your username and password.")
username = input ("Username : ")
password = input ("Password : ")
cursor.execute(f"SELECT * FROM data WHERE username='{username}' and password='{password}'")
result = cursor.fetchall()
for i in result:
if (i[0]) == username and (i[1]) == password:
print ("=="*15+"\n\tLogin Success.\n"+"=="*15)
else:
print ("=="*15+"\nUsername or password is wrong.\n"+"=="*15)
In your code snippet, the statement can NEVER be else!
You query for a database entries matching username and password. For every entry (with the matching username and password) you again check if these credentials are correct.
I guess what you want, is to check if there are records found.
Something like this:
result = cursor.fetchall()
if (len(result) > 0):
print ("=="*15+"\n\tLogin Success.\n"+"=="*15)
else:
print ("=="*15+"\nUsername or password is wrong.\n"+"=="*15)
Side note: you really should hash the password instead of saving it as plain text in the database.
Try changing:
cursor.execute(f"SELECT * FROM data WHERE username='{username}' and password='{password}'")
To:
cursor.execute(f"SELECT username, password FROM data WHERE username='{username}' and password='{password}'")
You're selecting ALL* columns, and if your 0 index column is not username, and your 1 index column is not password, your query result will not match up your submitted username and password.
if (i[0]) == username and (i[1]) == password:
It's also not a good idea to run your SELECT statements wide open if you don't need to. Retrieve only the columns explicitly that you need to retrieve.
You should really use a parameterized query.
But if you are going to use this method of data retrieval then I would go one step further then Griv's answer
cursor.execute(f"SELECT userid FROM data WHERE username='{username}' and password='{password}'")
I would never fetch the username or password. Instead, check for its existence by fetching the primary key of the table.
Then check if that value is null or not.
I am not familiar with python, I assume the f"SELECT is not a typo
Related
I am using below groovy code to select a row with a given username and password from mysql db.
For example,
I am searching for below user. Password is stored in db as a SHA1 hashed password.
Name - test7
password - {SHA}01132E914B722741CC3823D0BEACB8364EEAC376
Below is the groovy code which is trying to retrieve the record and failing as I am not able to fetch the record.I suspect the sql query constructed is wrong. SecurityUtil class is just decrypting and returning a plaintext password back as a positional parameter to the query. We are
using the sha1 method of mysql to generate the hash and prefix with string {SHA1} and then trying to retrieve the record.
sql.eachRow("SELECT id FROM users WHERE userName = ? AND password =CONCAT({SHA1},sha1(?))", [username, SecurityUtil.decrypt(password)]) {
authId = String.valueOf(it.id)
}
Welp if SQL doesn't want to play do it in Groovy. Using GStrings you get the same protection as prepared calls so no SQL Injection issues, and you can more easily do groovy operations:
sql.eachRow("SELECT id FROM users WHERE userName = ${userName} and password = ${'{SHA}' + SecurityUtil.decrypt(password)}") {
authId = String.valueOf( it.id )
}
The prepared statement syntax route:
sql.eachRow("SELECT id FROM users WHERE userName = ? and password = ?", [username, "{SHA}${SecurityUtil.descrypt(password)}"]) {
authId = String.valueOf( it.id )
}
sql.eachRow("SELECT id FROM users WHERE userName = ? AND password =CONCAT('{SHA1}',sha1(?))", [username, SecurityUtil.decrypt(password)]) {
authId = String.valueOf(it.id)
}
You may need to put the {SHA} in quotes for use in the concat operator.
I am using qt to create a user login. I am using Sqlite as my database and am stuck for some reason it is not working properly. I was able to corectly bypass the login screen only when typing in the first row from the database. Any other user cannot log in (row 2, 3,4 ... in database). I have been reading all kinds of posts for the past days and have not come to a proper solution. Here is my code. I have also tried creating a query through QSqlQuery and passing it into the QSQlQueryModel Object which did not work at all.
void MainWindow::on_login_clicked()
{
QSqlDatabase m_db;
QString path = "C:/Users/annea/Summer2019Database.db";
m_db = QSqlDatabase::addDatabase("QSQLITE");
m_db.setDatabaseName(path);
m_db.open();
if (!m_db.open())
{
qDebug() << "Error: connection with database fail";
}
else
{
qDebug() << "Database: connection ok";
}
QString username = ui->username->text();
QString password = ui->password->text();
QSqlQueryModel *queryModel = new QSqlQueryModel;
queryModel->setQuery("SELECT * FROM [User Database] WHERE Username= username"); //select the row of where the Username == username
queryModel->query().exec(); //execute it (not really sure why or what this does
if(queryModel->record(0).value(1).toString()== password) //if a row is found check column 2 for password
{
destroy(); //destroy current window
if(queryModel->record(0).value(3).toString()== 1) //if id is equal to one log in as user
{
user.showMaximized();
}
else {
dbManager.showMaximized();
}
}
else {
qWarning("Wrong Password or Username");
}
}
I think your query is wrong. Instead of writing like this:
queryModel->setQuery("SELECT * FROM [User Database] WHERE Username= username"); //select the row of where the Username == username
You might want writing like this:
queryModel->setQuery(QString("SELECT * FROM [User Database] WHERE Username = '%1'").arg(username)); //select the row of where the Username == username
Why? Because you are writing a query, and you probably want to check against the user name entered, not the string "username". Also, don't forget apostrophes when comparing.
In order to find more information which might help with your problem, you should read Qt's documentation regarding its' classes. Also, it would be beneficial to take a look into the SQLite WHERE clause and how strings are represented when writing queries:
https://doc.qt.io/qt-5/qsqlquerymodel.html#setQuery
https://doc.qt.io/qt-5/qsqlquery.html#QSqlQuery-1
http://www.sqlitetutorial.net/sqlite-where/
https://www.sqlite.org/datatype3.html
I'm new to Python and trying to test myself with general code that features things I know or causes me to go searching for answers and solutions as to why what I'm trying to do doesn't work. Unfortunately, I've hit a dead-end in my current attempt.
I got lasered in on the concept of creating a small authorization program inside a single script, and while trying to limit the number of failed log-in attempts the user was allotted, I ran into an issue with the following code:
def attempts(n):
a = n - 1
while a > 0:
result = a
return result
Username = input('Please enter a New Username: ')
Password = input('Please enter a New Password: ')
logu = Username
logp = Password
LoginU = input('Please enter your Username: ')
if LoginU != logu:
while LoginU != logu:
LoginRetry = input('Please try again')
att = attempts(3)
att
print(att)
else:
print('Welcome to the Environment!')
pass
print('Exiting Environment. Have a good day.')
Good practice and ugly code aside, my chief issue lies in getting the (n) to reduce inside the loop with each iterative attempt. As of right now, when I execute the script and intentionally enter the wrong username, it loops
Please try again:
2
Please try again:
2
until I enter the correct username. Under proper operation, I'd like it to spit
Please try again:
2
Please try again:
1
Please try again:
Exiting Environment. Have a good day.
I'd appreciate any and all solutions, or advice people can give.
Here's one approach you can take. A few notes:
Instead of subtracting from a counter, loop over an iterable to count. for loops are genrally easier to think about than while loops. Whenever you want to do something a certain number of times, use a for loop. You can always break out of them if you need to.
The best way to approach breaking your code into functions is to try to make all of the "actions" of your program into their own functions.
import sys
def login(username, password):
username_input = input('Please enter your Username: ')
password_input = input('Please enter your Password: ')
return username == username_input and password == password_input
def login_n_tries(n, username, password):
for i in reversed(range(n)):
if login(username, password):
return True
print(f"You have {i} attempts remaining")
return False
username = input('Please enter a New Username: ')
password = input('Please enter a New Password: ')
if not login_n_tries(3, username, password):
print("Login failed")
sys.exit(1) # End program
... # Rest of program
item = test.query('SELECT userName FROM Database.Users WHERE userName = "user"', function (err,result){
if(err) throw err;
else if('user' == / something correct /){
console.log("TRUE");
}
console.log(result[0]);
});
What I want to do is to check if the user gives a valid username, like you would when logging in to a form of some sort. Now I might have taken the wrong approach but I've tried the following.
I tried to basically check if there is a user with username 'user', which exists in the mysql database. Then I want to simple check that the fixed input 'user' exists by comparing to the result that one gets from querying the DB. However it doesn't seem to work as the console never prints out "TRUE". However when I print out result[0] i get:
{ userName: 'user' }
Which is expected yet I can't manage to retrieve the string 'user'.
The query won't fail if there isn't a record with that username. It will only return an empty result set. Take out all the error stuff and check for number of records. You could also do a SELECT count(*) as recCnt where user = '$usr' and check the value of the returned recCnt variable.
You can try to use results[0].userName in your console.log
$query = $db->prepare("SELECT id FROM users WHERE username = :username AND password = :password");
$query->bindValue(":username", $lName);
$query->bindValue(":password", imu($lPass));
var_dump(imu($lPass));
try {
$query->execute();
$result = $query->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
die($e->getMessage());
}
I'm trying to select the users id, depending on if they entered a valid login. I tried to just use "WHERE username = :username" and that works, it returns the id, but when I add the password part, or only the password check, it returns null. I checked with var_dump as you can see and the password that it's dumping is correct, it exists in the database. The password is hashed with my own encryption system and it returns all kinds of characters. This specific password was: "®Ç+¥J:àhMaÕú¡HW".
I was wondering if there is anyway to get the id with the password check or do I have to edit my hash'er so it returns alphanumeric characters?
if there is anyway to get the id with the password check
yes.
do I have to edit my hash'er so it returns alphanumeric characters?
no.
The only issue with certain characters that can be is their encoding.
Make your password field either [var]binary() or make its collation utf8_bin