AXIOS POST return result - javascript

I have created a non-JWT api call and it works. The moment I added JWT verifyToken it works but I cannot seems to get the return result set from AXIOS POST.
Function 2 --> /userget ----is working I can display result on HTML
Function 7 ---> /api/userget ---It can get data and token but I cannot display on HTML, it goes to "Bad response"
++++++++++++++++++++++++++++++++
function myFunction2() {
console.log("Going2");
var userid = document.getElementById("userid").value;
console.log(userid);
axios( {
method: 'post',
url:'http://localhost:8081/userget',
data : {
userid : userid
}
})
.then(function (response) {
console.log(response.data.result[0].username );
var userid = JSON.stringify(response.data.result[0].userid);
var username = JSON.stringify(response.data.result[0].username);
var email = JSON.stringify(response.data.result[0].email);
var userid = JSON.parse(userid);
var username = JSON.parse(username);
var email = JSON.parse(email);
var displaydata = ("User ID : " + userid + "<br><br>Name : " + username + "<br><br>Email :" + email);
document.getElementById("demo").innerHTML = displaydata;
})
.catch(function (error) {
document.getElementById("demo").innerHTML = "Bad response";
});
}
+++++++++++++++++++++++++++++++++
function myFunction7() {
console.log("Going7");
var userid = document.getElementById("userid").value;
console.log(userid);
console.log("Print local token == " + localStorage.getItem("token"));
var msgtxt = localStorage.getItem("token");
axios( {
method: 'post',
url:'http://localhost:8081/api/userget',
headers: {
'Authorization': `Bearer ${msgtxt}`
},
data : {
userid : userid
}
})
.then(function (response) {
console.log(response.data.result[0].username );
var userid = JSON.stringify(response.data.result[0].userid);
var username = JSON.stringify(response.data.result[0].username);
var email = JSON.stringify(response.data.result[0].email);
var userid = JSON.parse(userid);
var username = JSON.parse(username);
var email = JSON.parse(email);
var displaydata = ("User ID : " + userid + "<br><br>Name : " + username + "<br><br>Email :" + email);
document.getElementById("demo").innerHTML = displaydata;
})
.catch(function (error) {
document.getElementById("demo").innerHTML = "Bad response";
});
}
+++++++++++++++++++++++++++++
app.post('/userget', function (req, res) {
const userid = req.body.userid;
console.log ("User id == " + userid)
user.getUser(userid, function (err, result) {
if (!err) {
console.log(result)
res.send({result})
} else{
res.send(err.errno + " No record");
}
res.end()
});
});
+++++++++++++++++++++
app.post('/api/userget', verifyToken, (req, res) => {
const userid = req.body.userid;
console.log ("User id == " + userid)
jwt.verify(req.token, secretKey, (err, authData) => {
if(err) {
res.sendStatus(403);
} else {
user.getUser(userid, function (err, result) {
if (!err) {
console.log(result)
res.send({result})
} else{
res.send(err.errno + " No record");
}
res.end()
});
res.json({
message: 'Post created...',
authData : authData
});
}
});
});
Error in terminal
/home/ronaldtan/Programming/webservices/node_modules/mysql/lib/protocol/Parser.js:437
throw err; // Rethrow non-MySQL errors
^
Error: Can't set headers after they are sent.
at validateHeader (_http_outgoing.js:491:11)
at ServerResponse.setHeader (_http_outgoing.js:498:3)
at ServerResponse.header (/home/ronaldtan/Programming/webservices/node_modules/express/lib/response.js:771:10)
at ServerResponse.send (/home/ronaldtan/Programming/webservices/node_modules/express/lib/response.js:170:12)
at ServerResponse.json (/home/ronaldtan/Programming/webservices/node_modules/express/lib/response.js:267:15)
at ServerResponse.send (/home/ronaldtan/Programming/webservices/node_modules/express/lib/response.js:158:21)
at /home/ronaldtan/Programming/webservices/controller/app.js:170:17
at Query. (/home/ronaldtan/Programming/webservices/model/user.js:44:32)
at Query. (/home/ronaldtan/Programming/webservices/node_modules/mysql/lib/Connection.js:526:10)
at Query._callback (/home/ronaldtan/Programming/webservices/node_modules/mysql/lib/Connection.js:488:16)

