compare input to mysql database - mysql

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

Related

why my else cannoot execute while the statement is else?

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

Qt Checking Login using Database

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

Passing variables through Node MySQL function

I've created a simple function that runs a query and fetches a field value from a MySQL database in Node. I'm using the normal 'mysql' library. For some reason though, I can't pass the resulting field value out to the function. What am I doing wrong?
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'mydb'
});
//This is my function to fetch the field
function getinfofromdb(inputID){
connection.query('SELECT * FROM `mytable` WHERE ? ORDER BY `ID` DESC LIMIT 1;', {identifierID: inputID}, function (err, rows, fields) {
if(rows[0]['filename'].length > 0){
console.log(rows[0]['filename']); // This works fine! I just can't pass it as response. :(
response = rows[0]['filename'];
}else{
response = 'none found';
}
});
return response;
}
//However, I always get that 'response' is undefined
console.log(getinfofromdb(1));
Furthermore, returning from the inner function also yields nothing.
There is no problem with the query, as I can console.log it just fine, but it just doesn't return it to the function.
if(rows[0]['filename']){
console.log(rows[0]['filename']); //This prints out just fine
return rows[0]['filename']; //Doesn't return anything
}
Update: Everything I'm trying is not yielding anything. Would someone please show me the proper way of writing a function in nodejs using the mysql library (https://github.com/mysqljs/mysql) that receives an input, runs a simple query using that input, and the value of a field in the response row? I'm going nuts.
I found the solution -- this is impossible to do.
Coming from a PHP background, not everything I'm used to write is asynchronous.
This Node JS MySQL library runs its queries asynchronously, and therefore the callback function cannot return anything. It just prints stuff such as console.log.
I guess I'm gonna revert to PHP.
How to return value from an asynchronous callback function?

Comparison of strings will not return true, even tough they are identical

I am currently creating a super simple login system for educational purpose only in Processing.
What i am doing in short is comparing the inputs from 2 textfields created with the controllerP5-library, with information from a MySQL database which i am using the BezierSQlib-library to connect to. All of the code is contained in a method inside a class called DbHandler which has all of the code which is related to the database.
But the final if statement where i compare the retrieved password from the database with the password that is inputted by the user will not work. Even though the 2 strings are identical they it will not return true. I´ve tried just putting in " if('1234 == '1234')" and that returned true.
But if i do it like so "if(_rPass == '1234')" with the _rPass being the password from the database, and the password being set to 1234 it still returns false.
void loginCheck(String name, String password){ //This is the method that checks if the login information is correct
String _rPass; //where we store the retrieved password from the database
if(_msql.connect()){ //if there´s connection to the database
println("connection"); //we write out there´s a connection in the prompt
_msql.query("SELECT password FROM users WHERE username='" + name + "'"); //a query is done to find the matching password to the username
_msql.next(); //selects the next row in the retrieved table
if(_msql.getString(1) == null){ //if there´s no user with that username in the user table
println("wrong username"); //the username must be wrong
} //end if
else{ //if something is returned!
_rPass = _msql.getString(1); //the password from the database is stored in _rPass
if(_rPass == password) { //!!!THIS WILL NOT RETURN TRUE NO MATTER WHAT!!!
println("succesfull login!"); //if the strings are the same we´re logged in!
}
else{
println("wrong password");
}
}
}
}
The following code is a part of a "DbHandler" class which controls all of the code that is related to the database, and is being called in another class called "interface" through a method.
The part where the above method is activated is like so:
if(btn_login.isPositionWithinButton(mouseX,mouseY)){ //checks if the login button has been clicked
DbHandler.loginCheck( cp5.get(Textfield.class,"username").getText(), cp5.get(Textfield.class,"password").getText() ); //the loginCheck method is called with the arguments being the text from the textFields
}
Thanks in advance!
Use string. equal method instead of ==.
As == compares the reference so it will return false if reference is not same.
To compare value of string use equal method.
i. e. If (_rpass.equals(password)){}

how to inject sql in login process

I've received an old application which completely lacks user input sanitization and is vulnerable to sql injection. To prove gravity of the situation i need to give client an example and what can be better to scare him than the login process. I've tried standard techniques but the problem with them is that they return multiple rows and due to nature of the code it returns an error instead of logging him in. What sql should i inject so that only a single row is returned and the execution reaches "return $access" line in order to pass the value of this "access" column to code calling this login function. The request is made via POST method and magic quotes are off on the server. Please let me know if you need any other information.
function login($username, $pw)
{
global $dbname, $connection, $sqluser, $sqlpw;
$db = mysql_connect($connection,$sqluser,$sqlpw);
mysql_select_db($dbname);
if(!($dba = mysql_query("select * from users where username = '$username' AND password = '$pw'"))){
printf("%s", sprintf("internal error5 %d:%s\n", mysql_errno(), mysql_error()));
exit();
}
$row = mysql_fetch_array($dba);
$access = $row['access'];
if ($access != ''){
return $access;
} else {
return "error occured";
}
mysql_close ($db);
}
Note: it turns out that magic_quotes_gpc is turned on and the php version is 5.2.17
Thanks
Starting with the goal query:
SELECT *
FROM users
WHERE username = '' OR '1'='1'
AND password = '' OR 1=1 LIMIT 1;#'
We get username is ' OR '1'='1 and password is ' OR 1=1 LIMIT 1;#
It depends what values the login function is called with. If there's sanitation before passing it to the function it might actually be safe. However it's better to filter it right before the query so you can see that your built query is safe.
However if you have something like this:
login($_POST['user'], $_POST['pass']);
In that case just put foo' OR 1=1 OR ' in the user field in the login form :)