javasctipt - asynchronous issue for return value - javascript

I am working in MEAN STACK application and i want to set mail's parameters dynamic.
route.js
var Helper = require("../helper.js");
router
.route("/api/user/registration")
.POST(function (req, res) {
//after user insert send mail
Helper.sendCustomEmail(params, function (error, response) {
if (error) {
console.log("Mail : " + error);
res.json({"status": 0, "error": {"other": "Oops! something went wrong, please try again later"}});
} else {
console.log("Message sent");
res.json({status: 1, message: 'Thank you for registration. You will get verification email soon', token: res.locals.user.jwttoken});
}
});
});
Helper.js
exports.sendCustomEmail = function(params, callback) {
//Include nodejs mailer and smtp module
var nodemailer = require('nodemailer');
var smtpTransport = require('nodemailer-smtp-transport');
//read header email template
var headerHtml = params.fs.readFileSync(basePath + "emailHeader.html").toString();
//read footer email template
var footerHtml = params.fs.readFileSync(basePath + "emailFooter.html").toString();
//Your dynamic template html only
var dynamicMessage = params.message;
var message = headerHtml + dynamicMessage + footerHtml;
message = message.replace(/##DOMAIN_URL##/g, "http://" + params.domainUrl);
// create reusable transporter object using the default SMTP transport
var transporter = nodemailer.createTransport(smtpTransport({
host: this.getSiteSetting("SMTP_HOST"),
secure: true,
auth: {
user: this.getSiteSetting("SMTP_USER"),
pass: this.getSiteSetting("SMTP_PSSSWORD")
},
tls: {
rejectUnauthorized: false
}
}));
transporter.sendMail({
from: this.getSiteSetting("SMTP_FROM"),
to: params.to, // receiver
subject: params.subject,
html: message // body
}, function(error, response) { //callback
callback(error, response);
});
};
var SiteSetting = require('../models/siteSetting');
exports.getSiteSetting = function($keyword) {
if ($keyword !== undefined && $keyword !== null && $keyword !== "") {
SiteSetting.findOne({setting_key : $keyword},function(err,siteSetting){
if(err){
return null;
}else{
if(siteSetting !== null){
console.log(siteSetting.setting_value);
return siteSetting.setting_value;
}
}
});
}else{
return null;
}
};
dependencies
"express" => "version": "4.13.4",
"mongoose" => "version": "4.4.4",
"mongodb" => "version": "2.4.9",
"OS" => "ubuntu 14.04 lts 32bit",
from the following code SiteSetting function console.log print properly but before return mail send error occur.
Please give me a proper guideline for this code.

This can be solved as bellow.
exports.sendCustomEmail = function(params, callback) {
//Include nodejs mailer and smtp module
var nodemailer = require('nodemailer');
var smtpTransport = require('nodemailer-smtp-transport');
//read header email template
var headerHtml = fs.readFileSync(basePath + "app/client/views/layout/emailTemplates/emailHeader.html").toString();
//read footer email template
var footerHtml = fs.readFileSync(basePath + "app/client/views/layout/emailTemplates/emailFooter.html").toString();
//Your dynamic template html only
var dynamicMessage = params.message;
var message = headerHtml + dynamicMessage + footerHtml;
message = message.replace(/##DOMAIN_URL##/g, "http://" + params.domainUrl);
var host = null;
var user = null;
var pass = null;
var from = null;
this.getSiteSetting("SMTP_HOST", function(res) {
host = res;
setParams();
});
this.getSiteSetting("SMTP_USER", function(res) {
user = res;
setParams();
});
this.getSiteSetting("SMTP_PASS", function(res) {
pass = res;
setParams();
});
this.getSiteSetting("MAIL_FROM", function(res) {
from = res;
setParams();
});
var setParams = function() {
if (host !== null && user !== null && pass !== null && from !== null) {
// create reusable transporter object using the default SMTP transport
var transporter = nodemailer.createTransport(smtpTransport({
host: host,
//port: 25,
//port: 465,
secure: true,
auth: {
user: user,
pass: pass
},
tls: {
rejectUnauthorized: false
}
}));
transporter.sendMail({
from: from,
to: params.to, // receiver
subject: params.subject,
html: message // body
}, function(error, response) { //callback
callback(error, response);
});
}
};
}
var SiteSetting = require('../models/siteSetting');
exports.getSiteSetting = function(keyword, callback) {
if (keyword !== undefined && keyword !== null && keyword !== "") {
SiteSetting.findOne({ setting_key: keyword }, function(err, siteSetting) {
if (err) {
callback(null);
} else {
if (siteSetting !== null) {
//console.log(siteSetting.setting_value);
callback(siteSetting.setting_value);
}else{
callback(null);
}
}
});
} else {
callback(null);
}
};

Related

Need to do validation so if the url is invalid, then only send the email

I've create a script which checks a list of urls, and if their http status code is 200 then the urls are up and if their http status code is anything other than 200 then they are down.
I've also setup a mail function using nodemailer, which sends list of urls which are down. But right now the problem is if all the urls are valid then also it sends the empty mail.
What I want to do is , only send mail if the urls are invalid/down urls and if the all the urls are valid then send any other message like "No invalid urls" or just dont send any email and exit the script.
const request = require("request");
const nodemailer = require("nodemailer");
// list of urls that need to be checked
const urlList = [
// valid url (returns http 200)
"https://google.com/",
// invalid url (returns http 404 not found)
"https://googglslfdkfl.com/",
];
// e-mail setup
const transporter = nodemailer.createTransport({
host: "smtp.gmail.com",
port: 587,
auth: {
user: "email",
pass: "password",
},
secure: false,
});
//get the http status code
function getStatus(url) {
return new Promise((resolve, reject) => {
request(url, function (error, response, body) {
resolve({
site: url,
status:
!error && response.statusCode == 200
? "OK"
: "Down: " + error.message,
});
});
});
}
let promiseList = urlList.map((url) => getStatus(url));
// return a list of only the sites in an array with status of Down
const returnListOfUrls = Promise.all(promiseList).then((resultList) => {
const listWithDownStatus = resultList
.map((result) => result.status.startsWith("Down") && result.site)
.filter(Boolean);
return listWithDownStatus;
});
const runNodeMailer = () => {
returnListOfUrls.then((res) => {
const message = {
from: "from-email",
to: "to-email",
subject: "test",
html: `<h1>Following URLs have issues:</h1>
<p>${res.join(", ")}</p>`,
};
console.log(res, "---", message);
transporter.sendMail(message, function (err, info) {
if (err) {
console.log(err);
} else {
console.log(info);
}
});
});
};
runNodeMailer();
If I understand your question well, than you should check res that you get from returnListOfUrls and based on that decide what message you are sending.
Code would look like this:
const runNodeMailer = () => {
returnListOfUrls.then((res) => {
let htmlMessage = ''
if(res.length > 0) {
htmlMessage = `<h1>Following URLs have issues:</h1>
<p>${res.join(", ")}</p>`
} else {
htmlMessage = `<h1>You have no issues with urls</h1>` }
const message = {
from: "from-email",
to: "to-email",
subject: "test",
html: htmlMessage,
};
console.log(res, "---", message);
transporter.sendMail(message, function (err, info) {
if (err) {
console.log(err);
} else {
console.log(info);
}
});
});
};
Or if you don't want to send any message, than do:
if(res.length > 0) {
htmlMessage = `<h1>Following URLs have issues:</h1>
<p>${res.join(", ")}</p>`
} else {
return
}

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 to pull string from javascript file with promises?

I have a node.js app that has a few files that I am working with, but the main two javascript files are a RestController and AuthController. The RestController is supposed to call the AuthController to pull a new access token from Salesforce, the server that I am attempting to hit.
I currently set up my AuthController.js to work with promises so that I can wait to get my access token. The problem is I have no idea how to get my RestController.js file to wait for the access token from the AuthController.js file.
I am also very very new to Javascript and Promises, so I am not sure if I even set up my functions correctly. Basically, I want my AuthController to handle getting the access token and the RestController to handle the Rest request to our server.
AuthController.js
var fs = require('fs');
var jwt = require('jsonwebtoken');
var request = require('request');
var querystring = require('querystring');
var config = require('../../configs/config.json');
var filename = __dirname + '/../../' + config.key_path;
var access_token;
var readFilePromise = function(file) {
return new Promise(function(ok, notOk) {
fs.readFile(file, function(err,data) {
if (err) {
notOk(err);
} else {
ok(data);
}
});
});
}
var getAccessToken = function(key) {
return new Promise(function(ok,notOk) {
var jwtparams = {
iss : config.client_id,
sub: config.username,
aud: 'https://' + config.host,
exp : Date.now() + 300
};
var token = jwt.sign(jwtparams, key, {algorithm: 'RS256'});
var data = querystring.stringify({
grant_type : 'urn:ietf:params:oauth:grant-type:jwt-bearer',
assertion : token
});
request.post({
headers: {
'Content-Type' : 'application/x-www-form-urlencoded',
'Content-Length' : data.length
},
url: 'https://' + config.host + '/services/oauth2/token',
body: data
}, function(error, response, body) {
if (error) {
return notOk(error);
}
try {
ok(JSON.parse(body).access_token);
} catch (e) {
notOk(e);
}
});
});
}
function main() {
readFilePromise(filename).then(function(data) {
getAccessToken(data.toString()).then(function(data) {
access_token = data.toString();
});
});
}
module.exports = {main};
RestController.js
var https = require('https');
var request = require('request');
var auth = require('./authController.js');
class SystemController {
doProcessPostStatus (req,res) {
if (!req.body.systemId) {
return res.status(400).send([
{
'errorCode' : 'INVALID_REQUEST_BODY',
'message' : 'System Id "systemId" variable is required.'
}
]);
} else if (typeof req.body.success === 'undefined') {
return res.status(400).send([
{
'errorCode' : 'INVALID_REQUEST_BODY',
'message' : 'Success "success" variable is required'
}
]);
} else if (!req.body.message) {
return res.status(400).send([
{
'errorCode' : 'INVALID_REQUEST_BODY',
'message' : 'Message "message" variable is required'
}
]);
}
var access_token = auth.main();
console.log(access_token);
}
}
var systemControllerVar = new SystemController();
module.exports = systemControllerVar;
Any help is greatly appreciated as I am currently stuck, thanks!

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!

Sending emails from node server fails when using forever

I have an API server running with Node and the following add user function:
add: function (userArray, onSuccess, onError) {
userArray.forEach(function (user) {
var length = 8,
charset = "abcdefghijklnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
retVal = "";
for (var i = 0, n = charset.length; i < length; ++i) {
retVal += charset.charAt(Math.floor(Math.random() * n));
}
var password = retVal;
var salt = bcrypt.genSaltSync(10);
var password = bcrypt.hashSync(password, salt);
user.user_type_id = user.user_type.id;
if (user.title) {
user.title_id = user.title.id;
}
user.division_id = user.division.id;
user.password = password;
user.user_password = retVal;
user.image_path = 'img/AdamProfil.png';
});
emailTemplates(templatesDir, function (err, template) {
if (err) {
console.log(err);
} else {
var transportBatch = nodemailer.createTransport(smtpTransport({
host: 'smtp.mail.dk',
secureConnection: true,
port: 587,
tls: {
rejectUnauthorized: false
},
auth: {
user: 'my#mail.com',
pass: 'myPassword'
}
}));
var Render = function(locals) {
this.locals = locals;
this.send = function(err, html, text) {
if (err) {
console.log(err);
} else {
transportBatch.sendMail({
from: '*** <support#mymail.dk>',
to: locals.username,
subject: 'Din adgangskode til ***!',
html: html,
// generateTextFromHTML: true,
text: text
}, function(err, responseStatus) {
if (err) {
console.log(err);
} else {
console.log(responseStatus.message);
}
});
}
};
this.batch = function(batch) {
batch(this.locals, templatesDir, this.send);
};
};
// Send multiple emails
template('password', true, function(err, batch) {
for(var user in userArray) {
var render = new Render(userArray[user]);
render.batch(batch);
}
});
}
});
userArray.forEach(function(user){
User.create(user)
.then(function(createdUser) {
user.profile.user_id = createdUser[null];
Profile.create(user.profile);
});
});
onSuccess(userArray);
}
Now when i run my server.js file using the console writing node server.js and run this function it correctly sends an email to the target (SUCCESS!?) no because when i run this with forever start server.js and run the exact same function with the exact same parameters no email is sent.
What the hell is going on?:)
Looking at your code only, I see a templatesDir variable. I'd guess that is different, or changing in an unexpected way, when you run with forever.
Check out this issue at forever. Do you ever reference an absolute path, or process.cwd()?
Worth a try, good luck!

Categories