Can I use busboy with passport.js? - express

I'm using FormData() in my React app. I was going to use it for registration and login too. I have a working passport.js registration piece of code and was going to use it with busboy but it looks like it reads fields one by one whenever there is one and it seems like I can't use it with Account.register.
I've inserted Account.register in busboy.on('field') but then realized it won't work. I didn't change req.body.username etc in my original code, ignore them.
busboy.on('field', function(fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) {
console.log('Field [' + fieldname + ']: value: ' + inspect(val));
Account.register(new Account({ nickname: req.body.username, email: req.body.email }), req.body.passwordOne, (err, user) => {
if(err){
helpers.errors(err, res);
} else {
helpers.registerSuccess(res);
}
});
});
busboy.on('finish', function() {
console.log('Done parsing form!');
//res.writeHead(303, { Connection: 'close', Location: '/' });
res.end();
});

I'm using nickname instead of username in passport.js because I'm using email as the username field. Working code:
router.post('/register', (req, res, next)=>{
var busboy = new Busboy({ headers: req.headers });
let nickname = '';
let email = '';
let password = '';
busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
console.log('File [' + fieldname + ']: filename: ' + filename + ', encoding: ' + encoding + ', mimetype: ' + mimetype);
file.on('data', function(data) {
console.log('File [' + fieldname + '] got ' + data.length + ' bytes');
});
file.on('end', function() {
console.log('File [' + fieldname + '] Finished');
});
});
busboy.on('field', function(fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) {
console.log('Field [' + fieldname + ']: value: ' + inspect(val));
if(fieldname == 'username') { nickname = val; }
if(fieldname == 'email') { email = val; }
if(fieldname == 'password') { password = val; }
});
busboy.on('finish', function() {
console.log('Done parsing form!');
console.log('email: ' + email + 'password: ' + password + 'username: ' + nickname);
Account.register(new Account({ nickname: nickname, email: email }), password, (err, user) => {
if(err){
helpers.errors(err, res);
} else {
helpers.registerSuccess(res);
}
});
});
req.pipe(busboy);
});

Related

Cant send image upload and use token bearer authentication with axios

let url = this.globalAPIBaseUrl + 'program/' + this.tmsID + '/updateposters/?posterType=' + imageType;
let j = [{
posterType: imageType,
url: imageUrl
}];
axios.patch(url, {
headers: {
Authorization: 'Bearer ' + localStorage.getItem('accessToken')
}
}, j, {
onUploadProgress: progressEvent => {
this.basic.status = 'Uploaded: ' + progressEvent.loaded + 'b of ' + progressEvent.total + 'b'
}
}).then(response => (this.handleUploadComplete(response)));
before i put in the "headers" is worked fine, and when i use the same auth headers, but no "j" data variable elsewhere it also works fine.
Any advice, i'm kinda new here with axios. (this is in vue2.js btw)
data should be the second parameter, and the third parameter is config object, where you can set headers and onUploadProgress callback
axios.patch(url, j, {
headers: {
Authorization: 'Bearer ' + localStorage.getItem('accessToken')
},
onUploadProgress: progressEvent => {
this.basic.status = 'Uploaded: ' + progressEvent.loaded + 'b of ' + progressEvent.total + 'b'
}
}).then(response => (this.handleUploadComplete(response)));

Vue js, cant pass data

I have simple deposit calc. Here is the code.
app.js:
el: '#calcbox',
data: {
newCalc: {
summ: '50000',
currency: 'USD',
duration: '',
percents: '',
},
calcResult: '',
},
computed: {
percents() {
var id = $("#deposit_id").val();
var url = "/get_percent/"+ id + '/' + this.newCalc.currency + '/' + this.newCalc.duration;
this.$http.get(url, function(response){
return this.newCalc.percents = response;
});
},
calcResult() {
var deposit_id = $("#deposit_id").val();
var url = "/api/calc/"+ deposit_id + '/' + this.newCalc.summ + '/' + this.newCalc.currency + '/' + this.newCalc.duration;
this.$http.get(url, function(response){
return this.calcResult = response;
});
}
},
frontend:
<span>#{{newCalc.percents}}%:</span>
<span>#{{calcResult}}:</span>
So the problem is that result isn't appears in frontend, console.log shows the correct result.
Percentage value is showing well.
calcResult() {
var deposit_id = $("#deposit_id").val();
var url = "/api/calc/"+ deposit_id + '/' + this.newCalc.summ + '/' + this.newCalc.currency + '/' + this.newCalc.duration;
this.$http.get(url, function(response){
return this.calcResult = response;
});
}
add .bind(this)
calcResult() {
var deposit_id = $("#deposit_id").val();
var url = "/api/calc/"+ deposit_id + '/' + this.newCalc.summ + '/' + this.newCalc.currency + '/' + this.newCalc.duration;
this.$http.get(url, function(response){
return this.calcResult = response;
}.bind(this));
}
Or use fat arrow notation since you're using ES6 syntax
calcResult() {
var deposit_id = $("#deposit_id").val();
var url = "/api/calc/"+ deposit_id + '/' + this.newCalc.summ + '/' + this.newCalc.currency + '/' + this.newCalc.duration;
this.$http.get(url, response => {
return this.calcResult = response;
});
}
the this in the .then callback is not the same context as the one outside or within your vue method

