How to get the favorites from flickr - node.js

I am working on Node.js to get the list of favorites photos from a user in flickr, I know there is other method to get the public list of favorites, and that one works fine to me, but using this the flickr API return me this error.
{"stat":"fail", "code":98, "message":"Invalid auth token"}
This is my code:
var util = require('util'),
http = require('http'),
keys = require(__dirname + '/../oauth/flickrKeys'),
utilities = require(__dirname + '/Utilities');
var getPhotos = function(userInfo, callback) {
var requestResponse,
parameters,
requestPoint,
url,
toHash,
secretKey,
api_signature,
method = "flickr.favorites.getList",
format = "json";
requestPoint = 'http://api.flickr.com/services/rest/';
url = requestPoint
+ '?api_key=' + keys.clave
+ '&auth_token=' + userInfo.oauth_token
+ '&format=' + format
+ '&method=' + method
+ '&min_fave_date=' + userInfo.min_fave_date
+ '&nojsoncallback=1'
+ '&user_id=' + encodeURIComponent(userInfo.user_nsid);
parameters = 'api_key=' + keys.clave
+ '&auth_token=' + userInfo.oauth_token
+ '&format=' + format
+ '&method=' + method
+ '&min_fave_date=' + userInfo.min_fave_date
+ '&nojsoncallback=1'
+ '&user_id=' + encodeURIComponent(userInfo.user_nsid);
toHash = 'GET&'
+ encodeURIComponent(requestPoint) + '&'
+ encodeURIComponent(parameters);
// coding hash.
secretKey = keys.secreto + "&" + userInfo.oauth_token_secret;
api_signature = utilities.generateFlickrSignatureHex(toHash, secretKey);
// adding api signature to the url.
url = url + '&api_sig=' + encodeURIComponent(api_signature);
http.get(url, function(res) {});
}

at the below line
url = requestPoint
+ '?api_key=' + keys.clave
+ '&auth_token=' + userInfo.oauth_token
+ '&format=' + format
+ '&method=' + method
+ '&min_fave_date=' + userInfo.min_fave_date
+ '&nojsoncallback=1'
+ '&user_id=' + encodeURIComponent(userInfo.user_nsid);
i think you haven't initialized userInfo object before this, which causes the mentioned authentication error related to userInfo.oauth_token
updated to question edit
make sure userInfo has a oauth_token attribute before calling the api.just like you can wrap the api call inside a check like
if(typeof(userInfo)!="undefined" && typeof(userInfo.oauth_token)!="undefined" && userInfo.oauth_token!="") {
//code for api call
}

Related

Azure Table Storage (Table Services REST API) SharedKeyLite not working

After seeing through this link, I tried the same in my postman.
var storageAccount = "mystorage";
var accountKey = "<<primaryKey>>";
var date = new Date();
var UTCstring = date.toUTCString();
var data = UTCstring + "\n" + "/mystorage/Health"
var encodedData = unescape(encodeURIComponent(data));
var hash = CryptoJS.HmacSHA256(encodedData, CryptoJS.enc.Base64.parse(accountKey));
var signature = hash.toString(CryptoJS.enc.Base64);
var auth = "SharedKeyLite " + storageAccount + ":" + signature;
postman.setEnvironmentVariable("auth", auth);
postman.setEnvironmentVariable("date", UTCstring);
When I make the request to ATS, to the following url,
I get the auth denied!
Can someone please guide me what's going wrong here?!
I think you need to generate a bearer token and put it to the Authorization of Postman.
If you are using C#, you can use this to get the bearer token:
AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
string accesstoken = azureServiceTokenProvider.GetAccessTokenAsync("https://storage.azure.com/").Result;
string bearertoken = "Bearer " + accesstoken;
Then Copy the bearer token:
After that, it should be ok.
Just realized that the url and the data that we are encoding should exactly match the url we are querying...
After changing
var data = UTCstring + "\n" + "/mystorage/Health"
to
var data = UTCstring + "\n" + "/mystorage/Health(PartitionKey='USA',RowKey='WA')"
things started working.
Update :
It just expects the right table query. The following works fine,
var data = UTCstring + "\n" + "/mystorage/Health()"
with all filter expressions in the url being invoked from postman.

Sending message to Azure Service Bus from POSTMAN nodeJs

