Facebook Javascript Ajax Authentication - javascript

I've got my Cordova app authenticating with Facebook although i'm trying retrieve some data and I get errors. Was wondering if my URL is incorrect. Can anyone spot a mistake in this?
Errors:
app: makeAPICalls: error:setting authenticatedUser to Yes and skip registration.{"readyState":0,"status":0,"statusText":"Error: SyntaxError: DOM Exception 12"}
function makeAPICallsFB(token) {
$.ajax(
{
//url: 'https://api.linkedin.com/v1/people/~?format=json',
url: 'https://graph.facebook.com/v2.6/me?fields=id,first_name,last_name,bio,email,work,friends,picture{url}',
//url: 'https://graph.facebook.com/v2.6/oauth/access_token',
beforeSend: function (xhr) {
try {
console.log("Authorization...");
xhr.setRequestHeader('authorization', 'Bearer ' + token);
console.log("Finished Auth...");
} catch(err) {
alert(err);
}
},
success: function (linkedInData) {
console.log("TEST....");
if (linkedInData != null) {
console.log("Success");
try {
console.log('app: makeAPICalls LinkedInData: ' + JSON.stringify(linkedInData) + " token: " + token);
console.log('name: ' + linkedInData.id);
vsetaService.saveLinkedInData(linkedInData, token);
checkUserStatus();
} catch(err) {
alert(err);
}
} else {
alert("Data is NULL!");
}
},
error: function (error) {
console.log("app: makeAPICalls: error:setting authenticatedUser to Yes and skip registration." + JSON.stringify(error));
//navigator.notification.confirm('Unable to connect to LinkedIn at this time.', confirmCallback, "VSETA - Think Material", ["Ok"]);
//Take user to Home if an error with LinkedIn + Temp assign access
authenticatedUser = 1;
homeScreen();
}
});
console.log("Finished!");
}
This is my FB Login
function oauth2_loginFaceBook() {
$.oauth2({
type: 'post',
auth_url: 'https://www.facebook.com/v2.6/dialog/oauth', // required
response_type: 'code', // required - "code"/"token"
token_url: 'https://www.facebook.com/v2.6/oauth/access_token', // required if response_type = 'code'
logout_url: '', // recommended if available
client_id: 'confidential', // required
client_secret: 'confidential', // required if response_type = 'code'
redirect_uri: 'http://localhost/callback', // required - some dummy url
other_params: { scope: 'public_profile', state: 'somethingrandom1234' } // optional params object for scope, state, display...
}, function (token, response) {
console.log('app: oauth2_login Success: ' + response.text);
// do something with token or response
makeAPICallsFB(token);
}, function (error, response) {
console.log('app: oauth2_login ERROR: ' + response.text + " AuthenticateUser anyways to allow access to App as of right now.");
//Take user to Home if an error with LinkedIn + Temp assign access
authenticatedUser = 1;
homeScreen();
});
}
Any help is appreciated!
EDIT: Linkedlin was done correctly and the code is almost the exact same!
function makeAPICalls(token) {
$.ajax(
{
//url: 'https://api.linkedin.com/v1/people/~?format=json',
url: 'https://api.linkedin.com/v1/people/~:(id,first-name,last-name,picture-urls::(original),headline,industry,num-connections,location,summary,specialties,site-standard-profile-request,api-standard-profile-request,public-profile-url,picture-url,positions:(id,title,summary,start-date,end-date,is-current,company:(id,name,type,size,industry,ticker)),educations:(id,school-name,field-of-study,start-date,end-date,degree,activities,notes))?format=json',
beforeSend: function (xhr) {
xhr.setRequestHeader('authorization', 'Bearer ' + token);
},
success: function (linkedInData) {
if (linkedInData != null) {
console.log('app: makeAPICalls LinkedInData: ' + JSON.stringify(linkedInData) + " token: " + token);
vsetaService.saveLinkedInData(linkedInData, token);
checkUserStatus();
}
},
error: function (error) {
console.log("app: makeAPICalls: error:setting authenticatedUser to Yes and skip registration." + JSON.stringify(error));
//navigator.notification.confirm('Unable to connect to LinkedIn at this time.', confirmCallback, "VSETA - Think Material", ["Ok"]);
//Take user to Home if an error with LinkedIn + Temp assign access
authenticatedUser = 1;
homeScreen();
}
});
}
I was thinking that it could be the URL. Any suggestions?

