How to use select statement with where condition on node.js - angularjs

> 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+"'";

Related

Node promises and catch issue

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!

What is the node.js equivalent of this T-SQL query

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);
}

angular/node.js POST for payumoney integration

I'm using angular/node.js stack for payumoney integration.
On the angular side, an order is placed using $http.post to a route endpoint at the server side (node.js) as follows:
$http.post('/placeOrder',order).success(function(data, status, headers, config){
//handle responses on client side
console.log("Successfully POSTED to payment gateway");
window.location = "https://test.payu.in/_payment";
}).error(function(data, status, headers, config) {
console.log("Error in posting");
});
The actual heavy lifting is done on the node.js (server side):
router.post('/placeOrder', function(req, res, next){
hash_data = MERCHANT_KEY+'|'+txnid+'|'+amount+'|'+productinfo+'|'+firstname+'|'+email+'|'+udf1+'|'+udf2+'|'+udf3+'|'+udf4+'|'+udf5+'||||||'+SALT;
var data = querystring.stringify({
'key': MERCHANT_KEY,
'txnid': txnid,
'amount': amount,
'productinfo': productinfo,
'firstname': firstname,
'email': email,
'phone': phone,
'surl': SUCCESS_URL,
'furl': FAILURE_URL,
'curl': FAILURE_URL,
'hash': hash,
'service_provider': SERVICE_PROVIDER
//'salt': SALT
});
//POST options
var POST_OPTIONS = {
hostname: PAYU_BASE_URL,
port: 443,
path: '/_payment',
method: 'POST',
//json: true,
agent: false,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
//'Content-Length': Buffer.byteLength(data)
'Content-Length': data.length
}
};
var resp_status = "";
var req = https.request(POST_OPTIONS, function(response) {
console.log('STATUS: ' + response.statusCode);
console.log('HEADERS: ' + JSON.stringify(response.headers));
response.setEncoding('utf8');
response.on('data', function (chunk) {
console.log("body: " + chunk);
resp_status = 200;
res.json(chunk);
});
response.on('error', function (err) {
console.log("Got error: " + err.message);
resp_status = 500;
return res.send(err);
});
});
req.end(data);
However, this doesn't seem to work as the POST doesnt seem to work using this approach. While debugging on the browser through the network tab, I always see:
Request URL:https://test.payu.in/_payment
Request Method:GET
Status Code:200 OK
Also, the test payment page (https://test.payu.in/_payment) shows:
"Error Reason
One or more mandatory parameters are missing in the transaction request."
Any help would be appreciated!!
How did I implement this..
Use Jquery and create a Form
Use sha512 to create hashcode. (bower install js-sha512)
var hashString = this.merchantKey+'|'+ options.uid +'|'+ options.totalPrice + '|'+'options.uid + '|' +
options.recipient_name + '|'+ options.email +'|||||||||||'+ this.merchantSalt ;
var hash = sha512(hashString);
var key1 = $('<input></input>').attr('type', 'hidden').attr('name', "key").val("merchantKey");
var key2 = $('<input></input>').attr('type', 'hidden').attr('name', "txnid").val(options.uid);
var key3 = $('<input></input>').attr('type', 'hidden').attr('name', "amount").val(options.totalPrice);
var key4 = $('<input></input>').attr('type', 'hidden').attr('name', "productinfo").val(options.uid);
var key5 = $('<input></input>').attr('type', 'hidden').attr('name', "firstname").val(options.recipient_name);
var key6 = $('<input></input>').attr('type', 'hidden').attr('name', "email").val(options.email);
var key7 = $('<input></input>').attr('type', 'hidden').attr('name', "phone").val(options.phone);
var key8 = $('<input></input>').attr('type', 'hidden').attr('name', "surl").val("http://192.168.43.121/payment/success");
var key9 = $('<input></input>').attr('type', 'hidden').attr('name', "furl").val("http://192.168.43.121/payment/error");
var key10 = $('<input></input>').attr('type', 'hidden').attr('name', "hash").val(hash);
var key11 = $('<input></input>').attr('type', 'hidden').attr('name', "service_provider").val("payu_paisa");
var form = $('<form/></form>');
form.attr("id", "payuform");
form.attr("action", this.payumoneyLink );
form.attr("method", "POST");
form.attr("style", "display:none;");
form.append(key1, key2, key3, key4, key5, key6, key7, key8, key9,key10, key11);
$("body").append(form);
// submit form
form.submit();
This is my first answer on StacksOverflow. Hope it helps!
As per the browser network tab which you have mentioned,
Request URL:https://test.payu.in/_payment Request Method:GET Status Code:200 OK
This means PayU is getting called with GET request instead of POST request somehow. PayU accepts data as a POST request only.
Also, the test payment page (https://test.payu.in/_payment) shows: "Error Reason One or more mandatory parameters are missing in the transaction request."
This is due to GET request. I have faced similar situation in my JSF based application wherein I was sending all parameters correctly but as a GET request. Later on when I switched to POST, the error got resolved automatically.
For information about sending POST request from angular, check below link.
https://www.devglan.com/angular/payumoney-integration-angular
NOTE: If input type is hidden, angularjs has some issue connecting model and view. So please take a note of that. txnid and hash I am getting from AJAX get call so I had to bind it in seperate variable from scope.
Angular code is staright forward, just populate the variables.
One more thing to remember as of today, if your account is not active then you need to use test salt/key provided by their customer support:
MID : 4934580
Key : rjQUPktU
Salt : e5iIg1jwi8
Authorization : y8tNAC1Ar0Sd8xAHGjZ817UGto5jt37zLJSX/NHK3ok=
Test Card : 5123456789012346
Expiry : 05/20
CVV : 123

NodeJS OracleDB bind parameters returning parameter name

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.

Connection to table denied in SQL Server 2012

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);
});

Resources