I have been trying to send a sample message to Azure Service Bus Topic from POSTMAN, But it came with an unusual error. Here my doubt is, I am generating the SAS token using NodeJs own 'Buffer' rather than 'utf8' module. Can that be a reason Why I am getting 'The specified HTTP verb (POST) is not valid.'. Here is my snippet to generate the SAS token.
*function createSharedAccessToken(uri, saName, saKey) {
if (!uri || !saName || !saKey) {
throw "Missing required parameter";
}
console.log('inside the function')
var encoded = encodeURIComponent(uri);
var now = new Date();
var week = 60 * 60 * 24 * 7;
var ttl = Math.round(now.getTime() / 1000) + week;
var signature = encoded + '\n' + ttl;
var signatureUTF8 = Buffer.from(signature, 'utf8');
var hash = crypto.createHmac('sha256', saKey).update(signatureUTF8).digest('base64');
return 'SharedAccessSignature sr=' + encoded + '&sig=' +
encodeURIComponent(hash) + '&se=' + ttl + '&skn=' + saName;
}*
Its a POST call with Authorization and Content-Type header.
Please add 'messages' at the end of the url:
http{s}://{serviceNamespace}.servicebus.windows.net/{queuePath|topicPath}/messages
->
https://mynamespace.servicebus.windows.net/my-topic-name/messages
Send Message

Problem in JSR223 script JSR223 Sampler, while connecting to Azure Cosmos DB from Jmeter

