$firebaseAuth with AngularFire 2.0.1 and Firebase 3.0.5 - angularjs

I am trying to upgrade to Firebase 3 and AngularFire 2.
I have run initializeApp in the config phase of the app:
let firebaseConfig = {
apiKey: config.fbSecret,
authDomain: config.firebaseAuthDomain,
databaseURL: config.firebaseBase
},
fbApp = firebase.initializeApp(firebaseConfig);
let baseRef = firebase.database().ref()
and then 'provided` the baseRef for injection into other modules(as I do in the old version):
$provide.value('FirebaseBase', baseRef);
so that I can inject FirebaseBase into a service module and use e.g. FirebaseBase.child('profile').
That doesn't generate any errors, but I am getting this error in the console when the app runs:
angular.js:4576 Uncaught Error: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp().
There is no indication of where the error comes from, but I have some authentication code in the run phase:
$firebaseAuth.$onAuthStateChanged(..
and I'm guessing that it might come from there. I have tried to follow the migration guides but there doesn't seem to be any real-life example and it is not clear to me how the new AngularFire ties in with firebase.initializeApp.
Is there a sample app anywhere? Am I missing something?

you need to call the initialization in the beginning of the run block in your angular code since you are trying to authorize in there, I made this mistake in a few of my earlier integrations of Firebase
angular.module('starter', ['ionic', 'starter.controllers', 'starter.services', 'ngCordova'])
.run(function ($ionicPlatform, FirebaseDB, $rootScope, $state) {
FirebaseDB.initialize();
// for authentication, managing the state if error..
$rootScope.$on('$stateChangeError',
function (event, toState, toParams, fromState, fromParams, error) {
// if the error is "NO USER" the go to login state
if (error === "NO USER") {
event.preventDefault();
$state.go('login', {});
}
});
})
in my firebaseService
.factory('FirebaseDB', function ($q, $state, $timeout) {
var instance, storageInstance, unsubscribe, currentUser = null
var initialized = false
return {
initialize: function () {
// Not initialized so... initialize Firebase
var config = {
//SET YOUR CONFIG BLOCK HERE
};
// initialize database and storage
instance = firebase.initializeApp(config);
storageInstance = firebase.storage();
// listen for authentication event, dont start app until I
// get either true or false
unsubscribe = firebase.auth().onAuthStateChanged(function (user) {
currentUser = user
console.log("got user..", currentUser);
})
},
}
})

If you put it in the Run phrase it will fix it.

Related

Firebase - Angularjs handle email verification

I use firebase and Angularjs on my web app. I have a factory below serving to all my app modules:
.factory('Auth', ["$firebaseAuth",
function($firebaseAuth) {
return $firebaseAuth();
}
]);
It is critical for me (in fact it is the easiest and only way I know) to check pages if auth required or not. So I put this code on each module config in $stateProvider :
resolve: {
"currentAuth": ["Auth", function(Auth) {
return Auth.$requireSignIn();
}]
I want to use firebase email verification and according to documents I need to do so:
var app = firebase.initializeApp(config);
var auth = app.auth();
...
function handleVerifyEmail(auth, actionCode, continueUrl) {
auth.applyActionCode(actionCode).then(function(resp) {
...
}).catch(function(error) {
...
});
}
But then it returns error:
{code: "app/duplicate-app", message: "Firebase: Firebase App named
'[DEFAULT]' already exists (app/duplicate-app).",
I wanted to try with the factory Auth.applyActionCode but there is no such method. How can I solve this problem?
make sure you're not calling the initialize method more than once. see: github.com/Polymer/polycasts/issues/16 for more details.

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

Firebase V3 and Social Login with Ionic

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

How can I redirect a user to the login page using angularjs and laravel

I am working on a project using laravel and angularjs. I am using only Laravel to authenticate the users and when their logged in, then angularjs ui veiw will handle the navigation. when doing this I realized a problem, when the session has expire the user should be redirected to the logged in page based on the auth filter that is set on the route. Additionally when I checked the browser dev tool network tab, I see that the sign in page is send as a response. I am wondering how can I make my project redirect the user to the logged in page when the session has expire. how can I solve this problem and Thanks in advance for the assistance.
You can do that with $httpInterceptor, here is demo code:
var myApp = angular.module("MyApp", []);
myApp.config(function ($httpProvider, $provide) {
$provide.factory('myHttpInterceptor', function ($q, $location) {
return {
'response': function (response) {
//you can handle you sucess response here.
return response;
},
'responseError': function (rejection) {
console.log(rejection);
//if(rejection.data.xxx==="xxx")
if(rejection.status === 408){//session expired code
alert('logout!');
// clear your local data here...
$location.url("/login")
}
return $q.reject(rejection);
}
};
});
$httpProvider.interceptors.push('myHttpInterceptor');
});
myApp.controller("MainController", function ($scope, $http) {
$scope.response = {};
$scope.triggerGet = function () {
$http.get("/my/json").success(function (data) {
$scope.response = data;
});
};
});
When your server side response is session expired, you can handle the response.status or you can handle the other data with response.data.
Here is $httpInterceptor document.(In the middle of the page)
To redirect the user client-side in JavaScript use location. https://developer.mozilla.org/en-US/docs/Web/API/Location
For this case I think you want to look at location.assign() specifically.

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