Dashboard data with Good data SDK - javascript

I need to consume my company 'Target Social R3 V3' dashboard data with Good data Javascript SDK. First I'm trying to get pinterest data as start but I'm receiving error 400 Bad request. I'm newbie to good data api and following methods given in good data examples in Java script SDK.
$('#root').append('<div class="login-loader">Logging in...</div>');
gooddata.user.login(user, passwd).then(function() {
// Loged in
$('div.login-loader').remove();
$('#root').append('<div class="loading">Logged in... Loading metrics</div>');
// Do your stuff here
// ...
gooddata.md.getMetrics(projectId).then(function(dataSets) {
$('div.loading').remove();
$('#root').append('<div class="dataLoading">Laoding data...</div>');
$('#root').append('<p>Total number of metrics ' + dataSets.length + '</p>');
elements=[];
dataSets.forEach(function(ds) {
var dstr = JSON.stringify(ds.title);
if(dstr.toLowerCase().indexOf("pinterest account followers") > 0)
{
var did = JSON.stringify(ds.identifier);
$('#datasets').append('<li>'+did+'</li>');
elements.push(did);
}
});
$('#root').append('<p>Total number of choosen metrics '+elements.length + ' and element '+elements[0] +'</p>');
gooddata.execution.getData(projectId, elements).then(function(dataResult)
{
$('div.dataLoading').remove();
console.log('Social Data:\n'+ JSON.stringify(dataResult));
});
});
});
I'd appreciate if some one could explain about attributes and metrics passed here as parameters.

Make sure your sample is under gooddata-js/examples/ folder (let's assume is named 'mysample') and it has index.html file in that directory. Set user and passwd variables in your script file to your real GoodData user name and password. Run grunt dev and access your sample at https://localhost:8443/mysample/index.html. It should work.
If it does not work, please provide the details (message body) of the 400 error you are getting.

Related

Integrate Salesforce registration page with VanillaJS oidc-client-js, getting the error - No matching state found in storage

Integrate Salesforce registration page with VanillaJS, getting the error - No matching state found in storage
We are redirecting the user to Salesforce registration page when Create Account button is created.
Once the User registers in Salesforce, the user is redirected to our site but we are getting this error. ('No matching state found in storage').
We tried the below solution but still getting the same error.
As I stated in my answer, the oidc client maintains state information
in the local storage so that it can verify that it got the response
back from the intended server. You can mimic this by generating a
secure random string and saving it in localStorage. Do this before
sending a request to your auth server to register a new user.
Reference- Integrate third party login in from my registration page with IdentityServer4 and Angular 6 - 'No matching state found in storage'
Is there a function related to creating registration? How to fix this issue?
Thanks.
Appreciate your help.
After spending days on this issue. Finally found the workaround as registration is not a feature of OIDC.
To overcome this issue, need to follow the Sign In process same as for Sign Up process, created the startSignupMainWindow method same as startSigninMainWindow and passing the signUpFlag:true as shown below in code.
/* This function is written to mimic the oidc library sign in process flow */
function startSignupMainWindow() {
var someState = {
message: window.location.href,
signUpFlag: true
};
mgr.signinRedirect({
state: someState,
useReplaceToNavigate: true
}).then(function() {
log("signinRedirect done");
}).catch(function(err) {
log(err);
});
}
Reading the signUpFlag:true in UserManager.js and swapping the Salesforce Sign In page Url with Sign Up page url and calling the Register function in Code.
UserManager.js(oidc - client - dev - js / src / UserManager.js)
//UserManager Customised Code :
return this.createSigninRequest(args).then(signinRequest => {
Log.debug("UserManager._signinStart: got signin request");
navigatorParams.url = signinRequest.url;
navigatorParams.id = signinRequest.state.id;
if (signinRequest.state._data.signUpFlag) {
register(signinRequest.state._id, signinRequest.state._code_challenge);
} else {
return handle.navigate(navigatorParams);
}
})
The below code is Register function written in code.
/* This function is written to send the code_challenge to salesforce server so that
salesforce server holds the code challenge and used to verify the further requests(token-request)
against the code_challenge it received initially.*/
//Customised register function written outside the library (Inside our App):
function register(_id, code_challenge) {
var date = new Date();
var baseUrl = "SALESFORCE_URL/login/SelfRegister?expid=id";
var expId = "id";
var userPage = encodeURIComponent(window.location.href);
var appDetails = "response_type=code&" +
"client_id=CLIENT_ID" +
"client_secret=CLIENT_SECRET&" +
"redirect_uri=CALLBACK_URL&" +
"state=" + _id + "&code_challenge=" + code_challenge + "&code_challenge_method=S256&response_mode=query";
var encodedapp = encodeURIComponent(appDetails);
var startUrl = "/services/oauth2/authorize/expid?" + encodedapp;
var signUpUrl = baseUrl + "&startURL=" + startUrl;
window.open(signUpUrl, "_self");
};

Creating a user session - NODE js

I am new to node js & javascript in general. I have the below piece of code that will handle a login. I have a MYSQL database with a customer table. When the customer enters their username and password, it checks does it exist in the database. This part is working.
I now want to enhance this feature so that it will take the username and create some sort of a session variable, which can be used across the application. I am new to JS so I am not yet sure which inbuilt facilities already exist, or best practice around sessions.
I want to be able to use this session variable across the application, and for subsequent logout facility.
Can someone advise me on this, or point me in the right direction? Thanks.
case "/login":
var body = '';
console.log("user Login ");
request.on('data', function (data) {
body += data;
});
request.on('end', function () {
var obj = JSON.parse(body);
console.log(JSON.stringify(obj, null, 2));
var query = "SELECT * FROM Customer where name='"+obj.name+"'";
response.writeHead(200, {
'Access-Control-Allow-Origin': '*'
});
db.query(
query,
[],
function(err, rows) {
if (err) {
response.end('{"error": "1"}');
throw err;
}
if (rows!=null && rows.length>0) {
console.log(" user in database" );
theuserid = rows[0].customerID;
var obj = {
id: theuserid
}
response.end(JSON.stringify(obj));
}
else{
response.end('{"error": "1"}');
console.log(" user not in database");
}
}
);
});
}
There can be multiple ways of implementing a user session.
One, you could use a browser cookie, it comes with many pros and cons and you should read about it a bit to see how its managed. This would also depend on the server you are using (express, hapi, etc).
Two, you can set a JWT token on the backend, and include it in the header of the response, then you can either use your application state or the local storage of the browser to save that token on the UI. Any such follow up requests requiring authentication should contain this auth token as a header for verification.
For more clarity, you can look into related libraries (such as passport), which make this task a lot easier.
PS: If you choose cookies, please make sure the business is going to allow it or not as the end-users do not like being tracked always. :)

