Problem with facebook login from the facebook application - facebook

I also encounter a problem with a project, login with facebook works on absolutely any browser, even those on mobile, but in the integrated browser in the facebook application it doesn't work, it just doesn't connect me, it sends me back to login ... can you help me with a piece of advice please? Thank you.
I used this script:
<script>
(function(){
var body = $('body');
var socialLoginErrorElm = $('#loginError');
var loginModal = $('#loginModal');
body.on('social-login:error', function(e, error) {
socialLoginErrorElm.removeClass('hide').html('<div class="alert alert-danger">' + error + '</div>');
loginModal.removeClass("logging-in");
});
window.loginWithFb = function(){
FB.login(function(response) {
if (response.authResponse) {
if(response.authResponse.grantedScopes.split(',').indexOf('email') < 0) {
//If email permission not granted
body.trigger('social-login:error', (__('fbNoEmailError')));
return;
}
FB.api('/me', {fields: 'id,name,email'}, function(response) {
console.log('Logged in as ' + response.name + '.');
//Dual check email - needed to if check if the user has a verified email ID
if(!response.email) {
body.trigger('social-login:error', (__('fbNoEmailError')));
return;
}
body.trigger('loggedIn:fb');
});
} else {
body.trigger('social-login:error', (__('fbPermissionError')));
}
}, {
scope: 'email',
auth_type: 'rerequest',
'return_scopes': true
});
}
var body = $('body');
body.on('click', '[data-action="loginWithFB"]', function(e){
loginWithFb();
e.preventDefault();
});
body.on('loggedIn', function(){
loginModal.modal('hide');
});
body.on('loggedIn:fb', function(){
if(!User.isLoggedIn()) {
$.get(BASE_PATH + '/login/fb').success(function(response){
User.setData(response.user);
}).fail(function(jqXHR, textStatus, errorThrown){
body.trigger('social-login:error', jqXHR.responseText);
}).always(function(){
loginModal.removeClass("logging-in");
});
}
});
body.on('prompt-login', function(e, message){
loginModal.find('.login-prompt-message').html(message);
loginModal.modal('show');
});
})();
function showNewPointsAlert(addedPoints) {
var alertOptions = {
title: "+"+ addedPoints +" " + __('points'),
text: __('earnedNewPointsMessage'),
imageUrl: "{{LeaderboardHelpers::getPointsIcon()}}",
confirmButtonText: __('earnedNewPointsOkayBtnText'),
allowEscapeKey: true,
allowOutsideClick: true,
customClass: 'new-points-alert'
}
#if(!empty($mainBtnColor))
alertOptions.confirmButtonColor = '{{{$mainBtnColor}}}';
#endif
swal(alertOptions);
}
$('body').on('user-activity-recorded', function() {
$.get('{{route('getMyPoints')}}').success(function(response) {
if(response && response.points) {
var oldPoints = parseInt(User.data.points);
var newPoints = parseInt(response.points);
User.data.points = newPoints;
User.setData(User.data);
if(oldPoints != newPoints) {
var animateClass = 'animated bounceIn';
$('#headerUserMenu').removeClass(animateClass).addClass(animateClass);
var addedPoints = parseInt(newPoints) - parseInt(oldPoints);
#if(MyConfig::isTrue('leaderboard.showNewPointsAlert'))
showNewPointsAlert(addedPoints);
#endif
}
}
}).fail(function() {
});
});
</script>

Related

How to set up profiles and sessions in Firebase and Ionic using Facebook Auth

