When clicking on login with facebook/persona button with angularFire v0.5.0 ($firebaseAuth) user gets redirected immediately to '/'.Why? - facebook

My problem is simple, everything in this code works as expected except that everytime, I click on login button, I get redirected to '/'. I do not want that. I want the user to stay on login page until they finish authenticating via facebook/persona/twitter and then get redirected to '/content'.
Here is my router/app/controllers:
var app = angular.module("myapp", ["ngRoute","firebase"]);
app.config(['$routeProvider',function($routeProvider){
$routeProvider.when('/',{
templateUrl: 'landing.html',
});
$routeProvider.when('/login',{
templateUrl: 'login.html',
controller: 'controller'
});
$routeProvider.when('/content',{
authRequired: true,
templateUrl: 'content.html',
controller: 'MyController'
});
$routeProvider.otherwise({redirectTo: '/'});
}]);
app.controller('MyController',['$scope', '$firebase','$firebaseAuth',function($scope,$firebase,$firebaseAuth) {
var ref = new Firebase("https://mybase.firebaseio.com/");
$scope.auth = $firebaseAuth(ref,{path: '/'});
$scope.messages = $firebase(ref);
$scope.addMessage = function(e) {
if (e.keyCode != 13) return;
$scope.messages.$add({from: $scope.name, body: $scope.msg});
$scope.msg = "";
};
}]);
app.controller('controller',['$scope','$firebaseAuth',function($scope, $firebaseAuth) {
var ref = new Firebase('https://mybase.firebaseio.com/');
$scope.auth = $firebaseAuth(ref);
}]);
This (my preferred solution) didnt work either:
.controller('LoginCtrl',['$scope','$firebase','$firebaseAuth','$location',function($scope,$firebase,$firebaseAuth,$location, waitForAuth){
var ref = new Firebase('https://myfirebase.firebaseio.com/');
$scope.auth = $firebaseAuth(ref,{path: '/'});
waitForAuth.then(function(user){
$location.path('/content');
})
}])
My div/button looks as follows (I also have similar one but with 'persona'.):
<div ng-controller="controller">
<div class="facebook-login">
<span><i class="fa fa-facebook-square fa-lg"></i> LogIn with Facebook</span>
</div>
<div class="facebook-login">
<span><i class="fa fa-facebook-square fa-lg"></i> LogIn with Persona</span>
</div>
</div>
I have included the following in my html:
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.min.js"></script>
<script src="//cdn.firebase.com/v0/firebase.js"></script>
<script src="//cdn.firebase.com/v0/firebase-simple-login.js"></script>
<script src="//cdn.firebase.com/libs/angularfire/0.5.0/angularfire.min.js"></script>
<script src="//code.angularjs.org/1.2.6/angular-route.js"></script>
<script src="js/app.js"></script>
<script src="js/module.waitForAuth.js"></script>
<script src="//login.persona.org/include.js"></script>
<script src="app.js"></script>
I have enabled facebook login and persona login in my firebase forge. Also I have added my facebook app id and secret too. Everytime I click on the login button I get redirected to '/'. waitforAuth I use is here: https://gist.github.com/katowulf/7328023, but if I use it in my controllers, login with facebook/persona buttons do not work at all. If I use waitForAuth, everytime I click on one of the login buttons I get redirected to '/' immediately instead of login popup.
Anyone? :)

