Difference between where and like in CLEARDB - sql

I'm trying a simple nodejs login system and want to use the following query:
"SELECT * FROM admin_cred WHERE username = '?' AND password = '?'", [username], [password]
But it simply doesn't return anything so I had to do it like this:
'SELECT * from admin_cred where username like "%'+username+'%" AND password like "%'+password+'%"'
This is the code segment:
const result = await database.query(
"SELECT * FROM admin_cred WHERE username = '?' AND password = '?'", [username], [password]
// 'SELECT * from admin_cred where username like "%'+username+'%" AND password like
"%'+password+'%"'
);
Can anyone point out why the first query is not working?
And the difference bertween the two statements?
N.B: This is the first time i'm using cleardb on heroku and a few things seems different from MySql. Everything else in the code works so I've narrowed the problem down
EDIT 1
I just noticed that the second query is running even though the password was wrong
UPDATE 1
Here is the node js code as requested:
class auth {
constructor(app, database) {
this.login(app, database);
}
//http://localhost:8000/api/auth/v1/login
login(app, database) {
app.post("/api/auth/v1/login", async (request, response) => {
const username = request.body.username;
const password = request.body.password;
try {
const result = await database.query(
"SELECT * FROM admin_cred WHERE username = '?'", [username]
);
console.log(result);
if(result.length > 0){
if(password === result[0].password){
response.json({
loggedIn:"true",
data: username
})
}else{
response.json({
loggedIn:"false",
data: "wrong username or pass"
})
}
}else{
response.json({
loggedIn:"false",
data:"username doesnt exist"
})
}
} catch (error) {
console.log(error);
}
});
}
}
And here is the post request from ReactJs:
const handleLogin = async (e) =>{
e.preventDefault();
const admin = {username, password};
const response = await axios.post(
"http://localhost:8000/api/auth/v1/login",
admin
);
if(response.length > 0){
console.log("response: " + response);
}else{
console.log("no response")
}
};

Use:
const result = await database.query(
'SELECT * FROM admin_cred WHERE username = "?" AND password = "?"', [username, password]
);
Tip: never use LIKE for authentication queries and try to encrypt passwords.

Related

How to add variable into JSON path

This is the query I am using:
app.get("/items/:data", async (req, res) => {
const { data } = req.params;
query = `
SELECT items.discount
FROM items
WHERE items.discount #? '$[*] ? (#.discount[*].shift == $1)'
`
try {
const obj = await pool.query(query, [data]);
res.json(obj.rows[0])
} catch(err) {
console.error(err.message);
}
});
I get this error:
error: bind message supplies 1 parameters, but prepared statement "" requires 0
I am using node-postgres package in node.js.
How can I solve this issue?
Use bracket notation instead of dot notation. So instead of obj.key use obj[key]
Updated
all them driver connectors come with their own method to do what you're looking for. node-postgres also have there own
Pool
import { Pool } from 'pg';
const pool = new Pool({
  host: 'localhost',
user: 'database-user',
max: 20,
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 2000,
});
/**
* execs the given sql statement.
*
* #param {string} sql - query to run.
* #param {Array} params - an array with the parameter.
* #example
* runQuery("SELECT * FROM users WHERE id = $1", [1]).then(result=> console.log(result))
*/
export async function runQuery (sql, params) {
const connection = await pool.connect()
try {
await connection.query('BEGIN')
const queryText = 'INSERT INTO users(name) VALUES($1) RETURNING id'
const result = await connection.query(sql,params);
// check what result has
console.log(result);
return connection.query('COMMIT').then(result)
} catch (e) {
await connection.query('ROLLBACK')
throw e;
throw e
} finally {
connection.release()
}
}
Pool Config
config = {
// all valid client config options are also valid here
// in addition here are the pool specific configuration parameters:
// number of milliseconds to wait before timing out when connecting a new client
// by default this is 0 which means no timeout
connectionTimeoutMillis?: int,
// number of milliseconds a client must sit idle in the pool and not be checked out
// before it is disconnected from the backend and discarded
// default is 10000 (10 seconds) - set to 0 to disable auto-disconnection of idle clients
idleTimeoutMillis?: int,
// maximum number of clients the pool should contain
// by default this is set to 10.
max?: int,
}
conclution
so basically the structure of a query should be like or less this
const text = 'INSERT INTO users(name, email) VALUES($1, $2) RETURNING *'
const values = ['brianc', 'brian.m.carlson#gmail.com']
connection
.query(text, values)
.then(res => {
console.log(res.rows[0])
// { name: 'brianc', email: 'brian.m.carlson#gmail.com' }
})
.catch(e => console.error(e.stack))

SQLite3 Database is not a constructor

