The legacy system used to store passwords in query's output format,
SELECT
HASHBYTES('SHA1', CONVERT(VARCHAR, HASHBYTES('SHA1', CONVERT(NVARCHAR(4000), ’test'))) + 'mysalt')
where the password is test and mysalt is the salt used.
The result is something like
0x169A0EF01AA369518D6810E14872A3A003A1F0AA
I have to take that encrypted password and create a node function to get the same result as the above query
Node.js is not going to replace a t-sql query. You would still use t-sql to query your database and something like the tedious module connection to the database. This is an example from https://msdn.microsoft.com/library/mt715784.aspx on how to connect from node.js to SQL Server and execute a query. Some modifications to the executeStatement function would get you going.
var Connection = require('tedious').Connection;
var config = {
userName: 'yourusername',
password: 'yourpassword',
server: 'yourserver.database.windows.net',
// When you connect to Azure SQL Database, you need these next options.
options: {encrypt: true, database: 'AdventureWorks'}
};
var connection = new Connection(config);
connection.on('connect', function(err) {
// If no error, then good to proceed.
console.log("Connected");
executeStatement();
});
var Request = require('tedious').Request;
var TYPES = require('tedious').TYPES;
function executeStatement() {
request = new Request("SELECT c.CustomerID, c.CompanyName,COUNT(soh.SalesOrderID) AS OrderCount FROM SalesLT.Customer AS c LEFT OUTER JOIN SalesLT.SalesOrderHeader AS soh ON c.CustomerID = soh.CustomerID GROUP BY c.CustomerID, c.CompanyName ORDER BY OrderCount DESC;", function(err) {
if (err) {
console.log(err);}
});
var result = "";
request.on('row', function(columns) {
columns.forEach(function(column) {
if (column.value === null) {
console.log('NULL');
} else {
result+= column.value + " ";
}
});
console.log(result);
result ="";
});
request.on('done', function(rowCount, more) {
console.log(rowCount + ' rows returned');
});
connection.execSql(request);
}
Related
I have to run a query on SQL Server 2014 using the node.js mssql package. To do so, use the query below with the two input parameters. When I execute the T-SQL code, the following error shows up:
RequestError: The conversion of a varchar data type to a datetime data type resulted in an out-of-range value
How can I solve it?
Input values:
IdCantiere: 14
Data: 2018-06-21 09:20:04.000
Node.js code:
async function CaricaRisorseCantiere(IdCantiere, Data) {
var value = [];
var query = "select RisorseUmane.IdRisorseUmane,IdUtenteInserimento,u1.Nome+' '+u1.Cognome as InseritoDA,ExtraPreventivo,u2.Nome+' '+u2.Cognome as Risorsa,RisorseUmane.IdUtente,IdCantiere,CONVERT(VARCHAR(10), Data, 105) as Data,Descrizione,convert(varchar(5), OreInizio, 108) as OreInizio,convert(varchar(5), OreFine, 108) as OreFine,REPLACE(Pausa, '.', ':') as Pausa,convert(varchar(5), Cast(convert(varchar(5), (OreFine - OreInizio), 108) as datetime) - CAST(REPLACE(Pausa, '.', ':') as datetime), 108) as TotaleOre from RisorseUmane inner join Utente as u1 on u1.IdUtente = RisorseUmane.IdUtenteInserimento inner join Utente as u2 on u2.IdUtente = RisorseUmane.IdUtente ";
if (Data == "") {
query = query + " where RisorseUmane.IdCantiere= #IdCantiere order by convert(datetime, Data, 103) desc ";
} else {
query = query + " inner join RisorsaRapportoMobile on RisorsaRapportoMobile.IdRisorseUmane=RisorseUmane.IdRisorseUmane where RisorseUmane.IdCantiere= #IdCantiere and RisorsaRapportoMobile.IdRapportoMobile is null and RisorseUmane.Data=convert(varchar,convert(datetime,#Data),105) ";
}
const ret = await new Promise((resolve, reject) => {
new sql.ConnectionPool(DbConfig.config).connect().then(pool => {
if (Data == "") {
return pool.request().input('IdCantiere', sql.Int, IdCantiere).query(query)
} else {
return pool.request().input('IdCantiere', sql.Int, IdCantiere).input('Data', sql.VarChar, Data).query(query)
}
}).then(result => {
resolve(result);
sql.close();
}).catch(err => {
console.log("Errore Risorse Model: ", err)
reject(err);
sql.close();
})
});
for (var i = 0; i < ret.recordset.length; i++) {
value.push({
IdRisorseUmane: ret.recordset[i].IdRisorseUmane,
IdUtenteInserimento: ret.recordset[i].IdUtenteInserimento,
InseritoDA: ret.recordset[i].InseritoDA,
ExtraPreventivo: ret.recordset[i].ExtraPreventivo,
Risorsa: ret.recordset[i].Risorsa,
Data: ret.recordset[i].Data,
Descrizione: ret.recordset[i].Descrizione,
TotaleOre: ret.recordset[i].TotaleOre
})
}
return value;
}
Instead of using the input call:
request.input('Data', sql.VarChar, Data)
The call should be changed to:
request.input('Data', sql.DateTime, new Date(Data));
Also, the SQL clause:
and RisorseUmane.Data=convert(varchar,convert(datetime,#Data),105)
Should become
and RisorseUmane.Data=convert(varchar,#Data,105)
I am currently writing a database class that receives a node http request and saves data into a db.
It uses MSSQL (yeah...), therefore I'm using node-mssql.
I created a class to manage DB access, code:
"use strict";
var config = require('../../config/mainConfigs');
const mssql = require('mssql');
class db {
constructor(){
this._pool = null;
}
get_pool(){
if (!this._pool) {
if (config.Logging.DB.type == 'mssql'){
const dbOptions = {
user: config.Logging.DB.user,
password: config.Logging.DB.password,
server: config.Logging.DB.mssql.server,
database: config.Logging.DB.mssql.database,
options: {
encrypt: config.Logging.DB.encrypt
}
};
this._pool = new mssql.ConnectionPool(dbOptions);
}
}
return this._pool;
}
insertHTTPRequest(req){
const pool = this.get_pool();
if (config.Logging.DB.type == 'mssql'){
if (pool._connected){
var request = new mssql.Request(pool);
var query = `INSERT INTO SD_LOG (
MODULE,
INSTANCE,
REMOTE_ADDR,
USERNAME,
USER_AGENT,
HTTP_METHOD,
HTTP_REQ_URL
) OUTPUT Inserted.ID_SD_LOG VALUES (
#module,
#instance,
#remote_addr,
#username,
#user_agent,
#http_method,
#http_req_url
)`;
request.input('module', 'tokenizer');
request.input('instance', config.Deployment.instance);
request.input('remote_addr', req.ip);
request.input('username', req.user.displayName);
request.input('user_agent', req.headers['user-agent']);
request.input('http_method', req.method);
request.input('http_req_url', req.url);
return request.query(query);
}else{
return pool.connect().then(() => {
var request = new mssql.Request(pool);
var query = `INSERT INTO SD_LOG (
MODULE,
INSTANCE,
REMOTE_ADDR,
USERNAME,
USER_AGENT,
HTTP_METHOD,
HTTP_REQ_URL
) OUTPUT Inserted.ID_SD_LOG VALUES (
#module,
#instance,
#remote_addr,
#username,
#user_agent,
#http_method,
#http_req_url
)`;
request.input('module', 'tokenizer');
request.input('instance', config.Deployment.instance);
request.input('remote_addr', req.ip);
request.input('username', req.user.displayName);
request.input('user_agent', req.headers['user-agent']);
request.input('http_method', req.method);
request.input('http_req_url', req.url);
request.query(query);
}
}
}
}
I am using a middleware in the routes to save the request into the DB, like this:
app.use(function(req, res, next){
//send req to DB, get ID_SD_LOG from DB, assign to req.id
db_instance.insertHTTPRequest(req).then((genid)=>{
req.id = genid;
next();
}).catch((err)=>{
combinedLogger.error(err);
res.send('Database is unavailable.');
res.end();
})
});
Thing is, I am getting an error, however, in console, the error is undefined. So I really can't figure out whats wrong. I can imagine it's the connect() method, as I tested logging in console static string in the db request and I don't them, which I assume it's not even accessing that part.
Any help?
Thanks!
> Am trying to provide login credentials with email and password using postgres database table.
postgres database tables. When i get records it should send 200 status
to my page.Am getting error on query. Kindly help me out how to use
select with where condition. Am missing some syntax.
getUser : function(req, res) {
var pg = require('pg');
var conString = process.env.DATABASE_URL || "postgres://test:test#localhost:5432/wallet";
var client = new pg.Client(conString);
client.connect();
console.log(req.query.email_id);
console.log(req.query.user_password);
var query = client.query("select * from pp_user_profile where email_id ="+req.query.email_id+ "and" + "user_password=" +req.query.password);
query.on("end", function (result) {
client.end();
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('Success');
res.end();
});
},
Try the below syntax:
"select * from pp_user_profile where email_id = '"+req.query.email_id+"' and user_password= '"+req.query.password+"'";
I am very new to NodeJS, but I have been working to use it to serve my Angular project. I need to access an Oracle DB and return some information using a select statement. I have one statement that works correctly using a bind parameter that is set up like this:
var resultSet;
connection.execute("SELECT column_name, decode(data_type, 'TIMESTAMP(3)','NUMBER'"
+ ",'VARCHAR2','STRING','CHAR', 'STRING','NUMBER') as \"DATA_TYPE\""
+ "FROM someTable where table_name = :tableName",
[table], //defined above
{outFormat: oracledb.OBJECT},
function (err, result) {
if (err) {
console.error(err.message);
doRelease(connection);
return;
}
resultSet = result.rows;
console.log("Received " + resultSet.length + " rows.");
res.setHeader('Content-Type', 'application/json');
var JSONresult = JSON.stringify(resultSet);
// console.log(JSONresult);
res.send(JSONresult);
doRelease(connection);
});
This returns exactly what I want it to, with the bound variable being what I wanted it to be. Below is the code that doesn't work:
var resultSet;
connection.execute(
"SELECT DISTINCT :columnName from someTable",
['someColumn'],
{outFormat: oracledb.OBJECT},
function (err, result) {
if (err) {
console.error(err.message);
doRelease(connection);
return;
}
resultSet = result.rows;
console.log("Received " + resultSet.length + " rows.");
res.setHeader('Content-Type', 'application/json');
var JSONresult = JSON.stringify(resultSet);
console.log(JSONresult);
res.send(JSONresult);
doRelease(connection);
});
This returns {":COLUMNNAME": "someColumn"}. I do not understand why it won't display the results correctly. The two snippets of code are exactly the same, save the SQL query part. I know this a long question, but I really need help. Thank you!
You can bind data values, not the text of the statement itself.
I am trying to manipulate a table in SQL Server with node. I've succeeded to connect to the database but when I do a query request I get this error :
SELECT permission was denied on the object Customer
I've tried this command but it didn't work :
USE NodeDB;
GRANT SELECT ON OBJECT::Customer TO test;
GO
This is the code I've written in node :
/*--------------------Connection--------------------------------*/
var sql = require('mssql');
var config = {
user: 'test',
password: '11111',
server: 'ICEFOX-PC\\SQLSQL',
database: 'NodeDB'
}
sql.connect(config, function(err) {
if (err){
throw err ;
} else{
console.log('connected');
}
/*--------------------Connection--------------------------------*/
var request = new sql.Request([config]);
request.query('select * from Customer', function(err, recordset) {
if (err) {
throw err ;
} else {
console.dir(recordset);
});