如果PERMISSION_DENIED重定向用户

时间:2016-02-19 23:03:58

标签: angularjs angular-ui-router firebase angularfire firebase-security

我想让人们登录并拒绝访问特定状态,具体取决于我已成功实现的firebase规则中设置的权限。

我想避免"页面闪存"重定向。

我已经关注了#34; Auth"状态重定向代码,但我无法在"左边的对象中选取PERMISSION_DENIED代码;返回$ firebaseObject(ref2);"

myapp.factory("Auth", function($firebaseAuth) {
  var ref = new Firebase("https://xxxx.firebaseio.com/");
  return $firebaseAuth(ref);
});


//myedit, got rid of this factory
///myapp.factory("notLive", function($firebaseObject) {
///  var ref2 = new Firebase("https://xxxx.firebaseio.com/events");
///  return $firebaseObject(ref2);
///});


// for ui-router
myapp.run(["$rootScope", "$state", function($rootScope, $state) {
                $rootScope.$on("$stateChangeError", function(event, toState, toParams, fromState, fromParams, error, code) {
                if (error === "AUTH_REQUIRED") {
                    $state.go("home");
                }

                    console.log(code); // returns undefined :(
                ///myedit - changed this
                ///if (code === "PERMISSION_DENIED") { 
                if (error.code === "PERMISSION_DENIED") { 
                    $state.go("home");
                }
            });
}]);

这是我的状态显示决心

.state("events", {
    url: "/events",
    templateUrl: "tpl/events.html",
    controller: "eventsCtrl",
    resolve: {
        currentAuth: function(Auth) {
            console.log(Auth.$requireAuth());
            return Auth.$requireAuth();
        },
        ///myedit - changed this
        ///notLive: function(notLive) {
        ///   console.log(notLive.$loaded());
        ///    return notLive.$loaded();
        ///}

        notLive: function($firebaseObject) {
            var refEvents = new Firebase("https://xxxxx.firebaseio.com/events");
            return $firebaseObject(refEvents).$loaded();
        }
    }
})

当我的用户被拒绝参与"事件"节点,他们无法看到很好的数据,但我希望他们重定向到本地状态并保持登录状态。

我在" eventsCtrl"中放置了一个黑客重定向但它在被重定向到" home"之前会闪烁。状态不是我想要的。

MYEDIT - 我把它放在eventsCtrl的顶部

        var refPermissionDeniedEvents = new Firebase("https://xxxxx.firebaseio.com/events");
        refPermissionDeniedEvents.on("value", function(snapshot) {
        }, function(err){
            $state.go("home", {}, { reload: true });
        });

执行此操作后,它允许用户登录并进行身份验证并坐在主页上,拒绝访问事件页面,除非我在USERS节点中更改其权限,并且在EVENTS上设置了权限规则节点。

这样做之后,我已经实现了我所需要的。

2 个答案:

答案 0 :(得分:1)

你可以这样“装饰”角度路线提供者:

(function (angular) {
  "use strict";

  var securedRoutes = [];

  angular.module('myApp.security', ['ngRoute', 'Auth', 'myApp.config'])

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

      $routeProvider.whenAuthenticated = function (path, route) {

        securedRoutes.push(path); // store all secured routes for use with authRequired() below
        route.resolve = route.resolve || {};

        route.resolve.user = ['Auth', function (Auth) {
          return Auth.$requireAuth(); //fetch auth info
        }];

        $routeProvider.when(path, route);
        return this;

      };

    }])

  /**
   * Apply some route security. Any route's resolve method can reject the promise with
   * { authRequired: true } to force a redirect. This method enforces that and also watches
   * for changes in auth status which might require us to navigate away from a path
   * that we can no longer view.
   */
    .run(['$rootScope', '$location', 'Auth', 'loginRedirectPath',

      function ($rootScope, $location, Auth, loginRedirectPath) {
        // watch for login status changes and redirect if appropriate
        Auth.$onAuth(check);

        // some of our routes may reject resolve promises with the special {authRequired: true} error
        // this redirects to the login page whenever that is encountered
        $rootScope.$on("$routeChangeError", function (e, next, prev, err) {
          if (err === "AUTH_REQUIRED") {
            $location.path(loginRedirectPath);
          }
        });

        function check(user) {
          if (!user && authRequired($location.path())) {
            //console.log('check failed', user, $location.path()); //debug
            $location.path(loginRedirectPath);
          } 
        }

        function authRequired(path) {
          return securedRoutes.indexOf(path) !== -1;
        }
      }
    ]);

})(angular);

如果用户未经过身份验证,则将loginRedirectPath设置为默认路径(登录页面或其他内容)以重定向

这是为了检查用户是否仅通过身份验证,但您可以在function check(user)

中执行其他检查(权限等)

答案 1 :(得分:0)

我不会想到"代码"已验证。在这里没有看到它: $ stateChangeError部分中的https://github.com/angular-ui/ui-router/wiki

编辑:不是肯定的,但您可能需要在catch语句中获取PERMISSION_DENIED错误。

$loaded().then(function(){}).catch(function(error){console.log(error)})