How to logout only my FBapplication not my facebook account? - javascript

I am using facebook javascript sdk on my web application. I am using graph api to login my application. When I logged out from my application, my application is logged out and my facebook account is also logout.
How to logout only my application not my facebook account ?
Please help me if someone has found solution for this.
Code:
<script type="text/javascript">
var button;
var userInfo;
window.fbAsyncInit = function() {
FB.init({ appId: '########',
status: true,
cookie: true,
xfbml: true,
oauth: true});
showLoader(true);
function updateButton(response) {
button = document.getElementById('fb-auth');
userInfo = document.getElementById('user-info');
userdata = document.getElementById('user-data');
if (response.authResponse) {
//user is already logged in and connected
FB.api('/me', function(info) {
login(response, info);
});
button.onclick = function() {
FB.logout(function(response) {
logout(response);
});
};
} else {
//user is not connected to your app or logged out
button.innerHTML = 'Login';
button.onclick = function() {
showLoader(true);
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me', function(info) {
login(response, info);
});
} else {
//user cancelled login or did not grant authorization
showLoader(false);
}
}, {scope:'email,user_birthday,status_update,publish_stream,user_about_me'});
}
}
}
// run once with current status and whenever the status changes
FB.getLoginStatus(updateButton);
FB.Event.subscribe('auth.statusChange', updateButton);
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol
+ '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
function login(response, info){
if (response.authResponse) {
var accessToken = response.authResponse.accessToken;
userInfo.innerHTML = '<img src="https://graph.facebook.com/' + info.id + '/picture">' + info.name
+ "<br /> Your Access Token: " + accessToken;
button.innerHTML = 'Logout';
showLoader(false);
document.getElementById('other').style.display = "block";
}
}
function logout(response){
userInfo.innerHTML = "";
document.getElementById('debug').innerHTML = "";
document.getElementById('other').style.display = "none";
showLoader(false);
}
//stream publish method
function streamPublish(name, description, hrefTitle, hrefLink, userPrompt){
showLoader(true);
FB.ui(
{
method: 'stream.publish',
message: '',
attachment: {
name: name,
caption: '',
description: (description),
href: hrefLink
},
action_links: [
{ text: hrefTitle, href: hrefLink }
],
user_prompt_message: userPrompt
},
function(response) {
showLoader(false);
});
}
function showStream(){
FB.api('/me', function(response) {
//console.log(response.id);
streamPublish();
});
}
function share(){
showLoader(true);
var share = {
method: 'stream.share',
u: 'http://www.appovative.com/'
};
FB.ui(share, function(response) {
showLoader(false);
console.log(response);
});
}
function setStatus(){
showLoader(true);
status1 = document.getElementById('status').value;
FB.api(
{
method: 'status.set',
status: status1
},
function(response) {
if (response == 0){
alert('Your facebook status not updated. Give Status Update Permission.');
}
else{
alert('Your facebook status updated');
}
showLoader(false);
}
);
}
function showLoader(status){
if (status)
document.getElementById('loader').style.display = 'block';
else
document.getElementById('loader').style.display = 'none';
}
</script>

Their is function defined in FB object use this to destroy FB session ,
usage( via PHP)
$facebook->destroySession();
Or
FB API provides a logoutURL which will log the user out of their current Facebook account.
you can use it like this ,
$facebook = new Facebook($config);
$params = array('next' => 'www.yousite.com/test.php' );
$logoutURL = $facebook->getLogoutUrl($params);
***note
advisable to add below codes also (not in case if you dont want your user to log out of your site)
//remove PHPSESSID from browser
if ( isset( $_COOKIE[session_name()] ) )
setcookie( session_name(), '', time()-7000000, '/' );
//clear session from globals
$_SESSION = array();
With JS using a custom event
ref : (FB.logout() called without an access token. javascript sdk)
function fbLogoutUser() {
FB.getLoginStatus(function(response) {
if (response && response.status === 'connected') {
FB.logout(function(response) {
document.location.reload();
});
}
});
}

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);
}

How to return authRequired and WL.Server.invokeHttp value to client side using web services in Adapter based authentication with worklight?

