Pregunta

I'm following thinkster's ang-news tutorial to build authentication using firebase. I can create users with a service and controller but after registering a new user they are not logged in.

I have a auth.js service:

app.factory('Auth', ['$rootScope', 'FIREBASE_URL', '$firebaseSimpleLogin', function($rootScope, FIREBASE_URL, $firebaseSimpleLogin){

    var ref = new Firebase(FIREBASE_URL);
    var auth = $firebaseSimpleLogin(ref);

    var Auth = {
        register: function(user){
            return auth.$createUser(user.email, user.password);
        },
        signedIn: function(){
            return auth.user !== null;  // user signed in if user property is not null
        },
        login: function(user){
            return auth.$login('password', user);   // type of login
        },
        logout: function(){
            auth.$logout();
        }
    };

    $rootScope.signedIn = function(){
        return Auth.signedIn();
    };

    return Auth;
}]);

auth.user always stays null.

This is my controller:

app.controller('AuthCtrl', ['$scope', '$location', 'Auth', function($scope, $location, Auth){
    if (Auth.signedIn()){
        $location.path('/')
    }

    $scope.register = function(){
        Auth.register($scope.user).then(function(authUser){
            console.log('authUser: ' + JSON.stringify(authUser))
            $location.path('/');
        })
    }
}])

Then I have a register.html with an email/password form. It calls register():

<form ng-submit='register()' novalidate>
    <input type='email' placeholder='Email' class='form-control' ng-model='user.email'>
    <input type='password' placeholder='Password' class='form-control' ng-model='user.password'>
    <input type='submit' class='btn btn-success' value='Register'>
</form>

The users get generated in my Firebase Forge, but after I submit the register form, the Logout button does not show:

<ul class='nav navbar-nav navbar-right' ng-show='signedIn()'>
   <li>
      <a href='#' ng-click='logout()'>Logout</a>
   </li>
</ul>

Why does signedIn() stay falsey after I create a user in the firebase forge?

¿Fue útil?

Solución

Creating a user does not automatically log them in (though it used to in an older version of angularFire).

Change your controller method to look like:

$scope.register = function(){
        Auth.register($scope.user).then(function(authUser){
            console.log('authUser: ' + JSON.stringify(authUser))
            Auth.login($scope.user);
            $location.path('/');
        })
    }

This will create the user in the Forge and then once that promise resolves, it will automatically log them in.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top