I am very new to Firebase and struggling to set up a system where a user logs in via Facebook, and his/her profile picture is saved in a database.
I have a users and also a uids array in Firebase. What I want the flow to be is:
Login via Facebook
Store some memory of the user so they don't have to login again on the app, or perhaps store into the uids and users array
Get the existing name, location to fill into a profile section of the app
Update any of these to then fill into the Firebase users database, as well as add new fields e.g. location
Here is my current setup:
Login Controller:
.controller('LoginCtrl', ['Auth', '$state', '$location', '$scope', '$rootScope', '$firebaseAuth', '$window',
function (Auth, $state, $location, $scope, $rootScope, $firebaseAuth, $window) {
// check session
//$rootScope.checkSession;
// Create a callback to handle the result of the authentication
$scope.user = {
email: this.email,
password: this.password
};
$scope.validateUser = function (user) {
$rootScope.show('Please wait.. Authenticating');
console.log('Please wait.. Authenticating');
var email = this.user.email;
var password = this.user.password;
/* Check user fields*/
if (!email || !password) {
$rootScope.hide();
$rootScope.notify('Error', 'Email or Password is incorrect!');
return;
}
/* All good, let's authentify */
Auth.$authWithPassword({
email: email,
password: password
}).then(function (authData) {
console.log(authData);
//$rootScope.userEmail = user.email;
$window.location.href = ('#/app/meals');
$rootScope.hide();
}).catch(function (error) {
console.log("Login Failed!", error);
if (error.code == 'INVALID_EMAIL') {
$rootScope.notify('Invalid Email Address');
}
else if (error.code == 'INVALID_PASSWORD') {
$rootScope.notify('Invalid Password');
}
else if (error.code == 'INVALID_USER') {
$rootScope.notify('Invalid User');
}
else {
$rootScope.notify('Oops something went wrong. Please try again later');
}
$rootScope.hide();
//$rootScope.notify('Error', 'Email or Password is incorrect!');
});
};
$scope.loginWithGoogle = function () {
Auth.$authWithOAuthPopup('google')
.then(function (authData) {
$state.go($location.path('app/meals'));
});
};
$scope.loginWithFacebook = function () {
Auth.$authWithOAuthPopup('facebook')
.then(function (authData) {
console.log(authData);
$state.go($location.path('app/meals'));
})
.catch(function(error){
if (error.code === "TRANSPORT_UNAVAILABLE") {
Auth.$authWithOAuthRedirect("facebook").then(function (authData) {
// User successfully logged in. We can log to the console
// since we’re using a popup here
console.log(authData);
$state.go($location.path('app/meals'));
});
} else {
// Another error occurred
console.log(error);
}
});
};
}
])
Key functions like get session I want in $rootScope:
.run(function ($ionicPlatform, $rootScope, $firebaseAuth, $firebase, $window, $ionicLoading) {
$ionicPlatform.ready(function () {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
$rootScope.userEmail = null;
$rootScope.baseUrl = 'https://[myappurl.firebaseio.com/';
var authRef = new Firebase($rootScope.baseUrl);
$rootScope.auth = $firebaseAuth(authRef);
$rootScope.authData = authRef.getAuth();
$rootScope.show = function(text) {
$rootScope.loading = $ionicLoading.show({
content: text ? text : 'Loading..',
animation: 'fade-in',
showBackdrop: true,
maxWidth: 200,
showDelay: 0
});
};
$rootScope.hide = function() {
$ionicLoading.hide();
};
$rootScope.notify = function(text) {
$rootScope.show(text);
$window.setTimeout(function() {
$rootScope.hide();
}, 1999);
};
$rootScope.logout = function() {
authRef.unauth();
$rootScope.authDataCallBack;
};
$rootScope.checkSession = function() {
if ($rootScope.authData) {
console.log("User " + authData.uid + " is logged in with " + authData.provider);
$rootScope.userEmail = user.email;
$window.location.href = ('#/app/meals');
} else {
console.log("No session so logout");
$rootScope.userEmail = null;
$window.location.href = '#/auth/signin';
}
}
$rootScope.authDataCallBack = function(authData) {
if ($rootScope.authData) {
console.log("User " + authData.uid + " is logged in with " + authData.provider);
} else {
console.log("User is logged out");
$window.location.href = '#/auth/signin';
}
};
});
})
The profile page:
<ion-view view-title="Profile">
<ion-content class="has-header">
<div class="list card">
<div class="item">
<h2>{{user.name}}</h2>
<p>{{user.city}}</p>
</div>
<!--https://github.com/israelidanny/ion-profile-picture-->
<!--<div class="item item-body">-->
<!--<img src="http://graph.facebook.com/{{user.id}}/picture?width=270&height=270"/>-->
<!--</div>-->
</div>
</ion-content>
</ion-view>
Auth factory:
app.factory('Auth', ['rootRef', '$firebaseAuth', function (rootRef, $firebaseAuth) {
return $firebaseAuth(rootRef);
}]);
If it helps, here is my SignUpCtrl which pushes items into the users array and also stores an array of uids of users already set up in the app.
.controller('SignUpCtrl', [
'$scope', '$rootScope', '$firebaseAuth', '$window', 'Auth',
function ($scope, $rootScope, $firebaseAuth, $window, Auth) {
$scope.user = {
firstname: this.firstname,
lastname: this.lastname,
email: "",
password: ""
};
$scope.createUser = function () {
var firstname = this.user.firstname;
var lastname = this.user.lastname;
var email = this.user.email;
var password = this.user.password;
if (!email || !password) {
$rootScope.notify("Please enter valid credentials");
return false;
}
$rootScope.show('Please wait.. Registering');
$rootScope.auth.$createUser(
{email: email, password: password})
.then(function (user) {
console.log('user is created');
$rootScope.hide();
$rootScope.userEmail = user.email;
var usersRef = new Firebase('https://foodsharingapp.firebaseio.com/users');
var keyRef = usersRef.push({
'uid': user.uid,
'email': email,
'firstname': firstname,
'lastname': lastname
});
var uidRef = new Firebase('https://[myapp].firebaseio.com/uids/' + user.uid + '/' + keyRef.key());
uidRef.set({'registered': true});
$window.location.href = ('#/app/meals');
}, function (error) {
console.log('error unfortunately');
$rootScope.hide();
if (error.code == 'INVALID_EMAIL') {
console.log('invalid email');
$rootScope.notify('Invalid Email Address');
}
else if (error.code == 'EMAIL_TAKEN') {
console.log('email taken');
$rootScope.notify('Email Address already taken');
}
else {
console.log('not sure what happened');
$rootScope.notify('Oops something went wrong. Please try again later');
}
});
}
Questions:
I want to call $rootScope.authDataCallBack(authData) on any controller to get the name and any details of the user_id logged in, however this is not working. Am I thinking about this right? How can I use my $rootScope functions as ways to obtain global information?
When I log in I see the Facebook object appearing fine, should I use the Facebook ID as a uid to store in my array?
On any view, how can I use the session uid or authData to then match against my list of users in the user array and pull out more detailed user info? Is there some pseudocode I can use and would this be in every function in my controller, or would it be split between factory and controller?

PhoneGap Facebook plugin, how to get firstname, lastname, image?

how to get firstname, lastname and image from facebook user after login ?
Here is the my code
function onDeviceReady()
{
var fbLoginSuccess = function (userData) {
document.getElementById('status').innerHTML = 'success';
}
facebookConnectPlugin.login(["public_profile"],
fbLoginSuccess,
function (error) { document.getElementById('status').innerHTML = 'error'; }
);
}
function loginFb() {
openFB.loginFb(
function(response) {
if(response.status === 'connected') {
openFB.api({
path: '/me',
success: function(data) {
console.log(JSON.stringify(data));
fbUserName = data.name;
fbUserId = data.id;
fbUserPic = document.getElementById("fbuserPic").src = 'http://graph.facebook.com/' + data.id + '/picture?type=small';
}
});
}
});
}
Hello, if you have any facing problem then tell me OK.

Facebook app login issues from public user

I created Facebook app and integrated with magento, when public user try to login to the fb it shows this error.
]1
My requirement is when user login Facebook from magento site need to display user images and albums, but this process working with admin details (Getting the profile images and albums from admin details )
window.fbAsyncInit = function() {
FB.init({ appId: facebook_app_id,
status: true,
cookie: true,
xfbml: true,
oauth: true});
function updateButton(response) {
var button = document.getElementById('fb-auth');
if (response.authResponse) {
//user is already logged in and connected
document.getElementById("fbaccesstoken").value = response.authResponse.accessToken;
var userInfo = document.getElementById('user-info'),
photos_album = document.getElementById('photos_album');
FB.api('/me', function(response) {
/* userInfo.innerHTML = '<img src="https://graph.facebook.com/'
+ response.id + '/picture" />' + response.name;
button.innerHTML = 'Logout';*/
});
FB.api('/me/albums', function(response){
var l=response.data.length,
rs_all,
all_img;
if(l > 0){
rs_all ='<select id="fb_album" onchange="get_all_photos(this.value)"><option value="0">-- Select your album --</option>';
for (var i=0; i<l; i++){
var album = response.data[i],
albumid = album.id;
rs_all += '<option value="'+album.id+'">'+album.name+'</option>';
}
rs_all += '</select>';
userInfo.innerHTML = rs_all;
}
//
});
get_all_photos = function(id){
if(id==0){
photos_album.innerHTML = '';
return;
}
FB.api("/"+id+"/photos",function(response){
console.log(response);
var photos = response["data"],
pt_result = '<ul>';
for(var pt=0;pt<photos.length;pt++) {
console.log(photos[pt].images);
//pt_result += '<li><img color="" src="'+photos[pt].images[0].source+'" /></li>';
//pt_result += '<li><img color="" src="https://graph.facebook.com/' + photos[pt].id + '/picture'+'" /></li>';
pt_result += '<img src="https://graph.facebook.com/'+photos[pt].id + '/picture?access_token='+document.getElementById("fbaccesstoken").value+'" style="margin-right:5px"/>';
}
photos_album.innerHTML = pt_result+'</ul>';
});
}
button.onclick = function() {
FB.logout(function(response) {
var userInfo = document.getElementById('user-info');
userInfo.innerHTML="";
});
};
} else {
//user is not connected to your app or logged out
//button.innerHTML = 'Please Login Facebook';
button.onclick = function() {
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me', function(response) {
var userInfo = document.getElementById('user-info');
//userInfo.innerHTML =
// '<img src="https://graph.facebook.com/'
//+ response.id + '/picture" style="margin-right:5px"/>'
// + response.name;
});
} else {
//user cancelled login or did not grant authorization
}
}, {scope:'user_photos'});
}
}
}
// run once with current status and whenever the status changes
FB.getLoginStatus(updateButton);
FB.Event.subscribe('auth.statusChange', updateButton);
};
window.fbAsyncInit = function() {
FB.init({ appId: facebook_app_id,
status: true,
cookie: true,
xfbml: true,
oauth: true});
function updateButton(response) {
var button = document.getElementById('fb-auth');
if (response.authResponse) {
//user is already logged in and connected
document.getElementById("fbaccesstoken").value = response.authResponse.accessToken;
var userInfo = document.getElementById('user-info'),
photos_album = document.getElementById('photos_album');
FB.api('/me', function(response) {
/* userInfo.innerHTML = '<img src="https://graph.facebook.com/'
+ response.id + '/picture" />' + response.name;
button.innerHTML = 'Logout';*/
});
FB.api('/me/albums', function(response){
var l=response.data.length,
rs_all,
all_img;
if(l > 0){
rs_all ='<select id="fb_album" onchange="get_all_photos(this.value)"><option value="0">-- Select your album --</option>';
for (var i=0; i<l; i++){
var album = response.data[i],
albumid = album.id;
rs_all += '<option value="'+album.id+'">'+album.name+'</option>';
}
rs_all += '</select>';
userInfo.innerHTML = rs_all;
}
//
});
get_all_photos = function(id){
if(id==0){
photos_album.innerHTML = '';
return;
}
FB.api("/"+id+"/photos",function(response){
console.log(response);
var photos = response["data"],
pt_result = '<ul>';
for(var pt=0;pt<photos.length;pt++) {
console.log(photos[pt].images);
//pt_result += '<li><img color="" src="'+photos[pt].images[0].source+'" /></li>';
//pt_result += '<li><img color="" src="https://graph.facebook.com/' + photos[pt].id + '/picture'+'" /></li>';
pt_result += '<img src="https://graph.facebook.com/'+photos[pt].id + '/picture?access_token='+document.getElementById("fbaccesstoken").value+'" style="margin-right:5px"/>';
}
photos_album.innerHTML = pt_result+'</ul>';
});
}
button.onclick = function() {
FB.logout(function(response) {
var userInfo = document.getElementById('user-info');
userInfo.innerHTML="";
});
};
} else {
//user is not connected to your app or logged out
//button.innerHTML = 'Please Login Facebook';
button.onclick = function() {
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me', function(response) {
var userInfo = document.getElementById('user-info');
//userInfo.innerHTML =
// '<img src="https://graph.facebook.com/'
//+ response.id + '/picture" style="margin-right:5px"/>'
// + response.name;
});
} else {
//user cancelled login or did not grant authorization
}
}, {scope:'user_photos'});
}
}
}
// run once with current status and whenever the status changes
FB.getLoginStatus(updateButton);
FB.Event.subscribe('auth.statusChange', updateButton);
};
First of all, as the error message tells you, your App is in development mode. Got to the "Status & Review" tab of your App and use the switch next to this text:
Do you want to make this app and all its live features available to the general public?
That being said, you need to go through a review process with user_photos or that permission will only work for users with a role in your App. Everything you need to know about Login Review can be found here: https://developers.facebook.com/docs/facebook-login/review
Btw, you don´t need getLoginStatus AND subscribing to the event auth.statusChange. Here is a tutorial with detailed explanation about everything you need for login and refreshing the Access Token for returning users: http://www.devils-heaven.com/facebook-javascript-sdk-login/

Facebook JS SDK -Access Tokens unable to post actions

When I use the code below nothing happens,I am unable to understand why this is so
function graphStreamPublish(){
var passString = '?[OBJECT]=http://entrancesuccess.net&access_token=' + accesstoken;
FB.api('/me/[APPNAMESPACE]:[ACTION]' + passString,'post',
function(response) {
showLoader(false);
if (!response || response.error) {
alert('Error occured');
} else {
alert('Post ID: ' + response.id);
}
});
}
but, when I just simply copy-paste the Access Token(YTWYDGFXVVZG456AVGAFV45HGCZXHGFACGFCGFXDG546FXGFXJGFXGFXGXFJXGFXG) in the variable "passString" everything works fine and actions are published on user activity on facebook.
Example:
function graphStreamPublish(){
var passString = '?[OBJECT]=http://entrancesuccess.net&access_token=YTWYDGFXVVZG456AVGAFV45HGCZXHGFACGFCGFXDG546FXGFXJGFXGFXGXFJXGFXG';
The rest of the code is below(if required):
window.fbAsyncInit = function() {
FB.init({ appId: 'XXXXXXXXXXXXX', //change the appId to your appId
status: true,
cookie: true,
xfbml: true,
oauth: true});
showLoader(true);
function updateButton(response) {
button = document.getElementById('fb-auth');
userInfo = document.getElementById('user-info');
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:'publish_stream,public_action'});
}
}
}
// 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);
}
I’d say there is no variable accesstoken in your function graphStreamPublish.
You’re using the var keyword in the function login, which makes it a local variable – so it’s contents are thrown away once that function is done.
You could do the assignment without var, then it’d be a global variable, and graphStreamPublish should be able to access it.
But normally you should not need to pass the access token explicitly at all, because the JS SDK is perfectly capable of passing it by itself in the background, without any need for you to pass it around actively by yourself.