Firebase push() method shuffle the list data

Have created a chat application and we use firebase for realtime communication.
Sometimes i noticed that push() method shuffle the list data. We can see in the below image :
If we see in above image i am just trying to communicate with someone i said hello in reply user said hey, again i said i need some help then user said That's what I'm here for. What can I assist you with? in the reply but if we see in the image users reply is appearing first.
It happens intermittently that's why i didn't figure out this problem. So please someone help me out what shall i doing wrong.
var pushMessageToFB = function(){
var chatMsgRef = db.child("chatMessages").child("gr1").child("ch_usr1_usr2");
var message = {
type: "chat",
content: data.messageText,
timestamp: Date.now(),
by: user.id
};
chatMsgRef.push(message, function(err){
if (err){
console.log('error occurred while pushing message to fb : err ' + JSON.stringify(err));
}
});};
var loadChatMessages = function(){
var chatMsgRef = db.child('chatMessages').child("gr1").child("ch_usr1_usr2");
$scope.chatMessages = chatMsgRef.orderByKey().limitToLast(50);
};
Don't use Date for remote data. It will be slightly offset on every machine. Use ServerValue.TIMESTAMP which Firebase will convert to the server's Unix epoch time when the data is written. This ensures consistency of order across clients.
You didn't provide any code for how you're reading or displaying the chat messages, but since you're trying to show them in chronological order I assume your query uses orderBy("timestamp"). If you use ServerValue.TIMESTAMP when you write the message it will be guaranteed to sort in the order that it was written to the database.

How to get Facebook user's friends' profile picture using Javascript SDK V2.0

