Reputation: 11157
Halo all,
I want to use angularjs with firebase simple login (facebook). But I have no idea how to create the auth share service.
What I want to do is
$location
if user loggedin/not-loginI also new to angularjs but I don't know which services should I use in this situation.
service
or factory
?
How can I put the below code in angular service then tell each controller if user logged in or not?
var firebaseRef = new Firebase("https://test.firebaseio.com");
var auth = new FirebaseAuthClient(firebaseRef, function(error, user) {
if (user) {
console.log(user);
} else if (error) {
console.log(error);
} else {
console.log('user not login');
}
});
Here is what i'm guessing, return user
value from authService
so in controllers if authService.user
exists then redirect to loggedin page otherwise show login dialog with a
login button to call the following code
authService.login('facebook');
Let me know if I can do like this, or there is a better way?
Upvotes: 2
Views: 1650
Reputation: 682
Here is what I'm using so far...
I haven't implemented the redirecting yet but the rest works.
p4pApp.factory('firebaseAuth', function($rootScope) {
var auth = {},
FBref = new Firebase(p4pApp.FIREBASEPATH);
auth.broadcastAuthEvent = function() {
$rootScope.$broadcast('authEvent');
};
auth.client = new FirebaseAuthClient(FBref, function(error, user) {
if (error) {
} else if (user) {
auth.user = user;
auth.broadcastAuthEvent();
} else {
auth.user = null;
auth.broadcastAuthEvent();
}
});
auth.login = function() {
this.client.login('facebook');
};
auth.logout = function() {
this.client.logout();
};
return auth;
});
The AuthCtrl is common to all/most of my pages.
var AuthCtrl = function($scope, firebaseAuth) {
$scope.login = function() {
firebaseAuth.login();
};
$scope.logout = function() {
firebaseAuth.logout();
};
$scope.isLoggedIn = function() {
return !!$scope.user;
};
// src: Alex Vanston (https://coderwall.com/p/ngisma)
$scope.safeApply = function(fn) {
var phase = this.$root.$$phase;
if (phase == '$apply' || phase == '$digest') {
if(fn && (typeof(fn) === 'function')) {
fn();
}
} else {
this.$apply(fn);
}
};
$scope.$on('authEvent', function() {
$scope.safeApply(function() {
$scope.user = firebaseAuth.user;
});
});
};
Upvotes: 6
Reputation: 7428
Regarding factory vs. service, there was a good blog post explaining how to approach the choice that I recommend reading: http://iffycan.blogspot.com/2013/05/angular-service-or-factory.html
In terms of doing authentication, your general approach of assigning signed in state to a variable in a service seems alright. We're thinking about doing a deeper integration with Angular for authentication, but for now this seems like a reasonable approach.
Upvotes: 2