Edit : I am using Adapter based authentication with worklight and angularJs. on click of login button i'm calling submitLogin procedure and pass the username and password in parameter as mention below. my query is after invocation of adapter how i'll return the authRequired value and WL.Server.invokeHttp(input) response simultaneously to the client side. i also mention challenge handler for authentication in login services code
adapter code:
function submitLogin(username, password){
WL.Logger.debug("username: "+username);
var payload = {
"Header": {
"header": {
"myschemeName": "",
"myserviceVersion": "0.00",
"myinternalId": "",
"myexternalId": "",
"mysource": "web",
"mydestination": "test",
"myuserId": ""
}
},
"Body": {
"login": {
"username": username,
"password": password
}
}
}
var input = {
method : 'post',
returnedContentType : 'jsonp',
path: '/mywebservices/login',
headers : {
'Accept-Encoding': 'gzip,deflate',
'Content-Type': 'application/json'
},
body: {
'contentType' : 'application/json',
'content' : payload
}
};
return {authRequired: false, WL.Server.invokeHttp(input);};
}
login services:
angular.module('my.services')
.factory('loginServices', function($http, $q, $rootScope) {
'use strict';
//worklight
var realm = "AdapterAuthRealm";
var securityTest = "Master-Password";
//offline
var offlineAuthed = false;
var tempUser = {};
//user object
var userObj = {};
//login popup
userObj.dialog = false;
//login error message
userObj.authError = "";
//logged in boolean
userObj.loggedIn = null;
var defunct = null;
//change handler
var ch = WL.Client.createChallengeHandler(securityTest);
//first response after protected call
ch.isCustomResponse = function(response){
console.log("challenge handler -- isCustomResponse");
if (!response || !response.responseJSON || response.responseText === null) {
return false;
}
if (typeof(response.responseJSON.authRequired) !== 'undefined'){
return true;
} else {
return false;
}
};
//when isCustomResponse returns true
ch.handleChallenge = function(response){
console.log("challenge handler -- handleChallenge");
var err = response.responseJSON.errorMessage;
var req = (String(response.responseJSON.authRequired) == "true");
if (!req){ //successful login request
console.log("-> login success!");
//create offline auth credentials
createOfflineAuth();
//call the success function of initial adapter call
//ch.submitSuccess();
}
//error message
userObj.authError = "";
if (err != null){
userObj.authError = "* " + err;
}
//login boolean
userObj.loggedIn = !req;
//show login popup
userObj.dialog = req;
//update scope
$rootScope.$apply();
//resolve original function if it exists
if (defunct != null){
defunct.resolve(userObj.loggedIn);
}
};
//** Offline **//
//check if user is online
function checkOnline(){
var def = $q.defer();
WL.Client.connect({
onSuccess: function(){
console.log("** User is online!");
def.resolve(true);
},
onFailure: function(){
console.log("** User is offline!");
def.resolve(false);
},
timeout: 1000
});
return def.promise;
}
//creates an offline authentication object
function createOfflineAuth(){
console.log("creating offline auth");
//encrypt the user object
var encyptedUser = md5(angular.toJson(tempUser));
//save to local storage
localStorage.setItem(tempUser.username, encyptedUser);
//clear tempUser
tempUser = {};
}
//offline login
function offlineLogin(){
userObj.authError = "";
//encrypt the tempuser object
var match = md5(angular.toJson(tempUser));
var savedAuth = localStorage.getItem(tempUser.username);
//check if matching the saved one
offlineAuthed = (savedAuth == match);
console.log("Login successfull: " + offlineAuthed);
//error - mismach
if (!offlineAuthed){
userObj.authError = "* Wrong login details.";
}
//error - if the user has never authenticated with the server
if (savedAuth == null){
userObj.authError = "* You have to go online first.";
}
//login boolean
userObj.loggedIn = offlineAuthed;
//show login popup
userObj.dialog = !offlineAuthed;
return offlineAuthed;
}
//-- APIS to the rest of the app --//
return {
getUser: function(){
return userObj;
},
initUser: function () {
console.log("-> getting user state data");
var def = $q.defer();
checkOnline().then(function (onl){
if (onl){ //online
WL.Client.updateUserInfo({onSuccess: function(){
userObj.loggedIn = WL.Client.isUserAuthenticated(realm);
def.resolve();
}});
} else { //offline
userObj.loggedIn = false;
def.resolve();
}
});
return def.promise;
},
checkUser: function () {
var def = $q.defer();
checkOnline().then(function (onl){
if (onl){ //online
userObj.loggedIn = WL.Client.isUserAuthenticated(realm);
} else { //offline
userObj.loggedIn = offlineAuthed;
}
userObj.dialog = !userObj.loggedIn;
//check success
if (!userObj.loggedIn){
//save the deferred for challengehandler
defunct = def;
} else {
//resolve
def.resolve(true);
}
});
return def.promise;
},
login: function (user,pass){
//promise
var logindef = $q.defer();
//tempuser
tempUser = {username:user, password:pass};
userObj.user = user;
checkOnline().then(function (onl){
if (onl){ //online
console.log("attempting online login");
var options = {
parameters:[user, pass],
adapter:"myAdapter",
procedure:"submitLogin"
};
ch.submitAdapterAuthentication(options,{
onSuccess: function(){
console.log("-> submitAdapterAuthentication onSuccess!");
//update user info, as somehow isUserAuthenticated return false without it
WL.Client.updateUserInfo({onSuccess: function(){
//return promise
logindef.resolve(true);
}});
}
});
} else { //offline
console.log("attempting offline login");
logindef.resolve(offlineLogin());
}
});
return logindef.promise;
}
};
});
I am trying to decrypt your question. It's not clear at all.
However there is already one thing that jumps out.
In your adapter you finished with:
return {authRequired: false, WL.Server.invokeHttp(input);};
You saying authRequired false even before checking if the credentials are valid?
You are supposed to parse the content of the results of WL.Server.invokeHttp(input) inside the adapter, decide if the credentials are valid.
If they are valid use setActiveUser before returning authRequired false.
Don't return the content of WL.Server.invokeHttp(input) to the client. This is meant for the adapter to parse.
See this tutorial: https://developer.ibm.com/mobilefirstplatform/documentation/getting-started-7-1/foundation/authentication-security/adapter-based-authentication/