I think the problem is probably picture{url}
If you want the URL of their profile picture,
photoURL = "http://graph.facebook.com/" + response.id + "/picture";
EDIT
Alright then if that's not it I'll just tell you how I go about what you're trying to do.
Use facebook's SDK. It's way easier than using Ajax for this type of thing.
//1
//This initializes the SDK
FB.init({
appId : 'your app id goes here',
cookie : true, // enable cookies to allow the server to access
// the session
xfbml : true, // parse social plugins on this page
version : 'v2.6' // use graph api version 2.6
});
//2
//This loads the SDK
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
//3
//This is the login button
<fb:login-button scope="public_profile,email" onlogin="facebookDoAThing();" data-max-rows="1" data-size="large" data-show-faces="true" data-auto-logout-link="true"></fb:login-button>
//4
//This function gets called by the button, then calls the next couple of functions
function facebookDoAThing() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
//5
//This checks that they authorized your app
function statusChangeCallback(response) {
if (response.status === 'connected') {
// logged into facebook and gave your app access to their account
getInfoAndSuch(response);
}
}
//6
//This is where you grab their info
function getInfoAndSuch(response){
authType = "facebook";
authId = response.authResponse.userID; //For the api call
// This is the SDK's api call syntax.
FB.api('/' + authId + '?fields=id,first_name,last_name,email,permissions',
function(response) {
firstName = response.first_name; //grabs first name
lastName = response.last_name; //grabs last name
email = response.email; //grabs email
photoURL = "http://graph.facebook.com/" + response.id + "/picture"; //Grabs photo url, probably an easier way to do this
});
//This removes your app from their account if you want that
FB.api("/me/permissions", "delete", function(response){});
That flow should be able to accomplish what you want.

Related

To post on facebook page using javascript SDK with page access token

I am trying to post to my facebook's wall using javascript SDK. I am first getting user access token. Then using user access token i am getting page access token and including it while posting to a wall. I'm getting following error
here's my code : First am trying to login using FB.login
FB.login(function(response) {
if (response.authResponse) {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.'+JSON.stringify(response));
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
},{scope: 'manage_pages,publish_pages'});
Then trying to post to a page.
var body = 'Reading JS SDK documentation';
FB.getLoginStatus(function(response) {
console.log('login status',response);
if(!(response.status === 'connected')){
location.href = './fb-login.html';
} else {
uID = response.authResponse.userID;
accessToken = response.authResponse.accessToken;
console.log('accesstoken::',response.authResponse.accessToken);
FB.api('/me', {fields: 'last_name'}, { access_token : accessToken } ,function(response) {
console.log(response);
});
//get list of pages
if(accessToken!=null){
FB.api('/me/accounts','get',{ access_token : accessToken },function(response){
console.log('resp of pages',response);
if(response!=null){
var data = response.data;
pageAccessToken= data[0].access_token;
console.log('pageAccessToken::',pageAccessToken);
FB.api('/6599048*******/feed', 'post', {message :body, access_token : pageAccessToken }, function(response) {
console.log('response',response)
if (!response || response.error) {
alert('Error occured');
} else {
alert('Post ID: ' + response.id);
}
});
}
});
}

how to save javascript variable to my sql by using spring boot controller?

I need to store email_id to my sql using spring boot. How do I send this variable to controller without using submit-form action?
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', {
locale: 'en_US',
fields: 'name, email'
},
function(response) {
var email_id = response.email;
// }
//FB.api('/me', function(response)
// {
console.log('Successful login for: ' + 'thats it');
document.getElementById('status').innerHTML =
'Thanks for logging , ' + email_id + '!';
});
You can do something like the following.
var data = new FormData();
data.append('key', 'value');
function yourAjaxFunction() {
var ajaxCall = new XMLHttpRequest();
ajaxCall.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log("Printing the response here");
console.log(this);
}
};
ajaxCall.open("GET", "Your full url here", true);
ajaxCall.send(data);
}

conversationId - Value can't be NULL

In a Word-addin I'm am trying to fetch data from AAD with the help of ADAL and microsoft.graph. Here is the code:
from app.js
var app = (function () {
"use strict";
window.config = {
instance: 'https://login.microsoftonline.com/',
tenant: '<TENANT>',
clientId: '<CLIENTID>',
redirectUri: '<THE-APP-ADDRESS>',
postLogoutRedirectUri: window.location.origin,
endpoints: {
officeGraph: 'https://graph.microsoft.com',
},
callback: userSignedIn,
popUp: true,
cacheLocation: 'localStorage'
};
function signIn() {
authContext.login();
}
function userSignedIn(err, token) {
console.log('userSignedIn called');
// showWelcomeMessage();
if (!err) {
console.log("token: " + token);
showWelcomeMessage();
}
else {
console.error("error: " + err);
}
}
function showWelcomeMessage() {
var authContext = new AuthenticationContext(config);
var $userDisplay = $(".app-user");
var $signInButton = $(".app-login");
var $signOutButton = $(".app-logout");
// Check For & Handle Redirect From AAD After Login
var isCallback = authContext.isCallback(window.location.hash);
authContext.handleWindowCallback();
if (isCallback && !authContext.getLoginError()) {
window.location = authContext._getItem(authContext.CONSTANTS.STORAGE.LOGIN_REQUEST);
}
and main.js
function getDataFromSelection() {
var baseEndpoint = 'https://graph.microsoft.com';
var authContext = new AuthenticationContext(config);
Office.context.document.getSelectedDataAsync(Office.CoercionType.Text,
function (asyncResult) {
if (asyncResult.status === Office.AsyncResultStatus.Succeeded) {
authContext.acquireToken(baseEndpoint, function (error, token) {
if (error || !token) {
app.showNotification("Ingen token: ", "Du får logga in igen." + error); // + error
}
//var email = authContext._user.userName;
var url = "https://graph.microsoft.com/v1.0/" + config.tenant + "/me";
var html = "<ul>";
$.ajax({
beforeSend: function (request) {
request.setRequestHeader("Accept", "application/json");
},
type: "GET",
url: url,
dataType: "json",
headers: {
'Authorization': 'Bearer ' + token,
}
}).done(function (response) {
html += getPropertyHtml("Namn", response.displayName);
html += getPropertyHtml("Titel", response.jobTitle);
html += getPropertyHtml("Avdelning", response.officeLocation);
html += getPropertyHtml("Telefon jobb", response.businessPhones);
$("#results").html(html);
return postDataToContentControlers(response);
}).fail(function (response) {
// app.showNotification('Inloggningen slutade att fungera!', 'Du får logga ut och prova att logga in igen'); //response.responseText
}).always(function () {
console.log("AJAX is done!!")
})
});
} else {
app.showNotification('Error:', 'Något gick fel. Du får logga in igen.'); //result.error.message
}
}
);
}
On local wordklient it works but on Word online (Office 365 Pro Plus v.1609)
I get this when running the function getDataFromSelection();
Error from console
And right Before I login and i get confirmed and a token:
the parameter ConversationId is handled when you use microsoft-graph to GET mail-messages. Every mail has a conversationId... Why is it complaining about that regarding a GET against https://graph.microsoft.com/v1.0/me ?
Does anyone know how to get around this problem or Point me in the right direction? Thanks =)
EDIT: And I forgot to mention that this works online on Google Chrome but on Microsoft Edge The popup doesn't work at all regarding login Before even fetching any data. Only popup the addin again.

Redirecting after all functions finished

I am using the Parse hosting and Cloud Code functions.
I have a button that runs a function and then redirects to the same page to refresh it after the function has been called. The cloud function that is being called by the button then calls a number of different functions from there, including a httpRequest. From what I can see, the page is refreshing after the first function has been called, not the subsequent functions and httpRequests being called later. The data on the loaded page is still displaying old data, and has to be refreshed manually to see the updated data.
Here is the code the button is triggering:
// User Control Panel -- Logic
app.post('/panel', function(req, res) {
var currentUser = Parse.User.current();
if (currentUser) {
currentUser.fetch().then(function(fetchedUser){
var username = fetchedUser.getUsername();
if (fetchedUser.get("timeRemaining") < 10) {
res.redirect("/panel");
} else if (fetchedUser.get("isRunning") == false){
Parse.Cloud.run("dockerManager", {username: username}) // Ignoring the rest of the code, this is where the cloud function is called.
res.redirect("/panel");
} else {
res.redirect("/panel");
}
}, function(error){
});
} else {
res.redirect('/panel');
}
});
This is the cloud function that is running:
Parse.Cloud.define("dockerManager", function(request, response) {
var username = request.params.username;
var override = request.params.override;
var containerID = request.params.containerID;
//other irrelevant code here
} else {
Parse.Cloud.useMasterKey();
var query = new Parse.Query(Parse.User);
query.equalTo("username", username);
query.first(function(user) {
if (user.get("dockerID") == undefined) {
Parse.Cloud.run("createDockerContainer", {username: username});
response.success("[Docker Manager] Created Docker Container for username: " + username + " with Docker ID: " + user.get("dockerID"));
} else if (user.get("isRunning") == true) {
Parse.Cloud.run("stopDockerContainer", {username: username});
response.success("[Docker Manager] Stopped Docker Container for username: " + username + " with Docker ID: " + user.get("dockerID"));
} else if (user.get("isRunning") == false) {
if (user.get("timeRemaining") >= 10){
Parse.Cloud.run("startDockerContainer", {username: username});
response.success("[Docker Manager] Started Docker Container for username: " + username + " with Docker ID: " + user.get("dockerID"));
} else {
response.error("noTime");
}
}
});
}
});
Each of the functions this is calling send a httpReqest to another server, as shown below:
Parse.Cloud.define("stopDockerContainer", function(request, response) {
var username = request.params.username;
//irrelevant code
containerID = user.get("dockerID");
Parse.Cloud.httpRequest({
method: "POST",
url: "http://[redacted address]/containers/" + containerID + "/stop",
headers: {
"Content-Type": "application/json"
},
success: function(httpResponse) {
console.log("[Docker Stopper] Stopped Docker container for user: " + username + " with ID: " + containerID);
user.set("isRunning", false);
user.save();
response.success(true);
},
error: function(httpResponse) {
console.log("[Docker Stopper][CRITICAL] Error stopping docker container for username:" + username);
console.log("Request failed with response code " + httpResponse.status);
response.error(false);
}
});
});
});
Any ideas?