Render HTML with images using PhantomJS

I am trying to create a PDF from HTML text using PhantomJS (version 1.9.7). I've written a very simple script (made more complicated by error callbacks etc.)
phantom.onError = function(msg, trace) {
var msgStack = ['PHANTOM ERROR: ' + msg];
if (trace && trace.length) {
msgStack.push('TRACE:');
trace.forEach(function(t) {
msgStack.push(' -> ' + (t.file || t.sourceURL) + ': ' + t.line + (t.function ? ' (in function ' + t.function + ')' : ''));
});
}
system.stdout.write(msgStack.join('\n'));
phantom.exit(1);
};
var page = require('webpage').create();
page.viewportSize = { width: 800, height: 600 };
page.paperSize = { format: 'A4', orientation: 'portrait', margin: '1cm' };
page.onResourceRequested = function(requestData, networkRequest) {
console.log('Request (#' + requestData.id + '): ' + JSON.stringify(requestData));
};
page.onResourceReceived = function(response) {
console.log('Response (#' + response.id + ', stage "' + response.stage + '"): ' + JSON.stringify(response));
};
page.onResourceError = function(resourceError) {
console.log('Unable to load resource (#' + resourceError.id + 'URL:' + resourceError.url + ')');
console.log('Error code: ' + resourceError.errorCode + '. Description: ' + resourceError.errorString);
};
page.onError = function(msg, trace) {
var msgStack = ['ERROR: ' + msg];
if (trace && trace.length) {
msgStack.push('TRACE:');
trace.forEach(function(t) {
msgStack.push(' -> ' + t.file + ': ' + t.line + (t.function ? ' (in function "' + t.function + '")' : ''));
});
}
console.error(msgStack.join('\n'));
};
page.content = "<html><body><b>test</b><img src=\"http://www.google.co.uk/images/srpr/logo11w.png\" alt=\"\" border=\"0\" /></body></html>";
page.render('tmp.pdf');
setTimeout(function() {
phantom.exit();
}, 5000);
I set up the page, assign the simple HTML string to the content property and render it to a PDF.
This script doesn't produce any output.
I've narrowed the problem down to the <img> element, when that is removed a PDF is generated as expected. I can see from the callback functions that the image is requested, a response is received, and there are no errors reported. I've tried rendering to a PNG which also yields no output.
I've explored the possibility of this being a proxy issue, however the raserize.js example works without any problems.
You have to call render when the page is fully loaded. Remember that loading a page via page.open or page.content is always async.
Change your code to this
page.content = "<html><body><b>test</b><img src=\"http://www.google.co.uk/images/srpr/logo11w.png\" alt=\"\" border=\"0\" /></body></html>";
setTimeout(function() {
page.render('tmp.pdf');
phantom.exit();
}, 5000);

Can I get the failed request id when PhantomJS get resource error?

I don't quite understand why PhantomJS only returns the url of request for onResourceError callback, while for the other two resource callbacks it returns the request id. That makes "finding which request did actually fail" really impossible if there is more than one request to the same url. Does anyone knows how to get the failed request id?
Actually, that's just old documentation. onResourceError has the id of a failed request.
page.onResourceError = function(resourceError) {
console.log('Unable to load resource (request ID:' + resourceError.id + 'URL:' + resourceError.url + ')');
console.log('Error code: ' + resourceError.errorCode + '. Description: ' + resourceError.errorString);
};
Why do you really need to request id ?
Since onResourceError was added in 1.9, some information may be missing.
A way to resolve your problem is to keep in an array all requested resourcessuach as in netsniff example.
Here is a very basic implementation :
var page = require('webpage').create(),
system = require('system');
if (system.args.length === 1) {
console.log('Usage: netsniff.js <some URL>');
phantom.exit(1);
} else {
page.address = system.args[1];
page.resources = [];
page.onLoadStarted = function () {
page.startTime = new Date();
};
page.onResourceRequested = function (req) {
page.resources[req.id] = {
request: req,
startReply: null,
endReply: null
};
};
page.onResourceReceived = function (res) {
if (res.stage === 'start') {
page.resources[res.id].startReply = res;
}
if (res.stage === 'end') {
page.resources[res.id].endReply = res;
}
};
page.onResourceError = function(resourceError) {
console.log('Unable to load resource (URL:' + resourceError.url + ')');
console.log('Error code: ' + resourceError.errorCode + '. Description: ' + resourceError.errorString);
page.resources.forEach(function (resource) {
var request = resource.request,
endReply = resource.endReply;
if (request && request.url === resourceError.url && !endReply) {
console.log('request id was :' + request.id);
}
})
};
page.open(page.address, function (status) {
var har;
if (status !== 'success') {
console.log('FAIL to load the address');
phantom.exit(1);
} else {
page.endTime = new Date();
page.title = page.evaluate(function () {
return document.title;
});
console.log(page.title);
phantom.exit();
}
});
}
onResourceError, you just need to find first/last/all recorded urls that match the error resource url.