So in my project I am trying to gather simple Discord username and unique identifier from discord and store it in SQLite database file. I get the error:
` let userDB = new sqlite.Database('./disco.db', sqlite.OPEN_READWRITE);
^
TypeError: sqlite.Database is not a constructor`
Here is my code in my index.js
// Requirements
const Discord = require('discord.js');
const client = new Discord.Client();
const fs = require('fs');
const ServList = client.guilds.cache.size;
const sqlite = require('sqlite3').verbose();
require('dotenv').config()
//client login function
client.login(process.env.TOKEN);
// Start up Check list
client.once('ready', () => {
//Log and Set Status
console.log('Bot Online');
client.user.setActivity(`Proudly in ${client.guilds.cache.size} servers`, {
type: "WATCHING",
}, 60000);
//Database Initialization
let userDB = new sqlite.Database('./disco.db', sqlite.OPEN_READWRITE | sqlite.OPEN_CREATE);
});
Here is my code for the command that is creating the error:
const Discord = require('discord.js');
const sqlite = require('sqlite3').verbose();
module.exports = {
name: 'create',
description: "Create your account!",
use(message, args, client, sqlite){
// Data to Add
let userDB = new sqlite.Database('./disco.db', sqlite.OPEN_READWRITE);
userDB.run(`CREATE TABLE IF NOT EXIST usersInfo(userID INTEGER NOT NULL, uNameR TEXT NOT NULL)`);
let userID = message.author.id;
let uName = message.author.tag;
let uQuery = `SELECT * FROM usersInfo WHERE userID = ?`;
userDB.get(uQuery, [userID], (err, row) => {
if (err) {
console.log(err);
return;
}
if (row === undefined){
userDB.prepare(`INSERT INTO usersInfo VALUES(?,?)`);
insertdata.run('userID, uName');
insertdata.finalize();
userDB.close();
} else {
let userID2 = row.userID;
let yName = row.uNameR;
console.log(yName, userID);
}
});
message.channel.send('success');
}
}
Edit: Your question has been identified as a possible duplicate of another question. If the answers there do not address your problem, please edit to explain in detail the parts of your question that are unique.
The suggestion solution does not work for me as the suggested answer utilizes mySQL while I use SQLite3, Not only that but the suggested answer attempts to connect to a hosted database while mine is local.

Insert session data into postgres database in Nodejs Expess app

I have an Nodejs express function where I am trying to insert data that is stored in the browser session into my postgres database. When I have the insert statement like this, the insert works but the session-stored customer_id isn't inserted and is just left null.
On the line with "var sql = INSERT INTO journal....", the values $1 and $2 are from user input and work correctly.
How can I get value 3 of the customer_id stored in the session to insert correctly? I would appreciate any advice or greater understanding.
app.post("/addJournalEntry", addJournalEntry);
function addJournalEntry(req, res) {
console.log("Posting data");
// var id = req.query.id;
//body is for post, query is for get
const customer_id = req.session.customer_id;
const journal_entry_date = req.body.journal_entry_date;
const journal_entry = req.body.journal_entry;
const params = [journal_entry, journal_entry_date, customer_id];
addEntryFromDataLayer(params, function (error, addEntry) {
console.log("Back From the addEntryFromDataLayer:", addEntry);
if (error || addEntry == null) {
res.status(500).json({
success: false,
data: error
});
}
else {
// res.json(result);
res.status(200).json(addEntry);
}
});
}
function addEntryFromDataLayer(params, callback) {
console.log("addEntryFromDataLayer called with id");
var sql = "INSERT INTO journal (journal_entry, journal_entry_date, customer_id) VALUES($1::text, $2::text, $3)";
// var params = [id];
pool.query(sql, params, function (err, addEntry) {
if (err) {
console.log("error in database connection");
console.log(err);
callback(err, null);
}
console.log("Found DB result:" + JSON.stringify(addEntry));
callback(null, addEntry);
});
}

How to update correctly a table?

I try to update a table.
I do a first request to get all rows then I update this table with same data but passwords are crypted before update.
'use strict';
var sql = require('./db.js');
var crypto = require('crypto');
var Crypt = require('./encryption.js');
//Support object constructor
var Login = function(login){
this.login = login.login;
this.password = login.password;
};
sql.query("SELECT * FROM login WHERE Password IS NOT NULL OR Password != ''", function(err,res) {
if (err) {
console.log(err);
}
else {
console.log(res.length);
for (var i = 0; i < res.length ; i++) {
//console.log(res[i].Password);
//if (res[i].Password != '' ){
sql.query("UPDATE login SET Password = ? where id=?", [Crypt.encrypt(res[i].Password), i], fu
if (err){
console.log(err);
}else {
console.log(res2, 'ok');
}
}) //}
}
}
})
When I do update only some rows are updatted but not all. I want to do it on all rows.
the mistake was in the query. I was using the iterator as id but ids aren't orderded in the database. It was res[i].id instead of i in the query parameter

Nodejs Update SQL DB based on parameter from URL

Anyone able to help me out on this code .. What i expect to happen is when i hit thie URL I want it to update the DB Table with the user_name that is passed in the URL
Example: A user goes to /update/michael then I expect it to update the surname to Bloggs where the user_name is michael
app.get("/update/:user_name", function(req , res){
var user_name = req.params.name;
sql.connect(config, function() {
const request = new sql.Request();
request.query("UPDATE table SET surname = 'Bloggs' WHERE user_name= + 'req.params.name'", (err, recordset) => {
res.end(JSON.stringify(recordset));
});
});
});
I updated the code please try this and let me know in comments if it's not work.
app.get("/update/:user_name", function(req , res){
var user_name = req.params.user_name;
sql.connect(config, function() {
const request = new sql.Request();
request.query("UPDATE table SET surname = 'Bloggs' WHERE user_name= '"+user_name+"'", (err, recordset) => {
res.end(JSON.stringify(recordset));
});
});
});