Reputation: 290
I have a Firebase AngularJS application and I'm using the FirebaseSimpleLogin
to perform the authentication but I'm having a bit of trouble understanding how I can go about persisting the logged in user across my application. Each time I log in and refresh the page it appears that I'm no longer authenticated. I understand that a token is generated after the login which is used to authenticate the user but do I need to authenticate them using this token on each page and if so does this generate any type of overhead between my application and firebase?
Section of my app which performs the login/authenticatin
var ref = new Firebase("https://xxx.firebaseio.com/");
angularFireAuth.initialize(ref, {scope: $scope, name: "user", path:"/login"});
// Used to authenticate user at a later time
$scope.auth = function(token, callback)
{
ref.auth(token, function(error, data) {
if(error)
{
console.log("Login Failed!", error);
}
else
{
$scope.$apply(function()
{
$scope.user = data.auth;
});
}
if (typeof callback === 'function')
{
callback(error,data);
}
});
};
// Login to fetch authentication token to be used by $scope.auth()
$scope.login = function()
{
angularFireAuth.login("password", {
email: $scope.credentials.email,
password: $scope.credentials.password
});
};
// On login stores user within $scope
$scope.$on("angularFireAuth:login", function(evt, user) {
$scope.$apply(function()
{
// Is it possible to save this user accross my application not just in this $scope
$scope.user = user;
});
});
Here is the markup which captures the email/password combination
<div class="container-single" center>
<h3>Sign in</h3>
<input type="text" ng-model="credentials.email" placeholder="Username" />
<input type="password" ng-model="credentials.password" placeholder="Password" />
<input type="checkbox" id="checkbox-1" name="checkbox-1" /> <label>Remember my password</label>
<button ng-click="login()">Sign in</button>
</div>
Upvotes: 1
Views: 1392
Reputation: 7428
If you're using angularFireAuth
, then you don't need to do any authentication yourself. Just check the $scope.user
value to see if the user is logged in or not in every view.
var ref = new Firebase("https://xxx.firebaseio.com/");
angularFireAuth.initialize(ref, {scope: $scope, name: "user", path:"/login"});
$scope.login = function() {
angularFireAuth.login("password", {
email: $scope.credentials.email,
password: $scope.credentials.password
});
};
Upon successful login, $scope.user
is automatically set to the user details.
Upvotes: 2