The problem is the following:
user.getUser(userid, function (err, result) {
if (!err) {
console.log(result)
res.send({
result
})
} else {
res.send(err.errno + " No record");
}
res.end()
});
res.json({
message: 'Post created...',
authData: authData
});
The second statement (res.json(...)) is executed before the async-operation user.getUser(..) has finished. So once its callback is executed, res.json will already have finished and since you are trying to res.send again (res.json does the same operation under the hood) you get the error.
It seems like you can just remove the res.json(...) statement as you want to return the found user, not some info about creating a post.

Related

express-ntlm: how to get additional attribute value in req.ntlm?

In express-ntlm package i have added password attribute but i'm not able to get its value while i provide in private window of chrome. I always getting empty value.
My code is:
/* jshint node:true */
// node.js modules
var url = require('url');
// 3rd-party modules
var _ = require('underscore'),
async = require('async');
// Custom modules
var Cache = require('./Cache'),
NTLM_AD_Proxy = require('./NTLM_AD_Proxy'),
NTLM_No_Proxy = require('./NTLM_No_Proxy'),
utils = require('./utils');
const { Domain } = require('domain');
// Globals
var cache = new Cache();
module.exports = function(options) {
// Overwrite the default options by the user-defined
options = _.extend({
badrequest: function(request, response, next) {
response.sendStatus(400);
},
internalservererror: function(request, response, next) {
response.sendStatus(500);
},
forbidden: function(request, response, next) {
response.sendStatus(403);
},
unauthorized: function(request, response, next) {
response.statusCode = 401;
response.setHeader('WWW-Authenticate', 'NTLM');
response.end();
},
prefix: '[express-ntlm]',
debug: function() {
},
domaincontroller: null,
getConnectionId(request, response) {
return utils.uuidv4();
}
}, options);
function ntlm_message_type(msg) {
if (msg.toString('utf8', 0, 8) != 'NTLMSSP\0') {
return new Error('Not a valid NTLM message:', msg.toString('hex'));
}
var msg_type = msg.readUInt8(8);
if (!~[1, 2, 3].indexOf(msg_type)) {
return new Error('Incorrect NTLM message Type', msg_type);
}
return msg_type;
}
function parse_ntlm_authenticate(msg) {
var DomainNameLen = msg.readUInt16LE(0x1C),
DomainNameBufferOffset = msg.readUInt32LE(0x20),
DomainName = msg.slice(DomainNameBufferOffset, DomainNameBufferOffset + DomainNameLen),
UserNameLen = msg.readUInt16LE(0x24),
UserNameBufferOffset = msg.readUInt32LE(0x28),
UserName = msg.slice(UserNameBufferOffset, UserNameBufferOffset + UserNameLen),
PasswordLen = msg.readUInt16LE(0x34),
PasswordBufferOffset = msg.readUInt32LE(0x38),
Password = msg.slice(PasswordBufferOffset, PasswordBufferOffset + PasswordLen),
WorkstationLen = msg.readUInt16LE(0x2C),
WorkstationBufferOffset = msg.readUInt32LE(0x30),
Workstation = msg.slice(WorkstationBufferOffset, WorkstationBufferOffset + WorkstationLen);
if (utils.isFlagSet(msg.readUInt8(0x3C), utils.toBinary('00000001'))) {
DomainName = DomainName.toString('utf16le');
UserName = UserName.toString('utf16le');
Password = Password.toString('utf16le');
Workstation = Workstation.toString('utf16le');
} else {
DomainName = DomainName.toString();
UserName = UserName.toString();
Password = Password.toString();
Workstation = Workstation.toString();
}
return [UserName, Password, DomainName, Workstation];
}
function decode_http_authorization_header(auth) {
var ah = auth.split(' ');
if (ah.length === 2) {
if (ah[0] === 'NTLM') {
return ['NTLM', new Buffer(ah[1], 'base64')];
}
}
return false;
}
function connect_to_proxy(type1, callback) {
var domain = options.domain;
var proxy,
ntlm_challenge;
async.eachSeries(!options.domaincontroller ? [ -1 ] : typeof options.domaincontroller === 'string' ? [ options.domaincontroller ] : options.domaincontroller, function(server, eachDomaincontrollerCallback) {
if (!server || ntlm_challenge) return eachDomaincontrollerCallback();
if (server === -1) {
options.debug(options.prefix, 'No domaincontroller was specified, all Authentication messages are valid.');
proxy = new NTLM_No_Proxy();
} else if (!server.indexOf('ldap')) {
var serverurl = url.parse(server),
use_tls = serverurl.protocol === 'ldaps:',
decoded_path = decodeURI(serverurl.path);
options.debug(options.prefix, 'Initiating connection to Active Directory server ' + serverurl.host + ' (domain ' + domain + ') using base DN "' + decoded_path + '".');
proxy = new NTLM_AD_Proxy(serverurl.hostname, serverurl.port, domain, decoded_path, use_tls, options.tlsOptions);
} else {
return eachDomaincontrollerCallback(new Error('Domaincontroller must be an AD and start with ldap://'));
}
proxy.negotiate(type1, function(error, challenge) {
if (error) {
proxy.close();
proxy = null;
options.debug(options.prefix, error);
return eachDomaincontrollerCallback();
}
ntlm_challenge = challenge;
return eachDomaincontrollerCallback();
});
}, function(error) {
if (error) return callback(error);
if (!proxy) {
return callback(new Error('None of the Domain Controllers are available.'));
}
return callback(null, proxy, ntlm_challenge);
});
}
function handle_type1(request, response, next, ntlm_message, callback) {
cache.remove(request.connection.id);
cache.clean();
connect_to_proxy(ntlm_message, function(error, proxy, challenge) {
if (error) return callback(error);
response.statusCode = 401;
response.setHeader('WWW-Authenticate', 'NTLM ' + challenge.toString('base64'));
response.end();
cache.add(request.connection.id, proxy);
return callback();
});
}
function handle_type3(request, response, next, ntlm_message, callback) {
var proxy = cache.get_proxy(request.connection.id);
var userDomainWorkstation = parse_ntlm_authenticate(ntlm_message),
user = userDomainWorkstation[0],
pass = userDomainWorkstation[1],
domain = userDomainWorkstation[2],
workstation = userDomainWorkstation[3];
if (!domain) {
domain = options.domain;
}
proxy.authenticate(ntlm_message, function(error, result) {
if (error) return callback(error);
var userData = {
DomainName: domain,
UserName: user,
Password: pass,
Workstation: workstation,
Authenticated: false
};
request.ntlm = userData;
response.locals.ntlm = userData;
request.connection.ntlm = userData;
if (!result) {
cache.remove(request.connection.id);
options.debug(options.prefix, 'User ' + domain + '/' + user + ' authentication for URI ' + request.protocol + '://' + request.get('host') + request.originalUrl);
return options.forbidden(request, response, next);
} else {
userData.Authenticated = true;
return next();
}
});
}
return function(request, response, next) {
if (!request.connection.id) {
request.connection.id = options.getConnectionId(request, response);
}
var auth_headers = request.headers.authorization;
var user = request.connection.ntlm;
if (user && user.Authenticated) {
options.debug(options.prefix, 'Connection already authenticated ' + user.DomainName + '/' + user.UserName);
if (auth_headers) {
if (request.method != 'POST') {
request.ntlm = user;
response.locals.ntlm = user;
return next();
}
} else {
request.ntlm = user;
response.locals.ntlm = user;
return next();
}
}
if (!auth_headers) {
options.debug(options.prefix, 'No Authorization header present');
return options.unauthorized(request, response, next);
}
var ah_data = decode_http_authorization_header(auth_headers);
if (!ah_data) {
options.debug(options.prefix, 'Error when parsing Authorization header for URI ' + request.protocol + '://' + request.get('host') + request.originalUrl);
return options.badrequest(request, response, next);
}
var ntlm_version = ntlm_message_type(ah_data[1]);
if (ntlm_version instanceof Error) {
options.debug(options.prefix, ntlm_version.stack);
return options.badrequest(request, response, next);
}
if (ntlm_version === 1) {
return handle_type1(request, response, next, ah_data[1], function(error) {
if (error) {
options.debug(options.prefix, error.stack);
return options.internalservererror(request, response, next);
}
});
}
if (ntlm_version === 3) {
if (cache.get_proxy(request.connection.id) !== null) {
return handle_type3(request, response, next, ah_data[1], function(error) {
if (error) {
options.debug(options.prefix, error.stack);
return options.internalservererror(request, response, next);
}
});
}
options.debug(options.prefix, 'Unexpected NTLM message Type 3 in new connection for URI ' + request.protocol + '://' + request.get('host') + request.originalUrl);
return options.internalservererror(request, response, next);
}
options.debug(options.prefix, 'Type 2 message in client request');
return options.badrequest(request, response, next);
};
};
my response is
{"DomainName":"ijk","UserName":"xyz","Password":"","Workstation":"some","Authenticated":true}