Childbrowser plugin not working in Phonegap

I'm using Backbone, Require and Underscore Bundled with Phonegap or Cordova.
I tried using the childbrowser plugin but it wont work. I followed the instructions here.
http://blog.digitalbackcountry.com/2012/03/installing-the-childbrowser-plugin-for-ios-with-phonegapcordova-1-5/
define([
'jquery',
'backbone',
'underscore',
'base64',
'mobile',
'const',
'child',
'text!template/login/login.tpl.html'
],function($, Backbone, _, base64, Mobile, Const, ChildBrowser, template){
var EncodeAuth = function(user,pass)
{
var _tok = user + ':' + pass;
var _hash = Base64.encode(_tok);
return "Basic "+ _hash;
}
var LoginView = Backbone.View.extend({
events:{
"click .login-btn" : "Login",
"click .connection-btn" : "OpenSite"
},
initialize: function(){
},
Login: function(){
Const.USERNAME = $("#username").val();
Const.PASSWORD = $("#password").val();
if(!Const.USERNAME || !Const.PASSWORD)
{
navigator.notification.alert("Invalid Username/Password!");
$("input").val("");
}else{
var auth = EncodeAuth(Const.USERNAME,Const.PASSWORD);
var sendAuthorization = function (xhr) {
xhr.setRequestHeader('Authorization', auth)
};
this.model.save(this.model, {
beforeSend : sendAuthorization,
success: function(model,result){
if(result.ErrorMessage === null)
{
alert(JSON.stringify(result.Message));
$("input").val("");
}
else
{
alert(JSON.stringify(result.ErrorMessage));
$("input").val("");
}
},
error: function(model,result){
alert("Remote server returned an error. Not Found");
$("input").val("");
}
});
}
},
OpenSite: function(){
window.plugins.ChildBrowser.showWebPage("http://www.google.com");
}
});
return LoginView;
});
Any ideas?