how to get publish_stream permissions for post on facebook wall?

here is my connection:
window.fbAsyncInit = function () {
FB.init({
appId: "348044465251207",
status: true,
cookie: true,
xfbml: true,
oauth: true
});
FB.Event.subscribe('auth.login', function (response) {
var credentials = { uid: response.authResponse.userID, accessToken: response.authResponse.accessToken };
SubmitLogin(credentials);
}, { perms: 'read_stream,publish_stream,offline_access' });
FB.getLoginStatus(function (response) {
if (response.status === 'connected') {
FB.api('/me', function (response) {
//console.log('Good to see you, ' + response.name + '.');
mail = response.email;
currentName = response.name;
gender = response.gender;
place = response.location;
$.ajax({
url: "/Login/DetailsToDataBase",
type: "POST",
data: { gender: gender, mail: mail, place: place },
success: function (data) {
generalScore = data;
div_element = document.getElementById("userScore");
div_element.innerHTML = "Your score is: " + generalScore;
}
});
});
} //end if
else if (response.status === 'not_authorized') { alert("user is not authorised"); }
else { alert("user is not conntected to facebook"); }
}, { scope: 'read_stream,publish_stream,offline_access' });
function SubmitLogin(credentials) {
$.ajax({
url: "/Login/FacebookLogin",
type: "POST",
data: credentials,
error: function () {
alert("error logging in to your facebook account.");
},
success: function () {
// alert("success log in facebook");
// window.location.reload();
}
});
}
};
(function (d) {
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {
return;
}
js = d.createElement('script');
js.id = id;
js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
} (document));
and this is the function to post on user facebook wall:
var params = {};
params['method'] = 'stream.publish';
params['message'] = currentName +' earn '+ score+ '$ in battelship!';
params['name'] = 'BattelShip';
params['description'] = 'let\'s see if you sucsses to break my highlight';
params['link'] = 'https://apps.facebook.com/348044465251207/?fb_source=search&ref=ts&fref=ts';
params['picture'] = 'http://www.israup.net/images/98d0808995e356818a0c016bc1a2a7cc.png';
params['caption'] = 'Try it by Yourself!';
FB.api('/me/feed', 'post', params, function(response) {
if (!response || response.error) {
console.log('Error occured');
} else {
console.log('Published to stream - you might want to delete it now!');
}
});
it post only on my wall (because i am the admin of the app), but for another users it says:
"The user hasn't authorized the application to perform this action"
help me please!!
You need to look at the Login documentation again I think, you're using a parameter in part of your login flow 'perms' which was deprecated over a year ago in favour of 'scope' -
Check the examples that come with the SDK and read the login documentation, though the code might just work if you fix that error, i'd be wary of what other things have changed in the API since the example you're working from was written - you can check what permissions were granted to the access token you're using by calling /me/permissions with that access token

Categories

Resources