【发布时间】:2016-05-13 00:09:32
【问题描述】:
我构建了一个简单的应用程序,可让您使用 Firebase Auth 注册帐户并登录。
我为此使用了 Ionics 启动器“选项卡”应用程序。我按照这里的教程进行操作:https://www.firebase.com/docs/web/libraries/angular/guide/user-auth.html#section-routers
用于根据用户的身份验证状态阻止路由。使用下面的代码,我已经阻止您在没有登录的情况下访问仪表板选项卡,但仅出于测试目的,您仍然可以访问它。我一步一步地按照教程进行操作,这就是我所拥有的。
app.js
// Before anything else I define firebase, create a reference to the url,
// create a service for the url and create the Auth function.
angular.module('starter', ['ionic', 'starter.controllers', 'starter.services', 'firebase'])
.constant('FirebaseUrl', 'https://<firebase-name>.firebaseio.com/')
.service('rootRef', ['FirebaseUrl', Firebase])
.factory("Auth", ["$firebaseAuth", function($firebaseAuth) {
var ref = new Firebase("https://<firebase-name>.firebaseio.com/");
return $firebaseAuth(ref);
}])
...
app.js .run()
// Then in my `.run()` function I listen for our state change that fails
// because it needs to authorized first.
.run(function($rootScope, $state, $ionicPlatform) {
// ionic init. code here
$rootScope.$on("$stateChangeError", function(event, toState, toParams, fromState, fromParams, error) {
// We can catch the error thrown when the $requireAuth promise is rejected
// and redirect the user back to the login page
if(error === "AUTH_REQUIRED") {
$state.go("login");
}
});
})
app.js .config()
// Finally in my `.config()` I have my $stateProvider set up and my dashboard
// tab is resolving as to have auth required to view.
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
// setup an abstract state for the tabs directive
.state('tab', {
url: '/tab',
abstract: true,
templateUrl: 'templates/tabs.html'
})
.state('login', {
url: '/login',
templateUrl: 'templates/login.html',
controller: 'LoginCtrl as ctrl'
})
.state('tab.dash', {
url: '/dash',
views: {
'tab-dash': {
templateUrl: 'templates/tab-dash.html',
controller: 'DashCtrl'
}
},
resolve : {
// controller will not be loaded until $waitForAuth resolves
// Auth refers to our $firebaseAuth wrapper in the example above
currentAuth: ["Auth", function(Auth) {
// $waitForAuth returns a promise so the resolve waits for it to complete
return Auth.$waitForAuth();
}]
}
})
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/login');
});
不管这一切,当我点击登录页面(应用程序启动的地方)上的临时链接时,即使未登录,它仍会将我带到仪表板页面!
我在这里缺少什么?
【问题讨论】:
-
验证错误是否真的是“AUTH_REQUIRED”,例如将其记录到控制台。如果真的是这样,我们需要进一步调查......
-
它似乎没有抛出任何错误。我做了
console.log('StateChangeError: ', error);,没有任何记录。 -
您的控制台中没有其他错误?在示例中,它的
return Auth.$requireAuth();和你有return Auth.$waitForAuth(); -
这就是问题所在。在他们的家乡,他们有 requireAuth,然后他们有 waitForAuth 想把它放在一个答案中?
标签: javascript angularjs ionic-framework firebase-authentication