Sign Up user with facebook in firebase

Hi every one I am trying to sign up users in my app using facebook connect botton. That is when the user click the button I check if it is first time i store some of his informatios if it is not his first time i just ligged into the app .Now I can logged the user when he click the botton get his information as showing bellow. My problem is to save those informations in my Firebase App but it is not working. Please any help will be great
//Here is the snapshot of my controller
var app = angular.module("yopi", ["firebase"]);
app.controller("EventCtrl", function($scope, $firebase, $window) {
var ref = new Firebase("https://yopi.firebaseio.com/");
window.fbAsyncInit = function() {
FB.init({
appId : 'MY API', // Set YOUR APP ID/
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
FB.Event.subscribe('auth.authResponseChange', function(response)
{
if (response.status === 'connected')
{
document.getElementById("message").innerHTML += "<br>Connected to Facebook";
//SUCCESS
}
else if (response.status === 'not_authorized')
{
document.getElementById("message").innerHTML += "<br>Failed to Connect";
//FAILED
} else
{
document.getElementById("message").innerHTML += "<br>Logged Out";
//UNKNOWN ERROR
}
});
};
$scope.Login = function()
{
FB.login(function(response) {
if (response.authResponse)
{
getUserInfo();
getPhoto();
$window.location.href = "https://yopevent.firebaseapp.com/events.html";
} else
{
console.log('User cancelled login or did not fully authorize.');
}
},{scope: 'email,user_photos,user_videos'});
}
function getUserInfo() {
FB.api('/me', function(response) {
UserId = response.id;
UserName = response.name;
UserEmail = response.email;
});
}
function getPhoto()
{
FB.api('/me/picture?type=normal', function(response) {
$scope.Id = UserId;
$scope.Name = UserName;
$scope.Email = UserEmail;
$scope.PicUrl = response.data.url;
var newUser = {
UserId: $scope.Id,
UserName: $scope.Name,
UserEmail: $scope.Email,
UserPicUrl: $scope.PicUrl
};
//Here no probleme Iamgeting the oblect correctly in the console.
console.log(newUser);
//but the problem is here this is not svaing this objet in firebase
ref.child("users").child($scope.Id).set(newUser);
var str="<br/><b>Pic</b> : <img src='"+response.data.url+"'/>";
document.getElementById("status").innerHTML+=str;
});
}
$scope.Logout = function()
{
FB.logout(function(){document.location.reload();});
}
// Load the SDK asynchronously
(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));
});

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