Unable to get work history/ email and other information - facebook-graph-api

I have a list of user id's ( may or may not be my friends) I want to get ALL the public possible information about them.. However, I am only getting back Name, Id and Photo. Where am I going wrong?
FB.login(function(){
/* make the API call */
FB.api(
"/{event-id}/attending",
function (response) {
if (response && !response.error) {
var array = response.data;
array.forEach(function(eachUser){
//console.log(eachUser);
FB.api(
"/"+ eachUser.id,
function (response) {
if (response && !response.error) {
console.log(response);
}
}
);
});
}
}
);
}, {scope: 'user_events, user_education_history , user_about_me , user_work_history , user_location , user_website'}); //,age_range, bio , context , education

Even if it´s set to public, all the other data is only available if the user authorizes your App with the appropriate permission. So in the list of attending users, name/id/photo is the only data you can get.

Related

How to get PowerBI accesstoken using ADAL.JS

I'm trying to use ADAL.js to authenticate against PowerBI in order to get an access_token and the embed_token needed to embed PowerBI reports/dashboards/tiles in a html/javascript-only "webpart". My adal-config looks like:
config = {
instance: 'https://login.windows.net/common/oauth2/authorize/',
tenant: 'tenant.onmicrosoft.com',
clientId: '05xxxxx-xxx-xxxx-xxxx-xxxxxxxxxxxx',
loginResource: "https://analysis.windows.net/powerbi/api",
postLogoutRedirectUri: window.location.origin,
cacheLocation: 'localStorage',
};
But I can't seem to find any access-token etc in the user.profile I get. I am obviously missing something but what.. :) Any help would be much appriciated
Looking at:
https://community.powerbi.com/t5/Developer/get-Access-token-using-js/m-p/350294
and also this:
https://community.powerbi.com/t5/Developer/How-to-Generate-Embed-Token-in-pure-JavaScript/td-p/350056
you can use ADAL.js to get the access token itself
window.config = {
instance: 'https://login.microsoftonline.com/',
tenant: 'common', //COMMON OR YOUR TENANT ID
clientId: 'XXXXX', //This is your client ID
redirectUri: 'XXXXXX', //This is your redirect URI
callback: userSignedIn,
popUp: true
};
var ADAL = new AuthenticationContext(config);
function signIn() {
ADAL.login();
}
function userSignedIn(err, token) {
console.log('userSignedIn called');
if (!err) {
showWelcomeMessage();
ADAL.acquireToken("https://analysis.windows.net/powerbi/api", function (error, token) {
// Handle ADAL Error
if (error || !token) {
printErrorMessage('ADAL Error Occurred: ' + error);
return;
}
}

How can I filter REST calls results based on Roles and current user context in Loopback (server side)

Given the following:
There are 3 models:
Company
Employee (derived from User)
Position
Company is linked to Employee through Position (has many, has many)
There are 2 Roles:
admin
user
I would like to configure my REST api as follow:
When an admin is logged, can access all REST functions.
"accessType": "*",
"principalType": "ROLE",
"principalId": "admin",
"permission": "ALLOW"
When a user is logged:
GET /companies : Only return the companies in which the current user has a position.
GET /companies/#id: Only allow if the current user has a position in this company.
Based on J3Y's comment, I wrote the following function.
Note that the function is not overriding model ACL.
The procedure follows those steps:
1: Access current user userID through the loopback current context.
If there is no authenticated user, exit the function.
2: Load Role of the current user, using the RoleMapping table
If the current user Role is not "user", exit the function.
3: Load Positions of our current user and create an array of the companies Id he's working in.
4: rewrite the current query
for /companies calls, inject a where condition for id
for /companies/#id, test if requested id is matching one of the allowed ids, if not, return an error 401
Company.observe('access', function (ctx, next) {
/* Observe the access to companies
* If the role of the logged user is 'user', will restrict access to only custom set of data
* Otherwise, will access all data */
// Access loopback current Context to get userID through accessToken
var loopbackCtx = loopback.getCurrentContext();
var accessToken = loopbackCtx && loopbackCtx.get('accessToken');
var userId = accessToken && accessToken.userId;
if (!userId) {
// without connected user. proceed without hook
return next();
}
// Will perform a query in the RoleMapping Model to findout the current role of connected user
var RoleMapping = app.models.RoleMapping;
var roleQuery = {
where: {
"principalId": userId,
"roleId": 2 // role 2: user
}
};
RoleMapping.findOne(roleQuery, function (err, result) {
if (!result) {
//no matching role, proceed without hook
return next();
}
// found one match in the RoleMapping table. must now restrict results in accordance with positions of the current employee
// Looking for positions for the current employee
var position = app.models.position;
var positionQuery = {
where: {
"employeeId": userId
}
};
position.find(positionQuery, function (err, results) {
// from the position list, create a list of companies
var allowedCompanies = [];
results.forEach(function (result) {
allowedCompanies.push(result.companyId);
});
//use the list of allowed companies to restrict results
if (!ctx.query.where) {
// typically call from a find() without arguments (findall)
// will inject a new condition
ctx.query = {
where: {
"id": { inq: allowedCompanies}
}
}
}
else {
if (ctx.query.where.id && Number.isInteger(ctx.query.where.id)) {
// typically call from a find({ id: .. )}
// will authorize or not access to the company data
console.log(ctx.query.where.id);
if ( allowedCompanies.indexOf(ctx.query.where.id) == -1 ) {
// the id is not in the permited scope, will return a 401 error
var error = new Error();
error.name = "Error";
error.status = 401;
error.statusCode = 401;
error.message = 'Authorization Required';
error.code = 'AUTHORIZATION_REQUIRED';
return next(error);
}
}
// other calls (with inq) are not yet implemented
}
return next();
});
});
});

Chat application using CFWebsocket

How can we develop a facebook like chat application using cfwebsocket. There is no description about how to send an user entered message to the server and how to send that message to a particular client from the server.
<script type="text/javascript">
function mymessagehandler(aevent, atoken)
{
console.log(aevent);
console.log(atoken);
var message = aevent.msg;
var txt=document.getElementById("myDiv");
txt.innerHTML = txt.innerHTML + message +"<br>";
}
</script>
<cfwebsocket name="mycfwebsocketobject" onmessage="mymessagehandler" subscribeto="stocks" >
<cfdiv id="myDiv"></cfdiv>
The above code just prints ok in the display. I am not sure how to pass my message inside the stocks object. Can anyone help on this? Thanks in advance
This is the stocks application that I am using
this.wschannels = [ {name="stocks", cfclistener="myChannelListener" }];
This is what I have did to make my chat application work
This is the chat application
<cfwebsocket name="ChatSocket" onOpen="openHandler" onMessage="msgHandler" onError="errHandler">
This is the script
function openHandler(){
//Subscribe to the channel, pass in headers for filtering later
ChatSocket.subscribe('chatChannel',{name: 'TheUserName', UserID: 'TheUserID', AccountID: 'AnUniqueID' });
}
// function to send the message. we can call this when the user clicks on send message
function publish(userID){
var msg = {
AccountID: "AnUniqueID",
publisher: userID,
id: userID,
message: document.getElementById("Name").value + " : " + document.getElementById("message").value
};
//When including headers, the "selector" is where you will filter who it goes to.
var headers = {
AccountID: "AnUniqueID",
publisher: userID,
id: userID
};
// we can save the chat history by an ajax call here
ChatSocket.publish('chatChannel',msg, headers);
}
// this is the receiving function
function msgHandler(message){
// if condition to display the message to the user who are sending and receiving
if(message.data !== undefined && message.data.message !== undefined && (message.data.id == '#session.userID#' || message.data.publisher == '#session.userID#')) {
var data = message.data.message;
console.log(data);
//showing the message
var txt=document.getElementById("myDiv");
txt.innerHTML+= data + "<br>";
}
}
function errHandler(err){
console.log('err');
console.log(err);
}

facebook graph API does not return event

I am trying to use graph API call to return events of a user who logged in to my app. However , $event is null all the time although I have created bunch of events myself, could anyone help?
Here is my code from login to the event api call:
require_once('AppInfo.php');
// Enforce https on production
if (substr(AppInfo::getUrl(), 0, 8) != 'https://' && $_SERVER['REMOTE_ADDR'] != '127.0.0.1') {
header('Location: https://'. $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
exit();
}
// This provides access to helper functions defined in 'utils.php'
require_once('utils.php');
require_once('sdk/src/facebook.php');
$facebook = new Facebook(array(
'appId' => AppInfo::appID(),
'secret' => AppInfo::appSecret(),
'sharedSession' => true,
'trustForwarded' => true,
));
$user_id = $facebook->getUser();
if ($user_id) {
try {
// Fetch the viewer's basic information
$basic = $facebook->api('/me');
} catch (FacebookApiException $e) {
// If the call fails we check if we still have a user. The user will be
// cleared if the error is because of an invalid accesstoken
if (!$facebook->getUser()) {
header('Location: '. AppInfo::getUrl($_SERVER['REQUEST_URI']));
exit();
}
}
// This fetches some things that you like . 'limit=*" only returns * values.
// To see the format of the data you are retrieving, use the "Graph API
// Explorer" which is at https://developers.facebook.com/tools/explorer/
$likes = idx($facebook->api('/me/likes?limit=4'), 'data', array());
// This fetches 4 of your friends.
$friends = idx($facebook->api('/me/friends?limit=4'), 'data', array());
// And this returns 16 of your photos.
$photos = idx($facebook->api('/me/photos?limit=16'), 'data', array());
// Fetch the event information
// $events = idx($facebook->api('/me/events?limit=5'), 'data', array());
$events = $facebook->api('/me/events','GET');
print("11111");
if($events == null) print("empty");
I see no login code in your example, are you sure the user is logged in? See PHP SDK "Usage": https://github.com/facebook/facebook-php-sdk
Anyway, i just tried this in one of my projects, i get the user events with the same call but i need the permission "user_events":
$facebook->getLoginUrl(array('scope' => 'user_events'));

Facebook FQLproblem with javascript sdk

Hey everyone,
i do the following query to get a user statuses:
FB.api(
{
method: 'fql.query',
query: 'SELECT message FROM statuses WHERE uid = ' + userId
},
function(data) {
// do something with the response
}
);
It works great when the number of result are more than 0.
but when there are no results, the callback function is not called at all.
i need to know if there are 0 rows returning from this query, is there any way to do it?
Thanks :)
First of all, the statuses table does not exists. You should be using status table.
The callback is always called but you should properly check against empty objects. Just paste this on the Javascript Test Console:
<fb:login-button scope="read_stream">
Grant access to statuses
</fb:login-button>
<button onclick="getStatuses()">Get Statuses</button>
<script>
window.getStatuses = function() {
FB.api(
{
method: 'fql.query',
query: 'SELECT message FROM status WHERE uid = me() AND time < 315532800'
},
function(data) {
if(!isEmpty(data)) {
for(var key in data) {
var obj = data[key];
console.log(obj['message'])
}
} else {
console.log("data is empty")
}
});
};
function isEmpty(obj) {
for(var prop in obj) {
if(obj.hasOwnProperty(prop))
return false;
}
return true;
}
</script>
Here I am checking for statuses before 1/1/1980 to insure that an empty result is returned. In your console you should note the data is empty response.
When there are no results from a query, you should be getting an empty array.
Also, there isn't a FQL table named "statuses", it's "status".