Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save meetbryce/614104cf5b09f2a868b399b29a1e20fa to your computer and use it in GitHub Desktop.
Save meetbryce/614104cf5b09f2a868b399b29a1e20fa to your computer and use it in GitHub Desktop.
Prevent permission denied errors from Firebase on logout (caused by active $firebaseArray & $firebaseObject connections not being destroyed). Example code follows John Papa's style guide.
(function () {
'use strict';
// keeps track of all open firebase connections to be $destroy'ed
// when logging out. stored as a global variable since config doesn't
// have $rootscope and needs to be globally accessible
window.openFirebaseConnections = [];
angular
.module('app', [
// Third party modules.
'firebase',
// Custom modules.
'app.auth'
])
.config(configFunction)
.run(runFunction);
configFunction.$inject = ['$provide'];
function configFunction ($provide) {
// inject the $delegate dependency into our decorator method
firebaseDecorator.$inject = ['$delegate'];
// Whenever $firebaseArray's and $firebaseObjects are created,
// they'll now be tracked by window.openFirebaseConnections
$provide.decorator("$firebaseArray", firebaseDecorator);
$provide.decorator("$firebaseObject", firebaseDecorator);
function firebaseDecorator ($delegate) {
return function (ref) {
var list = $delegate(ref);
window.openFirebaseConnections.push(list);
return list;
};
}
}
// EVERYTHING BELOW IS BOILERPLATE FROM THE FIREBASE SAMPLE PROJECT
runFunction.$inject = ['$location'];
function runFunction ($location) {
$rootScope.$on('$routeChangeError', function (event, next, previous, error) {
if (error === "AUTH_REQUIRED") {
$location.path('/login');
}
});
}
})();
// this should be the service where your logout method lives
(function () {
'use strict';
angular
.module('app.auth')
.factory('authService', authService);
authService.$inject = [
'$firebaseAuth',
'$location',
'$window',
'alertService',
'firebaseDataService'
];
function authService ($firebaseAuth, $location, $window, alertService, firebaseDataService) {
// defined here due to dependencies
var firebaseAuthObject = $firebaseAuth(firebaseDataService.root);
var service = {
isLoggedIn: function () { return firebaseAuthObject.$getAuth() },
login: function (user) { return firebaseAuthObject.$authWithPassword(user) },
logout: logout
};
return service;
////////////
function logout () {
// destroy all firebase refs
angular.forEach($window.openFirebaseConnections, function (item) {
item.$destroy();
});
// redirect the user to a page they're authorized to view when unauth'd
$location.path('/');
// unauth the user
firebaseAuthObject.$unauth();
}
}
})();
@fasfsfgs
Copy link

hey man. do you know if there are any similar angular 2 implementations of this solution?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment