Firebase V3 and Social Login with Ionic - angularjs

I am just trying to create a simple social login (e.g.: google, Facebook,...) inside a Ionic App and using Firebase V3 as backend. Unfortunately all the example and tutorial that I found on the internet seems to be broken and do not work with the new API v3.
For example I tried to follow this tutorial (https://firebase.googleblog.com/2016/01/social-login-with-ionic_77.html?showComment=1465144743780#c7688518627861813273)
but apparently I am not able to access the global variable Firebase that was previously available and therefore from this snippet of my app.js
angular.module('starter', ['ionic', 'starter.controllers', 'starter.services', 'firebase'])
.constant('FirebaseUrl', 'https://ionicle.firebaseio.com/')
.service('rootRef', ['FirebaseUrl', Firebase])
I get the following error
ReferenceError: Can't find variable: Firebase, http://localhost:8103/js/app.js, Line: 12

facebookAuth: function () {
ngFB.login({ scope: 'email' }).then(
function (response) {
if (response.status === 'connected') {
console.log('Facebook login succeeded', response);
var credential = firebase.auth.FacebookAuthProvider.credential(
response.authResponse.accessToken);
firebase.auth().signInWithCredential(credential).catch(function (error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
// ...
});
} else {
alert('Facebook login failed');
}
});
},
more details here: http://www.clearlyinnovative.com/firebase-3-0-ionic-facebook-login

Related

Ionic Firebase Facebook login works fine in browser, but not on Android

I am relatively new to Ionic and I'm having issues doing a Facebook login with ionic framework on the android platform. It does work perfectly on browser (sometimes when I try to do the login the first attempt doesn't work) but when I run the project on Android it just redirects and doesn't pass to the next page.
I think that the issue could be that the first login attempt doesn't fetch the Facebook user data.
Here is my code:
.controller('LoginCtrl', function (Backand, $state, $rootScope, $scope, LoginService, ID, name) {
$scope.bgs = ["img/welcome-bg.jpg"];
$scope.firebaseFacebookLogIn = function(){
var provider = new firebase.auth.FacebookAuthProvider();
provider.addScope('user_birthday');
provider.addScope('public_profile');
firebase.auth().signInWithRedirect(provider);
firebase.auth().getRedirectResult().then(function(result) {
if (result.credential) {
// This gives you a Facebook Access Token. You can use it to access the Facebook API.
var token = result.credential.accessToken;
var user = result.user;
var uid = user.providerData[0].uid;
var nombre = user.providerData[0].displayName;
localStorage.setItem("Usuario", user);
localStorage.setItem("ID", uid);
localStorage.setItem("Nombre", nombre);
$state.go('app.feed');
}
//var user = firebase.auth().currentUser;
}).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
alert(errorCode);
var errorMessage = error.message;
alert(errorMessage);
// The email of the user's account used.
var email = error.email;
alert(email);
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
alert(credential);
// ...
});
};
$scope.ID = localStorage.getItem("ID");
$scope.name = localStorage.getItem("name");
$scope.facebookLogOut = function(token){
firebase.auth().signOut().then(function() {
// Sign-out successful.
$state.go('auth.walkthrough');
}, function(error) {
// An error happened.
});
};
})
Solved it!
Turns out that I was just missing a firebase tag inside config.xml of the project.. Pretty dumb to be honest, hope it helps to somebody with the same issue.

On Auth State changed AngularFire

Trying to authenticate an user using firebase. Started my app using firebase 2.xx but even after upgrading to Firebase 3.xx, throwing
error "onAuthStateChanged is not a function".
This is how my login function looks like-
.controller('HomeCtrl', ['$scope','$location','CommonProp','$firebaseAuth', '$firebaseObject',function($scope,$location,CommonProp,$firebaseAuth,$firebaseObject) {
var firebaseObj = $firebaseObject(rootRef);
var loginObj = $firebaseAuth(firebaseObj);
$scope.SignIn = function($scope, user) {
event.preventDefault(); // To prevent form refresh
var username = user.email;
var password = user.password;
loginObj.$signInWithEmailAndPassword({
email: username,
password: password
})
.then(function(user) {
// Success callback
console.log('Authentication successful');
$location.path("/welcome");
CommonProp.setUser(user.password.email);
}, function(error) {
// Failure callback
console.log(error);
});
}
}]);
Your problem is that you are passing a $firebaseObject to $firebaseAuth().
So make sure you are initializing your [$firebaseAuth][1] object like the following and then your code should work properly.
var loginObj = $firebaseAuth();
Working jsFiddle for demonstrating.
You can check here the documentation for AngularFire2

How to save the google login as an app user?

So I have some code that authenticates the user to my app using google which works out fine. What I want to do is then save that user info to the firebase and then have that user be able add data specifically under their account that will then reload the next time they log in. What's the best way to do that? I'm getting very lost.
(function() {
'use strict';
angular.module('life-of-a-story')
.controller('UserController', function($scope, $firebaseAuth) {
var ref = new Firebase('https://life-of-a-story.firebaseio.com/');
// create an instance of the authentication service
var auth = $firebaseAuth(ref);
// login with Google
this.login = function() {
auth.$authWithOAuthPopup("google").then(function(authData) {
console.log(authData);
console.log("Logged in as:", authData.uid);
var user = {
'name': authData.google.displayName,
'image': authData.google.profileImageURL,
'uid': authData.uid
}
console.log(user);
}).catch(function(error) {
console.log("Authentication failed:", error);
});
};
});
})();
AngularFire is a (relatively) thin UI binding library on top of Firebase's regular JavaScript SDK. So when something is not explicitly documented in the AngularFire documentation, you can sometimes find the answer in the documentation for the regular Firebase JavaScript SDK.
Most Firebase Authentication developers store each user's data under a /users node. If that is what you're trying to do, you can read how to accomplish it in the section called Storing user data in the Firebase documentation for JavaScript.
The relevant code from there:
// we would probably save a profile when we register new users on our site
// we could also read the profile to see if it's null
// here we will just simulate this with an isNewUser boolean
var isNewUser = true;
var ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");
ref.onAuth(function(authData) {
if (authData && isNewUser) {
// save the user's profile into the database so we can list users,
// use them in Security and Firebase Rules, and show profiles
ref.child("users").child(authData.uid).set({
provider: authData.provider,
name: getName(authData)
});
}
});
// find a suitable name based on the meta info given by each provider
function getName(authData) {
switch(authData.provider) {
case 'password':
return authData.password.email.replace(/#.*/, '');
case 'twitter':
return authData.twitter.displayName;
case 'facebook':
return authData.facebook.displayName;
}
}

Firebase Google Login

Firebase deprecated FirebaseSimpleLogin, so we've been trying to implement the new authWithOAuthPopup, but we keep getting a console error: TypeError: undefined is not a function.
var app = angular.module("myApp", ["firebase"]);
app.controller("appCtrl", function($scope, $firebase) {
var ref = new Firebase("https://[forge].firebaseio.com/users");
// Login using Google
$scope.loginGoogle = function() {
console.log("Got into google login");
ref.authWithOAuthPopup("google", function(error, authData) {
console.log("yeah, we got in! " + user.uid);
}, {
remember: "sessionOnly",
scope: "email"
});
};
$scope.logout = function() {
ref.unauth();
};
});
What am I doing wrong?
The delegated authentication methods (i.e. authenticating via OAuth providers, or email / password, etc.) were added to Firebase core client libraries on October 3rd 2014, and will require a client library from that date or later (>= 1.1.0 for the web client).
Grab the latest web client library, and view the changelog, at https://www.firebase.com/docs/web/changelog.html.
Be sure to use the latest version of Firebase, otherwise it will not understand the ref.authWithOAuthPopup method
Here is the latest version: https://cdn.firebase.com/js/client/2.0.2/firebase.js

angularfire login with a previously issued firebase token

I am using a separate server that authenticates my angular app. As part of that process the server has already authenticated the user with firebase and has received an auth_token back. Once the angular app is served, I re-request the token from my server and now I want to issue an angularFireAuth.login().
I have tried this but get a "Reference Error unrecognized auth". Am I missing something very fundamental? Shouldn't I be able to login with a pre-existing firebase auth_token??
Here is the code:
var profileController = function ($rootScope, $scope, $log, $location, angularFire, angularFireAuth, profileService) {
init();
function init() {
$scope.profile = {};
profileService.getFirebaseToken(function success(data) {
$scope.auths = data;$
$scope.auth = $rootScope.auth;
var id = {'id': data['_id']};
auth=angularFireAuth.login(data['access_token'],id);
$scope.auth = auth;
}, function error(err) {
console.log('error', err);
});
** Note: data['_id'] = string id that is the userid in my firebase and used as auth.id in my security rules
data['access_token'] = string token. this is not a dictionary or object. just the string token returned from: token = create_token(SECRET, custom_data, options). Which runs successfully on my python tornado server using the: firebase_token_generator module.
Ok. I figured it out. The error I was receiving because the login request is asynchronous. So the "Reference Error: auth" was because the variable auth was referenced before assigned.
I did not ultimately use this exact code above. So I do not know if it was/would work. Instead I switched to the construct that is on the firebase site:
fbLoginService.getFirebaseToken(function success(data) {
var dataRef = new Firebase('xxxxxx.firebaseio.com')
dataRef.auth(data['firebase']['access_token'], function(error) {
if(error) {
console.log("Login Failed!", error);
alert("Login Failure. Unable to login to database(firebase)");
} else {
console.log("Firebase Login Succeeded!");
$rootScope.firebaseAuth=true;
}
});
}, function error(err) {
console.log('error', err);
alert('error', err);
});
I have now created a loginController and loginService that I fire on initial load of index.html with the inclusion of the ng-controller="fbLoginController". All looks good so far.

Resources