I am completely new to authentication concepts. The goal is to upload files to box using box-node-sdk (a node pacakge), I was advised to do Oauth with JWT to box in-order to manage my application data on box. But I keep keep getting the following error
err: Error: error:0906D06C:PEM routines:PEM_read_bio:no start line
Following is the code in my back-end. Please help me in learning and understanding this.
All my keys are coming from env.
var BoxSDK = require('box-node-sdk');
var sdk = new BoxSDK({
clientID: process.env.BOX_CLIENT_ID,
clientSecret: process.env.BOX_CLIENT_SECRET,
appAuth: {
keyID: process.env.BOX_PUBLIC_KEY_ID,
privateKey: process.env.BOX_PRIVATE_KEY,
passphrase: process.env.BOX_PASSPHRASE,
expirationTime: 60,
verifyTimestamp: false,
},
enterpriseID: process.env.BOX_ENTERPRISE_ID
});
var fs = require('fs');
var path = require('path');
// Get an app user client
var client = sdk.getAppAuthClient('user', process.env.BOX_APP_USER_ID);
var fileData = fs.createReadStream('hello_world.png')
client.files.uploadFile('71331215581', 'hello_world.png', fileData,
function(err, file) {
if (err) {
console.log('err: ' + err);
} else {
console.log('file uploaded: ' + file);
}
})
Related
I am trying to get a file from html form and store it in another folder. It's basically cloud function, and I am new to both node.js and firebase so don't know what I am doing wrong. What I manage to do is:
const fileMiddleware = require('express-multipart-file-parser');
app.post("/sendMail", (req, res) => {
const {
fieldname,
filename,
encoding,
mimetype,
buffer,
} = req.files[0];
console.log(req.files[0].originalname);
var fs = require('fs')
var oldPath = req.files[0].originalname;
var newPath = '/functions/'+oldPath;
fs.rename(oldPath, newPath, function (err) {
if (err) throw err
console.log('Successfully renamed - AKA moved!')
});
});
Whenever I try to move file, I got path issues. The error is as follows:
[Error: ENOENT: no such file or directory, rename 'C:\Users\Maisum Abbas\now\functions\sendMail.txt'
> 'C:\functions\sendMail.txt'] {
> errno: -4058,
> code: 'ENOENT',
> syscall: 'rename',
> path: 'C:\\Users\\Maisum Abbas\\now\\functions\\sendMail.txt',
> dest: 'C:\\functions\\sendMail.txt'
> }
Also, this is the path where I want to actually move the file but oldpath is already setup like this.
C:\Users\Maisum Abbas\now\functions\sendMail.txt
Since I needed to attach a file with email, it was causing path issues. I tried it with multer and it works. What I did:
//call libraries here
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, 'resume/');
},
filename: function (req, file, callback) {
callback(null, file.fieldname + '-' + Date.now());
}
});
var upload = multer({ storage : storage}).single('filetoupload');
app.post("/careerMail", (req, res) => {
const { name } = req.body;
const { email } = req.body;
const { phone } = req.body;
upload(req,res,function(err) {
if(err) {
return res.end("Error uploading file.");
}
});
const dest = 'mymail';
const mailOptions = {
from: email, // Something like: Jane Doe <janedoe#gmail.com>
to: dest,
subject: 'Candidate Application', // email subject
html: `<div>
<strong>From:</strong> ` +
name +
`<br /><br />
<strong>Email:</strong> ` +
email +
`<br /><br />
<strong>Phone:</strong> ` +
phone +
`<br /><br />
</div>
`,// email content in HTML
attachments: [
{
filename: req.files[0].originalname,
content: req.files[0].buffer.toString("base64"),
encoding: "base64"
}
]
and rest of the code...
I suggest rethinking this approach altogether. You won't be able to move files around in a deployed function. The nodejs runtime filesystem doesn't allow any files to be written anywhere in the filesystem, except for os.tmpdir() (which is /tmp on Linux).
If you need to write a file temporarily, you should definitely only use that tmp space. Be aware that files written there occupy memory and should be deleted before the function terminates, or you could leak memory.
You can read files that you deployed with your code, but you should do that through relative paths.
I ran into same problem while moving file. I sort this problem by using a function to get the application root folder and then concatenate rest of the location.
//place this file on application root.
//import where you need to get the root path.
const path = require('path');
module.exports = (function(){
return path.dirname(require.main.filename || process.mainModule.filename);
})();
//taking your case move location.
const rootPath = //require the above module.
const newPath = rootPath + /functions/' +oldPath;
fs.rename(oldPath, newPath, function (err) {
if (err) throw err
console.log('Successfully renamed - AKA moved!')
});
I have a file that I am trying to write to from a post. Currently, the FS does not error nor does it write to file. However, when taking the same code from the deployed build and running it locally, it works. I even kept the file path consistent since it was throwing no permissions error at first. I ensured this file wrote to the same directory so each Filewrite Stream process would look at the same directory and file.
Local build:
var fs = require('fs');
const path = require('path');
var user_name = 'Password';
var password = 'test';
var errSTR = ""
fs.writeFile('C:\\hi.txt', 'Content to write', { flag: 'w' }, function(err) {
if (err)
return console.error(err);
fs.readFile('C:\\hi.txt', 'utf-8', function (err, data) {
if (err)
return console.error(err);
console.log(data);
});
});
Deployed Build:
app.route('/test')
.get(function(req, res) {
res.send('GET test');
})
.post(function(req, res) { // Start Post
var boolTry = false;
try {
boolTry = true;
var bool = false
var user_name = "Password"//req.body.user;
var password = "test"//req.body.password;
var errSTR = ""
fs.writeFile('C:\\hi.txt', user_name + password, { flag: 'w' }, function(err) {
if (err)
return console.error(err);
fs.readFile('C:\\hi.txt', 'utf-8', function (err, data) {
if (err)
return console.error(err);
res.send(500 + err);
console.log(data);
});
})
} catch (error) {
bool = true
errSTR = error
}
res.send('POST test' + " " + boolTry + " " + bool + " " + errSTR + ";")
})//END POST
.put(function(req, res) {
res.send('PUT test');
});
The local build will properly write to the file, while the dev build appears to do nothing. It should be noted by booleans were being used to understand how the file writer works but here is the server response from build: successful response POST test true false ;
Using:
IISNODE for iis: 7.x
Express: 4.16.2
node.js: v8.9.4
cors: 2.8.4
body-parser: 1.17.2
Sidenote: If you are confused by the writing portion of code, the intention was to write, check error then read, check error for assurance.
Update
Reoccurring error based on certain filewrite methods Error: EPERM: operation not permitted, open. Yes, all permissions for the directory are enabled along with ensuring read and write are checked.
There is a service which provides a XML under a certain URL (for example: https://myxml). The organisation from that service send me a p12 certificate with the password.
In the Browser it works correct.
On my local machine I'm running a Node JS server. I want to send a request from my node server and get the response from the service.
I'm pretty new to certificates.
This is the error I get after trying to get the request from the service
error:0906D06C:PEM routines:PEM_read_bio:no start line
This is the implementation in the node server
const request = require('request');
const fs = require('fs');
const path = require('path');
const certFile = path.resolve(__dirname, 'folder/cert.p12');
var options = {
url: 'https://myxml',
cert: fs.readFileSync(certFile),
passphrase: 'xyz'
}
request.get(options);
request('https://myxml', function(error, response, body){
console.log("error: ", error);
console.log("statusCode: ", response && response.statusCode);
console.log("body: ", body);
})
Try reading the file in as binary and using it directly
var p12 = fs.readFileSync('file.p12', 'binary');
var p12Asn1 = forge.asn1.fromDer(p12, false);
var p12Parsed = forge.pkcs12.pkcs12FromAsn1(p12Asn1, false, 'password');
also add agentOptions in request like
request({
method: 'GET',
url: 'https://myxml',
rejectUnauthorized: false,
strictSSL: false,
agentOptions: {
//pfx: pfx,
pfx: require('fs').readFileSync('string_path_to_the_p12_key_file.p12'),
passphrase: 'redacted_password'
}
}
I have a weird bug going on with my code.
I'm using the simple-oauth2 library (https://github.com/lelylan/simple-oauth2) and my code works fine on Windows.
When I try to run my code on a linux server (raspberry pi zero), the oauth library keeps on returning 404 Not Found for my oauth request (specifically "Access Token Error Not Found" as per the code below).
What's going on?
Code (working with Yelp API):
var fs = require('fs');
var cID = fs.readFileSync('blahblahblah', 'utf8');
var cSecret = fs.readFileSync('blahblahblah2', 'utf8');
var credentials = {
client: {
id: cID,
secret: cSecret
},
auth: {
tokenHost: 'https://api.yelp.com',
tokenPath: '/oauth2/token'
}
};
var oauth2 = require('simple-oauth2').create(credentials);
var tokenConfig = {};
module.exports.gimmeMuhToken = function(cb) {
oauth2.clientCredentials.getToken(tokenConfig, function(error, result) {
if (error) {
return console.log('Access Token Error', error.message);
}
cb(oauth2.accessToken.create(result).token.access_token); // Return the token
});
};
Thanks
Found the culprit.
It was line endings...
I am trying to get the AWS JS SDK to work in Parse's Cloud Code. Below is a simple s3 bucket upload function that works in the browser, but not in the cloud code. I have the js sdk file uploaded in the cloud folder. What am I doing wrong?
Parse.Cloud.define("publish", function(request, response){
require("cloud/aws-sdk");
AWS.config.update({accessKeyId: 'MYKEY', secretAccessKey: 'MYSECRETKEY'});
AWS.config.region = 'us-west-2';
var s3bucket = new AWS.S3({params: {Bucket: 'maggiesotterocms'}});
var params = {Key: 'data.json', Body: 'Hello world!', ContentLanguage:'JSON'};
s3bucket.upload(params, function(err, data) {
if (err) {
console.log("Error uploading data: ", err);
}
else {
console.log("Success");
}
});
});
I get this error in parses error logs when trying to run it
Ran cloud function publish for user USERID with: Input: {"error":{},"success":{}} Result: ReferenceError: AWS is not defined at main.js:4:2