Nodejs function is working only once - javascript

I have a function called UpdateDocument.js and I have to run this function when I do request. It's only running once. After first request, it's not updating document. I have to refresh page but this is not why I want.
I'm requesting from client side and running function in server side.
socket.emit('UpdateDocumentRequest', ....);
UpdateDocument.js :
var users = require('./datas/user');
exports.UpdateDocument = function(app, passport, io) {
io.on('connection', function(socket){
socket.on('UpdateDocumentRequest', function(data) {
//console.log(data);
socket.emit('UpdateDocumentRequest__return', { last_balance: last_balance });
var query = {....};
users.update(query, { ...}, function (err, statu) {
});
});
}
In server.js
UpdateDocument.UpdateDocument(app, passport, io);
Console :
As you can see, they have different dates.
{ user: '',
btc_balance: '0.00008630',
betAmount: '0.00000002',
betPayout: '2',
betProfit: '0.00000002',
betTime: '2014-08-24T05:17:45.328Z' }
{ user: '',
btc_balance: '0.00008630',
betAmount: '0.00000002',
betPayout: '2',
betProfit: '0.00000002',
betTime: '2014-08-24T05:17:47.225Z' }
{ user: '',
btc_balance: '0.00008630',
betAmount: '0.00000002',
betPayout: '2',
betProfit: '0.00000002',
betTime: '2014-08-24T05:17:49.871Z' }

Related

How can I pass an error message from the server backend to vue frontend

I am working on error handling for an application built in Vue/Vuetify. I am using external pagination for a datatable that links to an API that only allows so many hits in a period of time. Because of that, I'm trying to pass through and display an error of "Too Many Requests" on the front end for users when they hit that limit.
The issue I'm having though is passing that error from the backend server to the frontend. When it errors on the front end, it just gives a 500 error. However, the server log is giving me the actual error happening. How can I get that to pass? Below is the relevant javascript code from the server and the front end.
For note: I've been using eventbus to display errors throughout the project. But up until now, I haven't had to pass any from the back to front.
Backend Server
module.exports = {
async find(ctx) {
var page = ctx.query.page;
var key = '';
var locale = ({ location: '', location_type: '', page: page });
const sdk = require('api')('#');
try {
var response = await sdk.auth(key)['grants_funders'](locale);
}
catch (err) {
console.log(err);
}
;
// .then(res => console.log(res))
// .catch(err => console.error(err));
// console.log(response);
return response
}
};
FRONTEND
export default {
name: "Search",
components: {},
props: ["funderDirectories", "serverItemsLength"],
data() {
return {
page: 1,
usericon: usericon,
greentick: greentick,
listicon: listicon,
training: training,
keyword: null,
funderHeaders: [
{ text: "Organization", value: "funder_name" },
{ text: "City", value: "funder_city" },
{ text: "Country", value: "funder_country" },
{ text: "Count", value: "grant_count" },
],
myloadingvariable: false,
pageCount: 1,
itemsPerPage: 25,
};
},
watch: {
page() {
Vue.$funderService.find({ page: this.page }).then((res) => {
this.funderDirectories = res.data.rows;
this.serverItemsLength = res.data.total_hits;
});
},
},
methods: {},
computed: {
filteredFunderDirectories() {
if (!this.keyword) {
return this.funderDirectories;
}
return this.funderDirectories.filter(
(q) =>
q.funder_name.toLowerCase().indexOf(this.keyword.toLowerCase()) !== -1
);
},
},
};
Ultimately figured it out. added the following to the backend catch
return ctx.send({errorStatus:"Too Many Requests. Please Wait"},429)
And I was able to call

Use functions inside of page-object commands in Nightwatch

Ignore the placement of the selectUser function. I'm still trying to play around with it. How can I use functions inside of the page-object commands? Before that function was repeated 5 times inside each command function, but for cleanliness, that obviously needed to be changed, I just can't figure out how.
Page-object snippet:
var selectUser = function(userName, password) {
return this.waitForElementVisible('#usernameField')
.setValue('#usernameField', userName)
.setValue('#passwordField', password)
.click('#signOnButton')
.waitForElementVisible('#eventTaskManager');
};
module.exports = {
elements: {
usernameField: '#UserName',
passwordField: '#Password',
signOnButton: 'input[value="Sign On"]',
cancelButton: 'a[href$="/cancel"]',
errorMessage: '.icon-warning',
eventTaskManager: '.concierge'
},
commands: [{
signInAsUniregisteredUser: function() {
selectUser(unregisteredUserName, unregisteredUserPass);
},
signInAsRegisteredUser: function() {
selectUser(registeredUserName, prodRegisteredPass);
},
signInAsUnregisteredUser_Regression: function() {
selectUser(unregisteredUserName, unregisteredUserPass);
},
signInAsRegisteredUser_Regression: function() {
selectUser(registeredUserName, prodRegisteredPass);
},
signInAsRegisteredUser_Production: function() {
selectUser(prodRegisteredUser, prodRegisteredPass);
}
}]
};
First at all, for login feature, there are only 2 assertions which are login "ok" or login "fail" (unregistered,wrong credentials,missing username,...), so you only need this for page object.
var pageCommands = {
tryToLogin: function(userName, password) {
return this.waitForElementVisible('#usernameField')
.setValue('#usernameField', userName)
.setValue('#passwordField', password)
.click('#signOnButton');
},
assertLoginSuccesfully: function() {
return this.waitForElementVisible('#eventTaskManager'); // login pass
},
assertLoginUnSuccesfully: function() {
return this.waitForElementVisible('#errorMessage'); // login fail
}
};
module.exports = {
elements: {
usernameField: '#UserName',
passwordField: '#Password',
signOnButton: 'input[value="Sign On"]',
cancelButton: 'a[href$="/cancel"]',
errorMessage: '.icon-warning',
eventTaskManager: '.concierge'
},
commands: [pageCommands],
};
And in your test cases :
const loginPage = browser.page.login();
const dataForTest = require('./data.json');
const credentials = {
username : dataForTest.username ,
password : dataForTest.password
};
login.tryToLogin(credentials.username,credentials.password)
.assertLoginSuccesfully() // if data from dataForTest is correct
This practice will keep you stay away of hard values by storing every thing in data.json (or anything you want).

Getting old records from Sails Models

Im actually trying to build up a complete chat with Sails.js websockets but im facing some troubles.
I succeed to send and get new messages when a new client connect to the chat but i would new client to get the older messages (like the 20 last messages sent in the chat).
Message.js (Model)
module.exports = {
attributes: {
name : { type: 'string' },
message : { type: 'string' }
}
};
MessageController.js (Controller)
module.exports = {
new: function(req, res) {
var data = {
name: req.param('name'),
message: req.param('message'),
};
Message.create(data).exec(function created(err, message){
Message.publishCreate({id: message.id, name: message.name, message: message.message});
});
},
subscribe: function(req, res) {
Message.watch(req);
}
};
I had an idea about using the "find" function on my Model but not really conclusive.
I hope im not missing something big about Sails possibilities !
Need your help :) Thanks !
Message.find({sort: 'createdAt ASC'}).exec(function(err, results) {
//results is an array of messages
});
http://sailsjs.org/documentation/concepts/models-and-orm/query-language
I added this code to my subscribe function but i don't receive anything on my client side listening on('message')
/* Get the last 5 messages */
Message.find({sort: 'createdAt DESC'}).limit(5).exec(function(err, messages) {
for (var i = 0; i < messages.length; i++) {
sails.sockets.broadcast(req.socket, 'message', messages[i]);
}
});

How to execute Orientdb server side function from Orientjs?

I am using Orientjs to access a Orientdb database from a nodejs script, but the server side function does not effect the database.
Server side script:
This Javascript function addTxt() takes the argument author and text
var db = orient.getGraph();
db.command('sql','insert into Message (author, text) VALUES ("'+author+'", "'+text+'")');
return "1";
Query: This function has been tested in Orient Studio and the following query works:
SELECT addTxt("Testuser","foo")
Nodejs/Orientjs: When invoking this function from a nodejs script using Orientjs, it only returns
[ { '#type': 'd', addTxt: '1', '#rid': { cluster: -2, position: 1 } } ]
and the database remains untouched.
I have tried:
//some code
var OrientDB = require('orientjs');
var server = OrientDB({
host: 'localhost',
port: 2424,
});
var db = server.use({
name: 'database',
username: 'admin',
password: 'pass'
db.query('SELECT addTxt(:arg1, :arg2)', {
params: {arg1:"Testuser",arg2:"foo"}
}).then(function (response){
console.log(response);
});
Other queries from Orientjs works.
What am I doing wrong? Is there an other way to invoke a server side function?
You explicit returns "1"
it is right that returns
[ { '#type': 'd', addTxt: '1', '#rid': { cluster: -2, position: 1 } } ]
try to directly explicit the commit in your function
db.commit()

Web FTP Portal Logins

I have a web ftp portal that was created a few years ago by a developer that is no longer around. The code for the website is written in Node.js. Inside of app.js is the following code:
var validUsers = [{
name:'x',
user:'907c78ef73998eafc2680e5fdd4798a8eef0881a',
pass:'95489cf3039eb2f5938e3daa954d04276bbf90e7',
dir:''
},{
name:'y',
user:'b26e5ebda152e81099ec78be2f9c191ee25e1cd6',
pass:'e3725873ae302e3f12eb97b02feb7457de9706c2',
dir:'y'
},{
name:'y2',
user:'3182b54d9f4d08641b5a9a0fb33f74df5d76b222',
pass:'916b2e1941c9e23610f8bd3462cdb19f55b5c631',
dir:'y2'
},{
name:'y3',
user:'38aa53de31c04bcfae9163cc23b7963ed9cf90f7',
pass:'7a98cf84c2c61a30f6c4e3984c0cad2eb29f5d6f',
dir:'y3'
},{
name:'y4',
user:'51e822c50cc62cdbdb850a439ea75b6d45ac487b',
pass:'da6a77293ddcdc7047dd461a94c88c8377753265',
dir:'y4'
},{
name:'y5',
user:'14ad0aca26e00f615990946181ee3405c6ede0f1',
pass:'4eb4e0e1ea0f04422b5bc6031ee37c8dc971236d',
dir:'y5'
},{
name:'y6',
user:'4ec9bdb28c5da0f9813e9eed55a0f1dc6217a305',
pass:'e72bd0bbd37423bb0c9b9edfb9ce94446161c511',
dir:'y6'
},{
name:'y7',
user:'f4603bd4ae9e4aa2a11d903d0b178b37a57b1bac',
pass:'8a6a67f235738c4b2e4f88d4608bdcf0bbc49f51',
dir:'y7'
},{
name:'Guest',
user:'35675e68f4b5af7b995d9205ad0fc43842f16450',
pass:'370bb444ef91a3999b1c36af97e166f18848e7b7',
dir:'Guest'
},{
name:'y8',
user:'d8f51fbf5e13e9f2637a8d5c4bd1ab251bd61c30',
pass:'1a047e6dd554ffdd67524916820a8fa23acd2c6e',
dir:'y8'
}];
The x and y1-8 are substitutions for the actual client names and corresponding directories. Example being the 'Guest' name and directory. My question is, the user and pass are hash values from crypto. Yet they result in specific usernames and passwords. If I wanted to reset a username or password, or add another. How would I figure out the corresponding hash value to add to the code based on the username/password strings I want to add.
Any input would be very helpful.
EDIT:
The rest of the FTP code:
app.get('/ftp/', function(req, res){
var pageName = 'File Transfer Portal';
var rNav = '',
sNav = '',
cNav = '',
imNav = '',
title = 'companyNameOmitted: '+pageName,
bodyClass = 'top ftp',
keywords = 'keywordsOmitted',
description = 'descriptionOmiited',
url = '/ftp/';
res.render('ftp', {
title: title,
bodyClass: bodyClass,
keywords: keywords,
description: description,
url: siteRoot+url,
pageEmail: 'mailto:?subject='+escape(title)+'&body='+escape(description)+'%0A'+siteRoot+url,
eUrl:escape(siteRoot+url),
eTitle:escape(title),
eDescription:escape(description),
rNav:rNav,
sNav:sNav,
cNav:cNav,
imNav:imNav});
//console.log(uniqId()+':'+pageName);
});
app.post('/ftp/upload', function(req, res){
//console.log(req.files);
var SID = req.cookies.SID;
var sessionUser = (users[SID]) ? users[SID] : false;
if (!!sessionUser){
_.each(req.files,function (file) {
console.log(new Date(curTime()).toGMTString()+' | Recieved '+file.name+' ('+file.size+' bytes) from '+sessionUser.name);
var newPath = __dirname + '/complete/'+_.where(validUsers,{user:sessionUser.user})[0].dir+'/'+file.name;
fs.rename(file.path,newPath,function(err) {
if (err) throw err;
else {
res.redirect('back');
if (sessionUser.name != 'adminOmitted') {
var htmlString = '<b>'+sessionUser.name+'</b> has uploaded a file <b>'+file.name+'</b>.<br /><br />View it on the File Transfer Portal.';
var transport = nodemailer.createTransport("SMTP",{
host: "hostname.com", // hostname
secureConnection: true, // use SSL
port: 465, // port for secure SMTP
auth: {
user: "user#host.com",
pass: "pass"
}
});
transport.sendMail({
sender:'sender#host.com',
to:'receiver#host.com',
subject:'File Upload: '+sessionUser.name+' uploaded '+file.name,
html: htmlString
},function(err) {
if (err) console.log(err);
else console.log('Notification Sent: S&A File Upload: '+sessionUser.name+' uploaded '+file.name);
});
}
}
});
And the login code...
app.get('/ftp/d/:hash/:filename', function(req, res){
var SID = req.cookies.SID;
var ip = req.ip;
//console.log(ip);
var sessionUser = (users[SID]) ? ((users[SID].md5==req.params.hash)&&(users[SID].ip==ip)) ? users[SID] : false : false;
if (sessionUser) {
var realpath = __dirname +'/complete/'+_.where(validUsers,{user:sessionUser.user})[0].dir+'/'+req.params.filename.replace('>','/');
console.log(new Date(curTime()).toGMTString()+' | Sending '+realpath.substr(realpath.indexOf('complete')+9)+' to '+sessionUser.name);
res.download(realpath,realpath.substr(realpath.lastIndexOf('/')+1),function(err){
if (err) {
res.redirect(302,'/ftp/');
throw (err);
}
});
} else {
console.log(new Date(curTime()).toGMTString()+' | Download request failed authorization for '+req.params.filename);
console.log(new Date(curTime()).toGMTString()+' | Hash: '+req.params.hash);
console.log(new Date(curTime()).toGMTString()+' | SID: '+req.cookies.SID);
res.redirect(302,'/ftp/');
}
});
sio.sockets.on('connection', function (socket) {
var SID = socket.handshake.SID;
if (!users[SID]) register(SID,socket.handshake.address.address);
//console.log(users);
socket.on('login',function(data) {
var thisUser = _.where(validUsers,{user:data.u,pass:data.p})[0];
if (_.isEmpty(thisUser)) {
if (!!users[SID].ip) {
console.log(new Date(curTime()).toGMTString()+' | '+users[SID].ip+' has failed logging in.');
console.log(new Date(curTime()).toGMTString()+' | '+'U:'+data.u);
console.log(new Date(curTime()).toGMTString()+' | '+'P:'+data.p);
}
socket.emit('login',{complete:false,name:false});
} else {
console.log(new Date(curTime()).toGMTString()+' | '+thisUser.name+' has logged in.');
users[SID].name = thisUser.name;
users[SID].user = thisUser.user;
socket.emit('login',{complete:true,name:thisUser.name});
}
});
And the disconnect function, the only code between the login and the disconnect functions are a move file and a delete file function which I doubt are of any use.
//console.log(users);
socket.on('disconnect',function() {
setTimeout(function() {
if (!!users[SID]) {
if (curTime()-users[SID].lastTap>30000)
unregister(SID);
else console.log('Not removing; connection still active. ('+users[SID].name+')');
} else (unregister(SID));
},30000);
});
});
and finally, the crypto functions:
function getMD5(string) {
return crypto.
createHash('md5').
update(string).
digest("hex");
}
function getSHA1(string) {
return crypto.
createHash('sha1').
update(string).
digest("hex");
}
I know the formatting isn't perfect, I've tried to keep it as neat as possible, I think that's all of the relevant functions. I doubt the .jade file for the FTP Portal would be of any use.
You can't.
The usernames and passwords have been put through an asymmetric encryption (ie MD5). This was likely done to protect the user's personal information if the server is hacked.
You're still missing the part of the code that handles the authentication and sets the session cookie.
If you can find the code that handles the auth and you know the username beforehand you could re-hash it to cross-reference the username to the entries list.
Otherwise, your only option is to crack the usernames/passwords which can be difficult/impossible depending on their complexity.
Good luck...

Categories

Resources