I am creating a website using Facebook API V2.0 JavaScript SDK and I would like to display the profile pictures of the user's friends.
I have managed to display my profile picture using the graph API but I can't manage to get the ID of all my friends if I am logged in my app (I am an admin). If I have the ID, I'll be able to show their profile picture.
In the graph explorer, I have checked all permissions (User Data Permissions + Extended Permissions). I have noticed if I switch to API V1.0, I get friends permission which is exactly what I'd like.
Also, I have added a couple of permission to my app in Facebook developers > App details > App Center Listed Platforms > Configure app center permissions. (user_friends + friends_birthday + friends_religion_politics + friends_relationships + friends_relationship_details + friends_location + friends_photos + friends_about_me)
So far, my html looks like this :
<fb:login-button scope="public_profile,email,user_friends,read_friendlists" onlogin="checkLoginState();">
After loading the Facebook SDK, I have :
function getUserFriends() {
FB.api('me/friends?fields=first_name,gender,location,last_name', function (response) {
console.log('Got friends: ', response);
$("#friendslist").html('<img src="https://graph.facebook.com/'+ response.id+'/picture?type=large"/>');
});
}
However, the array which is suppose to contain all my friends info is empty (see image : http://www.screencast.com/t/W02GaOm3h)
If all you need is their image, this can be found in the "taggable_friends" scope. However, do note that this field is very limited (by design) and that you require additional review by Facebook in order to present it to the average user.
It contains:
A taggable id. This is an id with the express purpose of tagging; it cannot be used to identify the user or otherwise gather information from their profile.
A name. The user's first and last name.
A picture, with common related fields. Url, is_silhouette, height and width.
function getUserFriends() {
FB.api('me/taggable_friends', function (response) {
console.log('Got friends: ', response.data);
$("#friendslist").html('<img src="'+response.data[0].picture.data.url+'"/>');
// maybe an $.each as well
// var friendMarkup = '';
// $.each(response.data, function(e, v) {
// friendMarkup += '<img src="' + v.picture.data.url +'" alt="'+ v.name +' picture"/>';
// }
// $("#friendlist").html(friendMarkup);
});
}
Related reading:
https://developers.facebook.com/docs/graph-api/reference/v2.0/user/taggable_friends
https://developers.facebook.com/docs/opengraph/using-actions/v2.0 - Tagging friends and Mentioning friends sections
A disclaimer: I've been battling with this issue for several days without really being able to mention-tag. My submission to use taggable_friends as a comprehensive, navigatable list for the user was rejected and I speculate (speculation ho!) it was because I did no actual tagging. I'll get back to this in a few days when I've clarified and re-submitted my request for a review on Facebook.
-- Edit --
It would seem the reason my initial submission was rejected was because I was using a special development url and did not point out clearly enough why it was not enough to use the url set under settings. This time I clearly pointed out and explained this reasoning in both the general description of my submission and in the step-by-step notes. In summary, be exceptionally clear in your submission about everything; your reasoning as to why you need this permission, how they can access it, etc. Just to make sure it isn't missed if skim-read.
It seems like in V2.0, Friends permission have dissapeared :
Facebook graph api explorer doesn't show 'Friends Data Permission' tab
https://developers.facebook.com/docs/facebook-login/permissions/v2.0

Log client browse website information in backbone.js

I'm using this code to get client information :
$.getJSON("http://www.geoplugin.net/json.gp?jsoncallback=?",function (data) {
console.log(data.geoplugin_request);
console.log(data.geoplugin_countryName);
});
Then I would like to record this information at the first time that client visit the website (session start of the website). My current project are using backbone.js, require.js, underscore.js.
Any suggestions would be appreciated. Thanks.
Assuming that you have application.js file which act as a entry point of the backbone aplication which initializes your router an all stuff, you can set the client details in the browser using localStorage.
// Retrieve the object from storage
var retrievedVar = localStorage.getItem('countryName');
if( retrievedVar == null) {
$.getJSON("http://www.geoplugin.net/json.gp?jsoncallback=?",function (data) {
console.log(data.geoplugin_countryName);
// Put the object into storage
localStorage.seItem('countryName', JSON.stringify(data.geoplugin_countryName)
});
Hence the getJSON will only be fired once when localStorage var is not set.

Categories