How do I get updated value from outside of function using net library

I am new to JS.
I am trying to build API server, this server must received data from other server using socket.
Currently I am using net library, I am facing a problem.
I should get data to check whether hardware worked or not, but I only get
undefiend(empty array).
I found some sources making async function to get called, but still I can't get it.
here is my code.
router.post("/Updated", async function(req, res, next) {
.....
//connect to station server for locking
var data = {
cmd: "lockStationQuery",
stationId: STATION_ID,
powerBankId: POWER_BANK_ID,
userId: USER_ID,
number: channelValue
};
var stringData = JSON.stringify(data);
var jsonData = JSON.parse(stringData);
var [client, recvData] = await getConnectionSocket(
USER_ID,
res,
merchant_uid,
amount
);
let successToWriteData = await writeData(client, stringData);
//Fail to send data to lock the Station
if (!successToWriteData) {
res.status(500).json({
RESULT: "FAIL",
REASON:
"error code 504"
});
res.end();
return;
}
console.log("received data", recvData); //this is empty array
jsonData = JSON.parse(recvData[0]);
Here is my getConnectionSocket function.
async function getConnectionSocket(USER_ID, res, merchant_uid, amount) {
//서버에 해당 포트로 접속
var client = "";
var recvData = [];
var local_port = "";
let status = {};
client = net.connect({ port: 8999, host: "localhost" }, function() {
console.log(
"connect log======================================================================"
);
console.log("connect success");
console.log("local = " + this.localAddress + ":" + this.localPort);
console.log("remote = " + this.remoteAddress + ":" + this.remotePort);
local_port = this.localPort;
this.setEncoding("utf8");
this.setTimeout(300000); // timeout : 10분
console.log("client setting Encoding:binary, timeout:300000");
console.log("client connect localport : " + local_port);
});
// 접속 종료 시 처리
client.on("close", function() {
console.log("client Socket Closed : " + " localport : " + local_port);
});
// 데이터 수신 후 처리
await client.on("data", function(data) {
console.log(
"data recv log======================================================================"
);
recvData.push(data);
console.log(recvData); //I want this data
console.log("data.length : " + data.length);
console.log("data recv : " + data);
let jsonData = JSON.parse(data);
if (jsonData.cmd === "removedPowerBank") {
if (jsonData.errorCode !== 0) {
//환불
console.log("환불 시작");
let cancel = cancelOrder(merchant_uid, USER_ID, res);
//여기서 환불 purchase db에 쓰기
} else {
console.log("PURCHASE 성공후 디비에 씀");
//구매 purchase db에 쓰기(getRentId에 썼음)
let purchased = writePurchaseDataInDB(
USER_ID,
res,
merchant_uid,
amount
);
console.log(purchased);
}
}
client.end();
});
client.on("end", function() {
console.log("client Socket End");
});
client.on("error", function(err) {
console.log("client Socket Error: " + JSON.stringify(err));
});
client.on("timeout", function() {
console.log("client Socket timeout: ");
});
client.on("drain", function() {
console.log("client Socket drain: ");
});
client.on("lookup", function() {
console.log("client Socket lookup: ");
});
return [client, recvData]; //recvData is always empty array
}
which way is best to address to resolve this?
Need some clarification on below point
are you getting correct value(s) in below log ? Or you undefined in them too.
console.log("data.length : " + data.length);
console.log("data recv : " + data);
also add this one
console.log("data type : " + typeof(data));

Node.js query INSERT callback not working as expected

Small problem when using POST and adding an INSERT. Works as below, but want to use a callball after the data has been inserted. At the moment the database is being updated. (good) but can't use the callback - I would expect this to be just below the throw error. So you could use result.insertId. Any thoughts welcome?
router.post('/group/:id', function(req, res) {
var idToken = req.params.id;
admin.auth().verifyIdToken(idToken).then(function(decodedToken) {
var userID = decodedToken.uid;
var name = encrypt(req.body.group);
getID(userID, function(result){
var ID = result;
var post = {ID:ID, name:name};
db.query('INSERT INTO cu_groups SET ?', post, function (error, results, fields) {
if (error)throw error;
//*** when I add response here get 502 bad gateway error.
});
res.sendStatus(200);
}); // depends on getID
// admin.auth cat
}).catch(function(error) {
res.sendStatus(error);
});
});
try this way :
router.post('/group/:id', function(req, res) {
var idToken = req.params.id;
admin.auth().verifyIdToken(idToken).then(function(decodedToken) {
var userID = decodedToken.uid;
var name = encrypt(req.body.group);
getID(userID, function(result){
var ID = result;
var post = {ID:ID, name:name};
db.query('INSERT INTO cu_groups SET ?', post, function (error, results, fields) {
if(error){
return res.status(500).send(error);
}
if(!error && results){
return res.status(200).send(results);
}
});
});
}).catch(function(error) {
return res.status(500).send(error);
});
});
if you want to use callback then ,create a separate function like :
var insertData = function(query,data,callback){
db.query(query, data, function (error, results, fields) {
if(error){callback(error,null);}
if(!error && results){callback(null,results);}
});
});
and call this way inside getID :
getID(userID, function(result){
var ID = result;
var post = {ID:ID, name:name};
insertData('INSERT INTO cu_groups SET ?', post, function (error,data){
if(error){
return res.status(500).send(error);
}
if(data){
return res.status(200).send(data);
}
});
});
Working code below many thanks to Saurabh Mistry. I removed the SET post and added the table fields and values explicity.
router.post('/group/:id', function(req, res) {
var idToken = req.params.id;
admin.auth().verifyIdToken(idToken).then(function(decodedToken) {
var userID = decodedToken.uid;
var name = encrypt(req.body.group);
getID(userID, function(result){
var ID = result;
// query
let query = "INSERT INTO cu_groups (ID, name) VALUES('" + ID + "','" + name + "')";
// execute query
db.query(query, (error, result) => {
if(error){
return res.status(500).send(error);
}
if(!error && result ){
return res.send(result);
}
});
}); // depends on getID
// admin.auth cat
}).catch(function(error) {
return res.status(500).send(error);
});
});

Cognito AmazonWebService authentication issue

I'm doing an user management with the AmazonWebService cognito and I having some difficulties to authenticate me to my user pool.
Do am I logged in if I just do:
login: function(username, password, _poolData) {
var deferred = $q.defer();
var authenticationData = {
Username : username,
Password : password,
};
var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(_poolData);
var userData = {
Username : username,
Pool : userPool
};
cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData);
var authenticationDetails = new AWSCognito.CognitoIdentityServiceProvider.AuthenticationDetails(authenticationData);
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function (result) {
console.log('access token + ' + result.getAccessToken().getJwtToken());
console.log('idToken + ' + result.idToken.jwtToken)
deferred.resolve('successfully logged in.');
},
onFailure: function(err) {
console.log(error);
alert(err);
deferred.reject('login failled.');
},
});
return deferred.promise;
},
Because I can not get my user attributes after using this login method.
Like this:
getCognitoUserAttr: function(username, _poolData) {
var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(_poolData);
var userData = {
Username : username,
Pool : userPool
};
cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData);
cognitoUser.getUserAttributes(function(err, result) {
if (err) {
alert(err);
return;
}
for (var i = 0; i < result.length; i++) {
console.log('attribute ' + result[i].getName() + ' has value ' + result[i].getValue());
}
});
}
I always have the error message:
Error: User is not authenticated
Note that the login method is from :https://docs.aws.amazon.com/fr_fr/cognito/latest/developerguide/using-amazon-cognito-user-identity-pools-javascript-examples.html
What I have to do?
Here you go. I made a function called getUserAttributes() then used the same code as seen in isAuthenticated.
getUserAttributes(){
let cognitoUser = this.getCurrentUser();
if (cognitoUser != null) {
cognitoUser.getSession(function (err, session) {
cognitoUser.getUserAttributes(function(err, result) {
if (err) {
console.log(err);
return;
}
for (let i = 0; i < result.length; i++) {
console.log('attribute ' + result[i].getName() + ' has value ' + result[i].getValue());
}
});
});
}
}
this is the login function i use
authenticate(username: string, password: string, callback: CognitoCallback) {
let authenticationData = {
Username : username,
Password : password,
};
let authenticationDetails = new AWSCognito.CognitoIdentityServiceProvider.AuthenticationDetails(authenticationData);
let poolData = {
UserPoolId : CognitoUtil._USER_POOL_ID,
ClientId : CognitoUtil._CLIENT_ID
};
let userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData);
let userData = {
Username : username,
Pool : userPool
};
let cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData);
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function (result) {
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId : CognitoUtil._IDENTITY_POOL_ID,
Logins : {
'cognito-idp.REGION.amazonaws.com/POOLID':result.getIdToken().getJwtToken()
}
});
callback.cognitoCallback('loginSuccess', null);
},
onFailure: function (err) {
callback.cognitoCallback(err.message, null);
}
});
}