I am trying to push my JMeter result to Azure Cosmos DB through the rest API exposed from the azure portal.
To achieve so I am using JSR223 sampler (as my pre processer) to get the auth token to connect to cosmos db also using the stand script to generate the auth_token (refer:https://github.com/MicrosoftCSA/documentdb-postman-collection/issues).
But I am getting Problem in JSR223 script JSR223 Sampler, message: javax.script.ScriptException: ReferenceError: "request" is not defined.
Code Snippet:
var mastKey = "master_key_for_cosmos_db";
log.info("mastKey = " + mastKey);
var today = new Date();
var UTCstring = today.toUTCString();
var url = "uri_key_for_cosmos_db"
var strippedurl = url.replace(new RegExp('^https?://[^/]+/'), '/');
log.info("stripped Url = " + strippedurl);
var strippedparts = strippedurl.split("/");
var truestrippedcount = (strippedparts.length - 1);
var resourceId = "";
var resType = "";
if (truestrippedcount % 2) {
resType = strippedparts[truestrippedcount];
if (truestrippedcount > 1) {
var lastPart = strippedurl.lastIndexOf("/");
resourceId = strippedurl.substring(1, lastPart);
}
} else // its even (item request on resource)
{
resType = strippedparts[truestrippedcount - 1];
strippedurl = strippedurl.substring(1);
resourceId = strippedurl;
}
var verb = request.method.toLowerCase();
var date = UTCstring.toLowerCase();
var key = CryptoJS.enc.Base64.parse(mastKey);
var text = (verb || "").toLowerCase() + "\n" +
(resType || "").toLowerCase() + "\n" +
(resourceId || "") + "\n" +
(date || "").toLowerCase() + "\n" +
"" + "\n";
var signature = CryptoJS.HmacSHA256(text, key);
var base64Bits = CryptoJS.enc.Base64.stringify(signature);
var MasterToken = "master";
var TokenVersion = "1.0";
auth = encodeURIComponent("type=" + MasterToken + "&ver=" + TokenVersion + "&sig=" + base64Bits);
vars.put("authToken", auth);
anything I am doing wrong or missed?
This request object belongs to Postman tool, you cannot use it in your JMeter scripts as it is not defined there.
You will also need to import this CryptoJS which might not be trivial.
Moreover the recommended language for scripting in JMeter is Groovy
So instead of trying to copy and paste someone's Postman code into JMeter which will not work I would rather recommend going into one of the following directions:
Use Azure Cosmos DB Java SDK for SQL API from JSR223 Test Elements using Groovy language
Or replicate the Postman's JavaScript in Groovy like it's described in How to Handle Dynamic AWS SigV4 in JMeter for API Testing article

Suitelet redirect to record

I have a suitelet script that creates a csv format file from the line-items of Opportunity. on Opportunity created a 'Export CSV' button which calls this suitelet.
var fileObj = file.create({
name: 'transactions.csv',
fileType: file.Type.CSV,
contents: data,
description: 'This is transactions',
folder: 13497862
});
var Fileid = fileObj.save();
var loadFile = file.load({ id: Fileid });
var fileurl = loadFile.url;
var html = "";
html += "<html>";
html += "<script>";
html += 'window.location.href="' + fileurl + '";\n';
html += "</script>";
html += "</html>";
response.write(html);
After response.write executes, the file gets downloaded in computer. but after that I want it to redirect again to the Opportunity. But its returning a blank screen.
I used redirect.toRecord() but it is not executing because response.write(html) executes first and script stops there.
You can try forcing the browser to download the file and then redirect to the opportunity record.
var html = '';
html += '<html>'
'<script>' +
'var a = document.createElement('a');' +
'a.href = "' + fileurl + '";' +
'a.download = "' + fileurl + '";'
'document.body.appendChild(a);' +
'a.click();'; +
'setTimeout(function(){' +
' window.location.href = "REDIRECT_URL";' +
'}, 5000);' +
'</script>' +
'</html>';
response.write(html);
However, this solution may not always bring the exact same results on all browsers. A client script could be more appropriate for your requirement.

sharepoint - starting workflow jsom script works on premise but fails online?

I have a piece of javascript code starting a workflow.
It all works on my on premise dev machine.
But as soon as I try to run it on an online site, it fails.
It is based on the workflow.asmx web service, and I get error 500 - value does not fall on expected range...
I suspect this is in the workflow parameters. But I cannot see what exactly. The user login differs but it is compliant with oneline format...
Any idea about any possible differences between on premise vs online that might explain this?
just in case, here's my code (again, perfectly fine onpremise):
function StartMyWorkflow(listGUID, itemId) {
var wfDefinitionId = "{9279E1FF-1D32-4423-85B7-C7F21998A701}";
var ctx = SP.ClientContext.get_current();
var web = ctx.get_web();
var list = web.get_lists().getById(listGUID);
var item = list.getItemById(itemId);
var currentUser = web.get_currentUser();
ctx.load(web);
ctx.load(item);
ctx.load(currentUser);
ctx.executeQueryAsync(
Function.createDelegate(this, function () {
var login = currentUser.get_loginName();
var name = currentUser.get_title();
var xml = getWFAssocData(name, login);
var fileRef = "https://" + location.host + item.get_item("FileRef");
$().SPServices({
operation: "StartWorkflow",
item: fileRef,
templateId: wfDefinitionId,
workflowParameters: xml,
completefunc: function () {
SP.UI.Notify.addNotification('workflow started', false);
}
});
}),
function (s, a) { console.error(a.get_message());}
);
}
function getWFAssocData(name, login) {
var assocData = '<dfs:myFields xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:dms="http://schemas.microsoft.com/office/2009/documentManagement/types" xmlns:dfs="http://schemas.microsoft.com/office/infopath/2003/dataFormSolution" xmlns:q="http://schemas.microsoft.com/office/infopath/2009/WSSList/queryFields" xmlns:d="http://schemas.microsoft.com/office/infopath/2009/WSSList/dataFields" xmlns:ma="http://schemas.microsoft.com/office/2009/metadata/properties/metaAttributes" xmlns:pc="http://schemas.microsoft.com/office/infopath/2007/PartnerControls" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">' +
'<dfs:queryFields></dfs:queryFields>' +
'<dfs:dataFields>' +
'<d:SharePointListItem_RW>' +
'<d:Approvers>' +
'<d:Assignment>' +
'<d:Assignee>' +
'<pc:Person><pc:DisplayName>' + name + '</pc:DisplayName><pc:AccountId>' + login + '</pc:AccountId><pc:AccountType>User</pc:AccountType></pc:Person>' +
'</d:Assignee>' +
'<d:Stage xsi:nil="true" />' +
'<d:AssignmentType>Serial</d:AssignmentType>' +
'</d:Assignment>' +
'</d:Approvers>' +
'<d:ExpandGroups>true</d:ExpandGroups>' +
'<d:NotificationMessage>Please approve test</d:NotificationMessage>' +
'<d:DueDateforAllTasks xsi:nil="true" /><d:DurationforSerialTasks xsi:nil="true" />' +
'<d:DurationUnits>Day</d:DurationUnits>' +
'<d:CC />' +
'<d:CancelonRejection>true</d:CancelonRejection>' +
'<d:CancelonChange>false</d:CancelonChange>' +
'<d:EnableContentApproval>false</d:EnableContentApproval>' +
'</d:SharePointListItem_RW>' +
'</dfs:dataFields>' +
'</dfs:myFields>';
return assocData;
}
It turns out to be as silly as obvious. I was just missing a 's' in the fileRef url... I've corrected the above script, so it's actually fully functional.

Resources