How to use Haraka librairy

Can someone helps me with some example using haraka librairy?
We use Haraka as our application mail server. We have written a simple plugin which takes any incoming mail and post it to our application web server.
Here is the plugin script. Just save it to a file do the necessary name changes and add the path to Harakas config/plugins file.
var
fs = require('fs'),
query_string = require('querystring'),
logger = require('./logger'),
DROP_DIRECTORY_PATH = '/path/haraka/drop/',
RETRY_DIRECTORY_PATH = '/path/haraka/retry/',
HOST_NAME = 'this_haraka_servers_name';
exports.hook_queue = function (next, connection, params) {
'use strict';
function haraka_log(function_name_in, section_in, text_in) {
var log_text = '[HttpMail]';
log_text += ' [' + function_name_in + ']';
log_text += ' [' + section_in + ']';
log_text += ' ' + text_in;
logger.lognotice(log_text);
}//function haraka_log
function move_file(filename_in) {
fs.rename(DROP_DIRECTORY_PATH + filename_in, RETRY_DIRECTORY_PATH + filename_in, function (err) {
if (err) {
//throw err;
haraka_log('move_file', 'fs.rename ... failed', filename_in + '\n' + JSON.stringify(err));
} else {
haraka_log('move_file', 'fs.rename ... success', filename_in);
}
});
}//function move_file
function delete_file(filename_in) {
fs.unlink(DROP_DIRECTORY_PATH + filename_in, function (err) {
if (err) {
//throw err;
haraka_log('delete_file', 'fs.unlink ... failed', filename_in + '\n' + JSON.stringify(err));
} else {
haraka_log('delete_file', 'fs.unlink ... success', filename_in);
}
});
}//function delete_file
function http_post_file(filename_in) {
var
http = require('http'),
post_options = {
host: 'my.server.com',
port: 80,
path: '/http_mail/' + HOST_NAME + '?' + query_string.stringify({FileName: filename_in}),
method: 'POST',
headers: {'Content-Type': 'text/plain'}
},
post_request,
read_stream;
haraka_log('http_post_file', 'Before http.request', filename_in);
post_request = http.request(post_options, function (post_response) {
haraka_log('http_post_file', 'post_response', ' post_response.statusCode = ' + post_response.statusCode + ' : ' + filename_in);
if (post_response.statusCode === 200) {
delete_file(filename_in);
} else {
move_file(filename_in);//Posted later by retry script;
}
post_response.resume();
});//post_request = http.request(post_options, function(post_response) {
post_request.on('error', function (err) {
haraka_log('http_post_file post_request.on(\'error\' ...)', err.message, filename_in);
move_file(filename_in);
});//post_request.on('error', function(err) {
read_stream = fs.createReadStream(DROP_DIRECTORY_PATH + filename_in);
read_stream.pipe(post_request);
}//function http_post_file
var
x_sender = connection.transaction.mail_from,
x_receiver_list = connection.transaction.rcpt_to,
filename = x_sender + '_' + new Date().toISOString() + '_' + connection.uuid,
writeStream;
filename = filename.replace(/\//g, '');
connection.transaction.add_header('x-sender', x_sender.toString());
x_receiver_list.forEach(function (value) {
connection.transaction.add_header('x-receiver', value.toString());
});
haraka_log('main', 'filename', filename);
writeStream = fs.createWriteStream(DROP_DIRECTORY_PATH + filename);
//connection.transaction.message_stream.pipe(writeStream, {dot_stuffing: true, ending_dot: true});
connection.transaction.message_stream.pipe(writeStream, {dot_stuffing: true});
writeStream.on("close", function () {
haraka_log('main writeStream.on("close"...', 'File Saved!', filename);
http_post_file(filename);
next(OK);
});//writeStream.on("close", function()
};//exports.hook_queue = function(next, connection, params) {