授权服务失败在angularjs页面刷新 [英] Authorization Service fails on page refresh in angularjs

查看:170
本文介绍了授权服务失败在angularjs页面刷新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

实现使用<一个授权href=\"http://nadeemkhedr.word$p$pss.com/2013/11/25/how-to-do-authorization-and-role-based-permissions-in-angularjs/\"相对=nofollow> POST
问题是,当我去一个特权页说/管理员它的工作原理,但是当我刷新页面
手动,管理员页面重定向到'/未经授权的页

Implemented the authorization using the POST The problem is when i go to a privileged page say '/admin' it works but when i refresh the page manually, the admin page is redirecting to the '/unauthorized' page

权限服务

angular.module('myApp')
    .factory('PermissionsService', function ($rootScope,$http,CookieService) {
        var permissionList;
        return {
            setPermissions: function(permissions) {
                permissionList = permissions;
                $rootScope.$broadcast('permissionsChanged')
            },
            getPermissions: function() {
                var roleId = 5
                if(CookieService.getLoginStatus())
                    var roleId = CookieService.getUserData().ROLE_ID;

                return $http.post('api/user-permissions', roleId).then(function(result){
                    return result.data;
                });
            },
            hasPermission: function (permission) {
                permission = permission.trim();
                return _.some(permissionList, function(item) {
                    if(_.isString(item.name))
                        return item.name.trim() === permission
                });
            }
        };
    });

hasPermissions指令

hasPermissions directive

angular.module('myApp')
    .directive('hasPermission', function(PermissionsService) {
        return {
            link: function(scope, element, attrs) {
                if(!_.isString(attrs.hasPermission))
                    throw "hasPermission value must be a string";

                var value = attrs.hasPermission.trim();
                var notPermissionFlag = value[0] === '!';
                if(notPermissionFlag) {
                    value = value.slice(1).trim();
                }

                function toggleVisibilityBasedOnPermission() {
                    var hasPermission = PermissionsService.hasPermission(value);

                    if(hasPermission && !notPermissionFlag || !hasPermission && notPermissionFlag)
                        element.show();
                    else
                        element.hide();
                }
                toggleVisibilityBasedOnPermission();
                scope.$on('permissionsChanged', toggleVisibilityBasedOnPermission);
            }
        };
    });

app.js

app.js

var myApp = angular.module('myApp',['ngRoute','ngCookies']);

myApp.config(function ($routeProvider,$httpProvider) {
    $routeProvider
        .when('/', {
            templateUrl: 'app/module/public/index.html',
            header: 'app/partials/header.html',
            footer: 'app/partials/footer.html'
        })
        .when('/login', {
            templateUrl: 'app/module/login/login.html',
            header: 'app/partials/header.html',
            footer: 'app/partials/footer.html'
        })
        .when('/home', {
            templateUrl: 'app/module/home/home.html',
            header: 'app/partials/header.html',
            footer: 'app/partials/footer.html'
        })
        .when('/register', {
            templateUrl: 'app/module/register/register.html',
            header: 'app/partials/header.html',
            footer: 'app/partials/footer.html'
        })
        .when('/admin', {
            templateUrl: 'app/module/admin/admin.html',
            header: 'app/partials/header.html',
            footer: 'app/partials/footer.html',
            permission: 'admin'
        })
        .when('/unauthorized', {
            templateUrl: 'app/partials/unauthorized.html',
            header: 'app/partials/header.html',
            footer: 'app/partials/footer.html'
        })
        .otherwise({redirectTo: '/'});

    $httpProvider.responseInterceptors.push('securityInterceptor');
});

myApp.provider('securityInterceptor', function() {
    this.$get = function($location, $q) {
        return function(promise) {
            return promise.then(null, function(response) {
                if(response.status === 403 || response.status === 401) {
                    $location.path('/unauthorized');
                }
                return $q.reject(response);
            });
        };
    };
});

