使用AngularFire注册后自动登录

时间:2015-08-24 16:13:05

标签: angularjs firebase angularfire firebase-authentication

我有一个应用程序,允许用户自己注册,登录和添加内容。 对于经过身份验证的用户,他们可以访问某些页面,否则会将其指向登录页面。但是,我无法弄清楚如何在注册后让用户自动登录(转到名为tools的页面)。如何将登录信息从注册页面传递到工具页面?

这是我的工具页面和登录页面的路线:

.config(['$routeProvider', function($routeProvider) {

  $routeProvider
    .when('/tools', {
        templateUrl: 'app/shared/nav.html',
        controller: 'NavCtrl',
        resolve: {
             // controller will not be loaded until $requireAuth resolves
            "currentAuth": ["$firebaseAuth", function ($firebaseAuth) {
                var firebaseObj = new Firebase("https://scurdangular.firebaseio.com/");
                var loginObj = $firebaseAuth(firebaseObj);
                return loginObj.$requireAuth();
            }]
        }
    })
    .otherwise({
        redirectTo: '/login'
    }); 
}])

这是注册控制器:

// Register controller
.controller('RegisterCtrl', ['$scope', '$firebaseArray', '$location', 'CommonProp', '$firebaseAuth', function($scope, $firebaseArray, $location, CommonProp, $firebaseAuth) {
$scope.signUp = function() {

    var firebaseObj = new Firebase("https://xxxxxx.firebaseio.com/");
    var auth = $firebaseAuth(firebaseObj);
    var loginObj = $firebaseAuth(firebaseObj);

    var email = $scope.user.username +'@whateverdomain.com';
    var password = $scope.user.password;

    // Sign up implementation 
    if (!$scope.regForm.$invalid) {
        console.log('Valid form submission');

        auth.$createUser({email, password})
               .then(function(userData) {

                    // login user after registration

                    loginObj.$authWithPassword({
                            email: email,
                            password: password
                     });
                     $location.path('/tools');
                     console.log('user creation success', userData.uid);
                            }, function(error) {
                                console.log(error);
                                $scope.regError = true;
                                $scope.regErrorMessage = error.message;
                            });

                    }

            });
        });
    }    
};}])

1 个答案:

答案 0 :(得分:2)

就像$createUser()一样,$authWithPassword()会返回一个承诺。当用户通过身份验证时,该承诺就会得到满足,这是您想要重定向的时间:

 loginObj.$authWithPassword({
     email: email,
     password: password
 }).then(function(authData) {
     $location.path('/tools');
 });