TypeError: Cannot read property 'length' of undefined and other errors

Whenever I try to run the JS code with node in CMD I get this error:
Oh and the bot probably cannot be run since stackoverflow needs permission from mySQL database.
TypeError: Cannot read property 'length' of undefined
at Query._callback (C:\Users\George\Desktop\bot2\websitebot.js:138:9)
at Query.Sequence.end (C:\Users\George\node_modules\mysql\lib\protocol\sequences\Sequence.js:86:24)
at Query.ErrorPacket (C:\Users\George\node_modules\mysql\lib\protocol\sequences\Query.js:94:8)
at Protocol._parsePacket (C:\Users\George\node_modules\mysql\lib\protocol\Protocol.js:280:23)
at Parser.write (C:\Users\George\node_modules\mysql\lib\protocol\Parser.js:74:12)
at Protocol.write (C:\Users\George\node_modules\mysql\lib\protocol\Protocol.js:39:16)
at Socket.<anonymous> (C:\Users\George\node_modules\mysql\lib\Connection.js:109:28)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at readableAddChunk (_stream_readable.js:176:18)
This is the code I'm trying to run, I honestly have no idea why I am getting these errors. Incase someone here might help me:
//The required liberys for the bot to work
var Steam = require('steam')
var SteamUser = require('steam-user');
var SteamTotp = require('steam-totp');
var SteamConfirm = require('steamcommunity-mobile-confirmations');
var SteamTradeOffers = require('steam-tradeoffers');
var TradeOfferManager = require('steam-tradeoffer-manager');
var TOTP = require('onceler').TOTP;
var request = require('request');
var mysql = require('mysql');
var offers = new SteamTradeOffers();
var apik = 'xxx'; //The API Key of the bot.
var botsteamid = 'xxx'; //The SteamID of the bot.
var identitysecret = 'xxx'; //The identity secret of the bot.
var sharedsecret = 'xxx'; //The shared secret of the bot
var botusername = 'xxx';
var botpassword = 'xxx';
var admin = 'xxx'; //The steamid of the Admin.
var botid = 'xxx'; //The ID of the bot..
var pooling_interval = 10000; // 10 seconds by default, the bot checks for outgoing confirmations every X seconds, defined here
//Setting up device identity
var deviceid=SteamTotp.getDeviceID(botsteamid);
//Making the bot log in.
var details = {
"accountName" : botusername, // Bot username
"password" : botpassword, // Bot password
"twoFactorCode" : SteamTotp.generateAuthCode(sharedsecret)
};
var client = new SteamUser();
var manager = new TradeOfferManager({
"steam" : client,
"domain" : "localhost", //localhost
"language" : "en",
})
//Setting up the MySQL Connection - This is where I have errors.
var connection = mysql.createConnection({
host : 'xxx', // MYSQL , LEAVE IT AS LOCALHOST IF YOU RUN IT ON THE SAME SERVER AS THE WEBSITE AND DATABASE
user : 'xxx', // MYSQL USERNAME
password : 'xxx', // MYSQL PASSWORD
database : 'xxx', // MYSQL DATABASENAME
charset : 'utf8_general_ci'
});
connection.connect();
client.logOn(details);
//Checking mobile confirmations
function checkConfirmations(steamcommunityMobileConfirmations){
steamcommunityMobileConfirmations.FetchConfirmations((function (err, confirmations)
{
if (err)
{
console.log('Confirmations error: '+err);
if(err=='Error: 503') // This is an error you can most likely ignore, except if it's spammed a lot - To fix it simply restart the bot
{
}
if(err=='Error: Invalid protocol: steammobile:') // - To fix it simply restart the bot
{
// A fix should be coming soon!
}
return;
}
if(confirmations.length>0)
{
console.log('[SERVER] Received ' + confirmations.length + ' confirmations');
}
if ( ! confirmations.length)
{
return;
}
steamcommunityMobileConfirmations.AcceptConfirmation(confirmations[0], (function (err, result)
{
if (err)
{
console.log(err);
return;
}
console.log('[SERVER] Confirmation handling result: ' + result);
}).bind(this));
}).bind(this));
}
//Done with the functions, time to do commands.
//Logging the bot in
client.on('loggedOn', function(details)
{
client.on('webSession', function(sessionID, cookies){
manager.setCookies(cookies, function(err) {
if(err) {
console.log('setCookies error: '+err);
process.exit(1); // Fatal error since we couldn't get our API key
return;
}
var steamapi=manager.apiKey;
var SteamcommunityMobileConfirmations = require('steamcommunity-mobile-confirmations');
var steamcommunityMobileConfirmations = new SteamcommunityMobileConfirmations(
{
steamid: botsteamid,
identity_secret: identitysecret,
device_id: deviceid,
webCookie: cookies,
});
setInterval(function(){
checkConfirmations(steamcommunityMobileConfirmations)
}, pooling_interval);
console.log("[SERVER] The Bot has logged in!");
client.addFriend(admin);
client.setPersona(Steam.EPersonaState.LookingToTrade);
});
offers.setup({
sessionID: sessionID,
webCookie: cookies,
APIKey: apik
});
});
});
function checkWithdraw(){
connection.query("SELECT * FROM `withdraw` WHERE active=1 AND `botid`='"+botid+"' AND tradestatus='Queued' LIMIT 1", function(err, row, fields) {
if (!row.length) {
return;
}
var tradeid = row[0].id;
var sendItems = (row[0].assetids).split(',');
var item=[],num = 0;
for (i = 0; i < sendItems.length; i++) {
item[num] = {
appid: 730,
contextid: 2,
amount: 1,
assetid: sendItems[i]
}
num++;
}
offers.makeOffer ({
partnerSteamId: row[0].steamid,
accessToken: row[0].token,
itemsFromMe: item,
itemsFromThem: [],
message: 'Withdraw from '
},
function(err, response) {
if (err) {
console.log(err);
return;
}
console.log('Tradeoffer sent to ' + row[0].steamid);
tradeofferquery = response;
tradeofferid = (tradeofferquery['tradeofferid']);
connection.query('UPDATE `withdraw` SET `tradeid`=\''+tradeofferid+'\', `tradestatus`="Sent" WHERE `id`=\''+tradeid+'\'', function(err, row, fields) {});
})
});
}
function checkDeposit(){
connection.query("SELECT * FROM `deposits` WHERE `credited`=\'0\' AND `tradestatus`=\'Queued\' AND `botid`='"+botid+"' LIMIT 1", function(err, row, fields) {
if (!row.length) {
return
}
offers.getHoldDuration({partnerSteamId: row[0].steamid, accessToken: row[0].token}, function(err, response)
{
if (err)
{
return;
}
escrowduration = response;
thesd = (escrowduration['their']);
if(thesd === 0){
var tradeid = row[0].id;
var sendItems = (row[0].assetids).split(',');
var item=[],num = 0;
for (i = 0; i < sendItems.length; i++) {
item[num] = {
appid: 730,
contextid: 2,
amount: 1,
assetid: sendItems[i]
}
num++;
}
console.log(item);
offers.makeOffer ({
partnerSteamId: row[0].steamid,
accessToken: row[0].token,
itemsFromMe: [],
itemsFromThem: item,
message: 'Deposit to , code: ' + row[0].code
}, function(err, response) {
if (err) {
console.log(err);
return;
}
console.log('Tradeoffer sent to ' + row[0].steamid);
tradeofferquery = response;
tradeofferid = (tradeofferquery['tradeofferid']);
connection.query('UPDATE `deposits` SET `tradeid`=\''+tradeofferid+'\', `tradestatus`="Sent" WHERE `id`=\''+tradeid+'\'', function(err, row, fields) {});
})
} else {
connection.query('DELETE FROM `deposits` WHERE `steamid`=\''+ row[0].steamid +'\'', function(err, row, fields) {});
console.log('They are in escrow');
}
});
});
}
//Keeping track of sent offers.
manager.on('sentOfferChanged', function(offer, oldState) {
console.log("Offer #" + offer.id + " changed: " + TradeOfferManager.getStateName(oldState) + " -> " + TradeOfferManager.getStateName(offer.state));
connection.query('UPDATE `deposits` SET `tradestatus`=\''+TradeOfferManager.getStateName(offer.state)+'\' WHERE `tradeid`=\''+offer.id+'\'');
connection.query('UPDATE `withdraw` SET `tradestatus`=\''+TradeOfferManager.getStateName(offer.state)+'\' WHERE `tradeid`=\''+offer.id+'\'');
if(offer.state == TradeOfferManager.ETradeOfferState.Accepted) {
offer.getReceivedItems(function(err, items) {
if(err) {
console.log("Couldn't get received items: " + err);
} else {
items.forEach(function(item)
{
console.log('Recieved: ' + item.name);
connection.query('INSERT INTO `bank` (`botid`,`assetid`,`img`,`name`,`status`) VALUES (\''+botid+'\',\''+item.assetid+'\',\''+item.icon_url+'\',\''+item.market_name+'\',\'1\')', function(err, row, fields) {});
})
}
});
}
if(offer.state != (TradeOfferManager.ETradeOfferState.Accepted || TradeOfferManager.ETradeOfferState.Active)) {
connection.query('DELETE FROM `deposits` WHERE `tradeid`=\''+offer.id+'\'');
connection.query('DELETE FROM `withdraw` WHERE `tradeid`=\''+offer.id+'\'');
}
});
//Processing incomming offers
manager.on('newOffer', function(offer)
{
offer.decline(function(err)
{
console.log('[DEBUG] Declined Counter offer.');
if (err)
{
console.log('Decline error: '+err);
}
connection.query('DELETE FROM `deposits` WHERE `tradeid`=\''+offer.id+'\'');
connection.query('DELETE FROM `withdraw` WHERE `tradeid`=\''+offer.id+'\'');
});
});
setInterval(function() {
checkDeposit();
checkWithdraw();
}, 5000);
//Numeric and float
function is_float(mixed_var)
{
return +mixed_var === mixed_var && (!isFinite(mixed_var) || !! (mixed_var % 1));
}
function isNumeric(n){
return (typeof n == "number" && !isNaN(n));
}
//Setting up chat commands for the admin
client.on('friendMessage#'+admin+'', function(steamID, message)
{
console.log("[SERVER] Admin to Bot: " + message);
if((message.indexOf("ping") == 0) || (message.indexOf("/cmd") == 0))
{
checkDeposit();
client.chatMessage(admin, 'Pong!');
}
if((message.indexOf("pong") == 0) || (message.indexOf("/cmd") == 0))
{
checkWithdraw();
client.chatMessage(admin, 'Pong!');
}
if(message.indexOf("/code") == 0)
{
var code = SteamTotp.generateAuthCode(sharedsecret);
client.chatMessage(admin, '[SERVER] Your login code: '+code+'');
}
});
If i understod your question right this is where the error occur.
connection.query("SELECT * FROM `withdraw` WHERE active=1 AND `botid`='"+botid+"' AND tradestatus='Queued' LIMIT 1", function(err, row, fields) {
if (!row.length) {
return;
}
Im kind of new too the mysql area but i whould try to write the code something like this instead:
connection.query("SELECT * FROM `withdraw` WHERE active=1 AND `botid`= ? AND tradestatus='Queued' LIMIT 1",botid , function(err, rows, fields) {
if (!rows.length) {
return;
}
What ive done is changed the place where you input the "botid" to a "?" instead, that takes the value from the botid right before your function, and row is now rows just for code clearance.
As you said, i cant access your DB but i hope that this might work. Let me know!

Categories