myApp.run(function($rootScope, $location, $window, $route, $cookieStore, CookieService, PermissionsService) {
    PermissionsService.getPermissions().then(function(permissionList){
        PermissionsService.setPermissions(permissionList);
    });

    // Check login status on route change start
    $rootScope.$on( "$routeChangeStart", function(event, next, current) {
        if(!CookieService.getLoginStatus() && $location.path() != '/register' && $location.path() != '/login') {
            $location.path("/");
            $rootScope.$broadcast('notloggedin');
        }

        if(CookieService.getLoginStatus() && $location.path() == '/login') {
            $location.path("/home");
        }

        var permission = next.$$route.permission;
        if(_.isString(permission) && !PermissionsService.hasPermission(permission))
            $location.path('/unauthorized');

    });

    // Adds Header and Footer on route change success
    $rootScope.$on('$routeChangeSuccess', function (ev, current, prev) {
        $rootScope.flexyLayout = function(partialName) { return current.$$route[partialName] };
    });
});

CookieService

CookieService

angular.module('myApp')
    .factory('CookieService', function ($rootScope,$http,$cookieStore) {
        var cookie = {
            data: {
                login: false,
                user: undefined
            },
            saveLoginData: function(user) {
                cookie.data.login = true;
                cookie.data.user = user;
                $cookieStore.put('__iQngcon',cookie.data);
            },
            deleteLoginData: function() {
                cookie.data.login = false;
                 cookie.data.user = undefined;
                 $cookieStore.put('__iQngcon',cookie.data);
            },
            getLoginStatus: function() {
                if($cookieStore.get('__iQngcon') === undefined)
                    return cookie.data.login;

                return $cookieStore.get('__iQngcon').login;
            },
            getUserData: function() {
                return $cookieStore.get('__iQngcon').user;
            }
        };

        return cookie;
    });

好像数据在页面刷新失去的权限。有没有其他办法可以解决这个问题?或者是有与code ??

It seems like the permissions data are lost on page refresh. Is there any other way i can solve the problem? Or is there any problem with the code??

推荐答案

嘛不得不思考了一段时间,并提出了它的工作如下变化。它可能不是最好的做法,但雅为我工作。将AP preciate如果一旦发现有人建议我在评论一个更好的解决方案。

Well had to think for some time and made the following change for it to work. It may not be the best practice but ya worked for me. Would appreciate if anyone suggested me a better solution in the comments if found.

myApp.run(function($rootScope, $location, $window, $route, $cookieStore, CookieService, PermissionsService) {
    var permChanged = false;

    PermissionsService.getPermissions().then(function(permissionList){
        PermissionsService.setPermissions(permissionList);
    });

    // Check login status on route change start
    $rootScope.$on( "$routeChangeStart", function(event, next, current) {
        console.log('$routeChangeStart');
        if(!CookieService.getLoginStatus() && $location.path() != '/register' && $location.path() != '/login') {
            $location.path("/");
            $rootScope.$broadcast('notloggedin');
        }

        if(CookieService.getLoginStatus() && $location.path() == '/login') {
            $location.path("/home");
        }

        $rootScope.$on('permissionsChanged', function (ev, current, prev) {
            permChanged = true;
        });

        if(CookieService.getLoginStatus() && permChanged) {
            var permission = next.$$route.permission;
            if(_.isString(permission) && !PermissionsService.hasPermission(permission))
                $location.path('/unauthorized');
        }

    });

    // Adds Header and Footer on route change success
    $rootScope.$on('$routeChangeSuccess', function (ev, current, prev) {
        $rootScope.flexyLayout = function(partialName) { return current.$$route[partialName] };
    });
});

我所做的就是等待要设置的权限,然后使用 permissionChanged 广播到 permChanged 变量设置为true,然后再加上,如果用户的loggedIn状态和 permchanged 不得不检查的权限,如果有

What i did was wait for the permissions to be set and then use the permissionChanged broadcast to set a permChanged variable to true and then combined with if user loggedin status and permchanged had to check the permissions if had

$rootScope.$on('permissionsChanged', function (ev, current, prev) {
                permChanged = true;
            });

            if(CookieService.getLoginStatus() && permChanged) {
                var permission = next.$$route.permission;
                if(_.isString(permission) && !PermissionsService.hasPermission(permission))
                    $location.path('/unauthorized');
            }

这篇关于授权服务失败在angularjs页面刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