I finally found the solution to my problem. Adding the following stops automatic redirect to '/' before login even takes place:
I just needed to add this:
$scope.$on('$locationChangeStart', function(event) {
event.preventDefault();
});
In here like this:
app.controller('controller',['$scope','$firebaseAuth','$location','$rootScope',function($scope, $firebaseAuth,$location,$rootScope) {
$scope.$on('$locationChangeStart', function(event) {
event.preventDefault();
});
var ref = new Firebase('https://mybase.firebaseio.com/');
$scope.auth = $firebaseAuth(ref);
$rootScope.$on('$firebaseAuth:login', function(){
$location.path('/content');
});
}]);
However, I ran into another problem, because this now doesnt work:
$rootScope.$on('$firebaseAuth:login', function(){
$location.path('/content');
Because after user is finished authenticating they should be redirected to /content (instead of being stuck at login page with login buttons disappearing due to ng-hide (See above)), but it does not matter what I try $location.path('/content') doesnt work.
I tried this:
waitForAuth.then(function(){
console.log('test');
$location.path('/content');
})
But console.log prints out "test" in the console way before user is authenticated, so waitForAuth doesnt seem to work either :/. Somehow waitForAuth fires console.log but it doesnt fire $location.path... Odd.
I even tried doing this (both with waitForAuth and $rootScope.$on:
waitForAuth.then(function(){
console.log('test');
$location.path('/content');
$scope.$apply();
})
But I just get an error that angular $digest is already in progress.
Adding this: ng-click="auth.$login('facebook'); return false;" like that, angular throws me this error :
Error: [$parse:syntax] Syntax Error: Token 'false' is an unexpected token at column 33 of the expression [auth.$login('facebook'); return false;] starting at [false;].
And login buttons become un-clickable... :(
Ohh dear... me :)

I had the same problem where the URL was always reverting back to the homepage. The problem was caused by a simple mistake in the html syntax:
Log out
After I removed # in the href attribute the problem was resolved. Hope this helps others who may experience a similar problem.

Related

ng-click and ngRouting on mobile devices

I am completely new to Angularjs and haven’t been doing any code for ages. I started setting up my website again with Angularjs. I have a main page and an about page, to which the user gets via ngRoute on ng-click (or hitting space). Once on the about page, the user can go back by clicking somewhere on the page and so on.
App.js
var app = angular.module("MyApp", ["ngRoute"]);
app.config(function($locationProvider, $routeProvider) {
$routeProvider
.when("/teaser", {
controller:"teaserCtrl",
templateUrl:'teaser.html'
})
.when("/about", {
controller:"aboutCtrl",
templateUrl: "about.html"
})
.otherwise({
redirectTo:"/teaser"
})
});
app.controller("mainCtrl", function($scope, $http, $location) {
$scope.v = {
inverted: false,
display: true,
offwhite: true,
}
$scope.$on("space", function() {
if ($scope.v.teaser) {
$location.path("/about")
$scope.v.teaser = false
} else {
$location.path("/teaser")
$scope.v.teaser = true
}
$scope.$apply()
})
$scope.goHome = function(){
$scope.$broadcast("goHome")
}
});
app.directive("ngMobileClick", [function () {
return function (scope, clickElement, attrs) {
clickElement.bind("touchstart click", function (e) {
e.preventDefault();
e.stopPropagation();
scope.$apply(attrs["ngMobileClick"]);
});
}
}])
HTML
<body ng-controller="mainCtrl as main" ng-mobile-click="goHome()" ng-class="{inverted: v.inverted, bg: v.offwhite}" space>
<div class="content" ng-view ng-hide="v.display"></div>
//My body code
<script ng-init="sw = 'some website'; id="about.html" type="text/ng-template">
<div class="about">
<p class="text" ng-click="next(); $event.stopPropagation()">
<p>some text</p>
<br>
<a ng-href="{{mail}}" ng-click="$event.stopPropagation()">some address</a>
</p>
</div>
</script>
</body>
The code for the about page is written into a script and it has hyperlinks (ng-href). Now my issue: As you can see, I changed my ng-click to ng-mobile-click for the body-section. If I also change it in the script for the hyperlinks, something weird is happening which I can’t really figure out (links change to hover color, but still no redirection to the ng-href.
For the desktop version, the click is triggering ngRoute, but I can also click the links. For the mobile version this is not possible any more. Any ideas how I can fix this? I know, there is no hovering possible, but somehow I need to detect the hyperlinks also on mobile devices without being redirected to the main-page.
As I said: this is my first try with Angularjs and I haven’t done any code for a while, please be as clear as possible!
There is another controller for teaser/about which I haven’t put here, as well as the directive for the keyup.
Any ideas or suggestions? Thank you so much in advance!

FB is not defined in Facebook Login

I have the following code but the FB.login gives a FB is not defined javascript error.
What am I missing?
<html>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function()
{
FB.init
({
appId : 'XXXX',
status : true,
cookie : true,
xfbml : true
});
};
(function()
{
var e = document.createElement('script');
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
FB.login(function(response)
{
if(response.session)
{
if(response.perms)
{
alert('yippee');
}
else
{
alert('oh no');
}
}
else
{
alert('login silly');
}
}, {perms:'email,user_birthday'});
</script>
hello
<fb:login-button></fb:login>
</body>
</html>
The function assigned to window.fbAsyncInit is run as soon as the SDK is loaded. Any code that you want to run after the SDK is loaded should be placed within this function and after the call to FB.init. For example, this is where you would test the logged in status of the user or subscribe to any Facebook events in which your application is interested.
Try by keeping other initialization code in between inialization and login function
Or keep FB.login code in $(document).ready
$(document).ready(function(){
FB.login(function(response)
{
if(response.session)
{
if(response.perms)
{
alert('yippee');
}
else
{
alert('oh no');
}
}
else
{
alert('login silly');
}
}, {perms:'email,user_birthday'});
});
You should not call to FB.login before JS-SDK is loaded, window.fbAsyncInit designed especially for this. If you move this call to be within window.fbAsyncInit function you'll be fine but be aware of fact that calling to FB.login opens popup, doing this without user interaction will be probably blocked by most browsers. If you want to use FB.login to handle login, you must do it on click or sumbit events...
BTW, you already have fb:login-button which is doing login once user clicks on it.
You can also get this error if you try to launch the facebook example code on your machine (e.g. copying the code in a .html file and trying to open it in your browser). You will need to upload this to your server and run it from there.

Facebook FB.Event.subscribe "bug" with the edge.create callback

Im fancing a really weird problem with the edge.create callback.
What im doing is to execute an ajax call to the server each time an edge.create or edge.remove event occurs (the firs is to like and the second to unlike a page).
Heres the code
// this will fire when any of the like widgets are "liked" by the user
FB.Event.subscribe('edge.create', function(href, widget) {
var dataSend = 'ajaxFace=true&submitAdd=true&code='+SomeCodeToAdd;
$.ajax({
type: 'POST',
url: 'http://somewebpage.com',
data: dataSend,
success: function(data) {
alert(data);
},
erro: function(data) {
alert('Try again later');
}
});
});
//this will fire when any widgets are "disliked" by the user
FB.Event.subscribe('edge.remove', function(href, widget){
var dataSend = 'ajaxFace=true&submitDelete=true&code='+SomeCodeToRemove;
$.ajax({
type: 'POST',
url: 'http://somewebpage.com',
data: dataSend,
success: function(data) {
alert(data);
},
erro: function(data) {
alert('Try again later');
}
});
});
Now, whats happening.
The function for the 'edge.remove' event works smooth and without any problems.
But when the user click like the code simply dont run on the success part of the ajax call, i tryed a simple alert like alert('test'); but nothing happens too. The code, however, works fine on the backend and the code I want to add is added with success.
However if i set the async : false the code works, the alerts is presented on the page but the browser gets that nasty "lock down" that i really want to avoid.
So, anyone have any idea whats exactly going on here?
PS.: Theres 2 others facebook elements on this page, the comments and activity feed. I dont know but im with the impression that the activity feed may have something to do with this...
I think this is some sort of scope issue. If you define the function containing the ajax call outside of the scope of the FB.Event.subscribe, and just call that function from within the FB.Event.subscribe, that may fix the issue.
HI i was facing the same problem but for different FB event. Here is my code an it 100% working :-
<!doctype html>
<html lang="en" xmlns:fb="https://www.facebook.com/2008/fbml">
<head>
<meta charset="utf-8">
<title>Facebook Like Button</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>--->(DO not forget to include)
</head>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({appId: '464134126954048', status: true, cookie: true,xfbml: true});
FB.Event.subscribe("message.send", function(targetUrl) {
$.ajax({
url:'abc.php',
type:'POST',
data:{name:'sunlove'},
success:function(data)
{
alert("I am here");
}
});
});
};
(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);
}());
</script>
<fb:send href="http://demo.antiersolutions.com/studybooster1.2"></fb:send>
<script type="text/javascript" src="http://platform.twitter.com/widgets.js"> </script>
</body>
</html>
You can just copy and make new file and customize according to your need

JS SDK FB.login() works but pop-up dialog is staying open after logged in

I am using the JS SDK for Facebook based on the NEW GraphAPI for Auth/Login.
Has anyone had this issue when logging in after FB.login() was called via the JS SDK?
The problem: after I initialize by calling FB.Init() asynchronously (because this all wrapped in a window.fbAsyncInit function) the login pops up; I log in but then that pop-up refreshes to show a white page and the pop-up stays open and does not close...why? I am waiting to check response.session in the FB.login() callback but it seems as though I never get it back because this pop-up seems to just stick there and the process appears to just halt after you're logged in and I just figured this pop-up would just close and return me the response.session in the callback automatically. Why would that pop-up not go away?
I copied the url from the pop-up after I'm logged in and showing white the following url so it looks like the response is there but then why isn't that pop-up window closing so my callback can handle the response??
http://static.ak.fbcdn.net/connect/xd_proxy.php#?=&cb=f18fe0b7c66da54&origin=http%3A%2F%2Flocalhost%2Ff3745f32ed63a7a&relation=opener&transport=postmessage&frame=f18adb488566372&result=user_photos&session={%22session_key%22%3A%222.vH4SVCisnh8HJWjEI1Vy_Q__.3600.1280106000-100001379631246%22%2C%22uid%22%3A%22100001379631246%22%2C%22expires%22%3A1280106000%2C%22secret%22%3A%22TH45WFg8I_5r_cOoVIujjg__%22%2C%22access_token%22%3A%22132444323462464|2.vH4SVCisnh8HJWjEI1Vy_Q__.3600.1280106000-100001379631246|q123iPQcKY45xWXtOZ2ebOOZTQQ.%22%2C%22sig%22%3A%22a75e85af2354292bfdcf90b9d319ebf7%22}
I did notice that when FB.login() is called and the login pop-up comes up, I see this error in FireBug talking about how it doesn't like the fact that I'm testing over localhost or something I guess:
uncaught exception: [Exception... "Component returned failure code: 0x80004005 (NS_ERROR_FAILURE) [nsIDOMLocation.host]" nsresult: "0x80004005 (NS_ERROR_FAILURE)" location: "JS frame :: chrome://smarterwiki/content/smarterwiki.js :: anonymous :: line 1225" data: no]
that error bothers me...I need to figure out why it's coming up and I bet you I'm not the only one who has seen this when testing locally. I see no info though on troubleshooting this on the net anywhere either on the Facebook forums or elsewhere. I see others have had this issue but no resolution.
So when you implemented yours, did your facebook pop-up just close after the user is logged in or did you need to do something special to finish this process?
Also, I notice if I manually close that pop-up then go to check if that cookie was generated to contain my session, it's not (the fbs_[yourappid] cookie). So it looks like something ends prematurely here. I've got in my init cookie: true so I wonder if this problem were the pop-up dialog is not closing is related to the cookie also not being created client-side on my test PC.
This problem appeared out of nowhere for my site, when facebook made a recent change to its "all.js".
In an earlier version of their javascript I had a problem specific to IE, and I copied this little snippet of code from someone's post on the internet. It seemed cryptic, but solved the problem at the time:
// http://developers.facebook.com/bugs/204792232920393
// Hack to fix http://bugs.developers.facebook.net/show_bug.cgi?id=20168 for IE7/8/9.
FB.UIServer.setLoadedNode = function (a, b) { FB.UIServer._loadedNodes[a.id] = b; };
FB.UIServer.setActiveNode = function(a, b) { FB.UIServer._active[a.id]=b; };
It turns out those lines were causing this problem for me. I removed them, and the problem went away. The original bug specific to IE has also been fixed, I believe, in the most recent "all.js".
I don't know what your code is, but my problem was I forget to add
<div id="fb-root"></div>. My code :
<div id="fb-root"></div>
<script src="http://static.ak.fbcdn.net/connect/en_US/core.js"></script>
<script>
FB.init({ apiKey: 'app key'});
</script>
<div class="fbloginbutton" id="fb-login" onclick="Login();">
<span id="fb_login_text" >Login with Facebook</span>
</div>
<asp:Label ID="errMsg" runat="server"></asp:Label>
<script type="text/javascript">
function Login() {
FB.login(function(response) {
document.getElementById('fb_login_text').innerHTML = 'Logout';
if (response.session) {
FB.api('/me', function(response) {
var str;
str = response['id'] + ";" +
response['name'] + ";" +
response['first_name'] + ";" +
response['last_name'] + ";" +
response['link'] + ";" +
response['birthday'] + ";" +
response['gender'] + ";" +
response['email'];
alert(str);
});
}
else {
document.getElementById('fb_login_text').innerHTML = 'Login with Facebook';
}
}, { perms: 'user_birthday,email' });
};
</script>
As you see I don't use div fb-root anywhere but It is requered to facebook login work!
I struggled with this issue recently. The problem appeared from no where, presumably from some change in the Facebook JS SDK. For what its worth I plan to never use the JS SDK again, these random issues eat up my time.
Anyway here is the hack that I used to get around the issue.
var accessToken, fb_response;
if (window.location.hash.length < 30) {
window.location = "http://www.facebook.com/dialog/oauth?client_id=YOUR_ID&redirect_uri=YOUR_URL&scope=YOUR_PERMISSIONS&response_type=token";
} else {
fb_response = window.location.hash;
accessToken = fb_response.substr(14, fb_response.indexOf("&expires") - 14);
FB._authResponse = {
accessToken: accessToken
};
window.location.hash = "";
FB.api("/me", function(profile) {
if (profile.id) {
app_init();
} else {
alert("Problem connecting to Facebook");
}
});
}
Basically I send the user to the Facebook oauth dialog and when they return I grab the access token from the hash. I then set the internal access token parameter on the Facebook Object. Once this is done you can make all the normal Facebook Api calls.
Hopefully this helps someone!
For future projects I will definitely stick to a server side auth flow, you have a lot more control!
It seems that you are trying the localhost, can you try it with the public url.
I already faced this problem. But I solved it by configuring the canvas url in application as the public url (example. www.something.com/test/).
This is a working sample for me:
<!DOCTYPE html>
<html>
<head>
<title>Facebook Client-side Authentication Example</title>
</head>
<body>
<div id="fb-root"></div>
<script>
// 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));
// Init the SDK upon load
window.fbAsyncInit = function() {
FB.init({
appId : '00000000000000', // Your App ID
channelUrl : '//'+window.location.hostname+'/channel', // Path to your Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
// listen for and handle auth.statusChange events
FB.Event.subscribe('auth.statusChange', function(response) {
if (response.authResponse) {
// user has auth'd your app and is logged into Facebook
FB.api('/me', function(me){
if (me.name) {
document.getElementById('auth-displayname').innerHTML = me.name;
}
})
document.getElementById('auth-loggedout').style.display = 'none';
document.getElementById('auth-loggedin').style.display = 'block';
} else {
// user has not auth'd your app, or is not logged into Facebook
document.getElementById('auth-loggedout').style.display = 'block';
document.getElementById('auth-loggedin').style.display = 'none';
}
});
// respond to clicks on the login and logout links
document.getElementById('auth-loginlink').addEventListener('click', function(){
FB.login();
});
document.getElementById('auth-logoutlink').addEventListener('click', function(){
FB.logout();
});
}
</script>
<h1>Facebook Client-side Authentication Example</h1>
<div id="auth-status">
<div id="auth-loggedout">
Login
</div>
<div id="auth-loggedin" style="display:none">
Hi, <span id="auth-displayname"></span>
(logout)
</div>
</div>
</body>
</html>
The website clearly says that all.js is expired. However, I get the same error you got only with sdk.js. Problem was fixed when went back to the depreciated all.js
// Old SDK (deprecated)
js.src = "//connect.facebook.net/en_US/all.js";
// New SDK (v2.x)
js.src = "//connect.facebook.net/en_US/sdk.js";
facebook sdk

Facebook open graph - login button not displaying everytime

I recently upgraded to open graph and implemented some of the facebook social plugins on my website like fb:friendpile fb:like-box etc
Ever since I implemented these new features, I'm seeing some random behavior with these plugins.
Like on my home page, when you type in the URL and go for the first time, none of the facebook social plugins are rendered - no login button, no friendpile no like - nothing.
But when you hit CTRL F5 - they appear. First I thought it probably has somethin to do with my machine but yesterday two of my users reported the same issue.
I googled around and it seems to have something to do with where you place your connect code. Right now, I have this relevant portion of the script placed in my head tag - I even tried placing it right before the end of body tag - but it made no difference.
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({appId: '<?php echo Zend_Registry::getInstance()->configuration->facebook->appid;?>', status: true, cookie: true, xfbml: true});
/* All the events registered */
FB.Event.subscribe('auth.login', function(response) {
// do something with response
login();
});
FB.Event.subscribe('auth.logout', function(response) {
// do something with response
logout();
});
};
(function() {
var e = document.createElement('script');
e.type = 'text/javascript';
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
function login(){
document.location.href = "<?php echo $this->baseUrl(); ?>/login/log";
}
function logout(){
FB.init({appId: '<?php echo Zend_Registry::getInstance()->configuration->facebook->appid;?>'});
FB.logout(function(response) {
// user is now logged out
});
document.location.href = "<?php echo $this->baseUrl(); ?>/login/logout";
return false;
}
</script>
Any insights in trouble shooting this will be appreciated
Thanks
Your logout logic seems problematic (you call FB.logout() in logout() -- but also call logout() on the 'auth.logout' event, which seems circular). You should also remove the FB.init() call inside your logout() function. The lack of xmlns:fb on the <html> tag is often the cause of XFBML not rendering in IE, so I'd double check that. You could also try replacing the async loading with sync loading using a normal script tag like:
<script src="http://connect.facebook.net/en_US/all.js"></script>
But a live repro case would be more helpful since your code looks fine for the most part.
EDIT: You can also checkout http://fbrell.com/xfbml/fb:login-button for examples.