如何在AngularJS中显示具有用户身份验证的按钮

How to show buttons with user authentication in AngularJS?

本文关键字:用户 身份验证 按钮 显示 AngularJS      更新时间:2024-02-14

目前我正在进行我的主项目。我的应用程序是在线投资组合管理。用户可以在应用程序上注册并创建配置文件。现在我想给编辑和删除按钮上的配置文件视图。但只有创建了配置文件的用户才能看到这些按钮。例如,如果我是应用程序的用户,那么只有我可以看到我的个人资料上的编辑和删除按钮,而我只能看到其他用户的个人资料。

我是AngularJS的新手。它看起来很简单,但对我来说仍然不起作用。我对查看配置文件和编辑配置文件有不同的看法。但我只有一个控制器来控制这两个。

这就是我的视图配置文件代码的样子,

HTML

<section data-ng-controller="ProfilesController as profilesCtrl">
    <div class="modal-header">
        <div>
            <h1>{{profile.firstname}} {{profile.lastname}}</h1>
        </div>
        <div class="pull-right">
            <button class="btn-success btn-lg" type="button" data-ng-click="profilesCtrl.modalUpdate('lg', profile)">Edit</button>
            <button class="btn-danger btn-lg" type="button" data-ng-click="profilesCtrl.remove(profile)">
                <i class="glyphicon glyphicon-trash">
                    </i>
            </button>
        </div>
    </div>
</section>

控制器

profilesApp.controller('ProfilesController', ['$scope', '$stateParams', '$location', 'Authentication', 'Profiles', '$modal', '$log',
    function($scope, $stateParams, $location, Authentication, Profiles, $modal, $log) {
        this.authentication = Authentication;
        // Find a list of Profiles
        this.profiles = Profiles.query();
        // open a modal window to view single profile
        this.modalview = function(size, selectedProfile) {
            var modalInstance = $modal.open({
                templateUrl: 'modules/profiles/views/view-profile.client.view.html',
                controller: function($scope, $modalInstance, profile) {
                    $scope.profile = profile;
                    console.log(profile);
                    $scope.ok = function() {
                        $modalInstance.close($scope.profile);
                    };
                },
                size: size,
                resolve: {
                    profile: function() {
                        return selectedProfile;
                    }
                }
            });
            modalInstance.result.then(function(selectedItem) {
                $scope.selected = selectedItem;
            }, function() {
                $log.info('Modal dismissed at: ' + new Date());
            });
        };
        // open a modal window to update single profile
        this.modalUpdate = function(size, selectedProfile) {
            var modalInstance = $modal.open({
                templateUrl: 'modules/profiles/views/edit-profile.client.view.html',
                controller: function($scope, $modalInstance, profile) {
                    $scope.profile = profile;
                    $scope.ok = function() {
                        $modalInstance.close($scope.profile);
                    };
                    $scope.cancel = function() {
                        $modalInstance.dismiss('cancel');
                    };
                },
                size: size
            });
            modalInstance.result.then(function(selectedItem) {
                $scope.selected = selectedItem;
            }, function() {
                $log.info('Modal dismissed at: ' + new Date());
            });
        };

        // Remove existing Profile
        this.remove = function(profile) {
            if (profile) {
                profile.$remove();
                for (var i in this.profiles) {
                    if (this.profiles[i] === profile) {
                        this.profiles.splice(i, 1);
                    }
                }
            } else {
                this.profile.$remove(function() {
                    $location.path('modules/profiles/views/list-profiles.client.view.html');
                });
            }
        };
        // Update existing Profile
        this.update = function(updatedProfile) {
            var profile = updatedProfile;
            profile.$update(function() {}, function(errorResponse) {
                $scope.error = errorResponse.data.message;
            });
        };

    }
]);

请给我一些建议,我该如何解决这个问题?任何帮助都将不胜感激。

您可以使用这样的指令:

<button access-level="canEdit">Edit</button>

并且您的指令绑定到accessLevel:

angular.module("app")
    .directive('accessLevel', ['AuthService', 'AUTH_EVENTS', function (authService, authEvents) {
        return {
            restrict: 'A',
            link: function ($scope, element, attrs) {
                var accessLevel;
                attrs.$observe('accessLevel', function (acl) {
                    if (acl) {
                        accessLevel = acl;
                        updateCss();
                    }
                });
                $scope.$on("auth-change", function (event, data) {
                    switch (data) {
                        case authEvents.logoutSuccess:
                        case authEvents.loginSuccess:
                            updateCss();
                            break;
                        case authEvents.notAuthorized:
                        default:
                    }
                });
                function updateCss() {
                    if (accessLevel) {
                        if (!authService.isAuthorized(accessLevel)) {
                            switch (element[0].nodeName) {
                                case "A":
                                    element.hide();
                                    break;
                                default:
                                    element.attr("disabled", "disabled");
                                    break;
                            }
                        } else {
                            switch (element[0].nodeName) {
                                case "A":
                                    element.show();
                                    break;
                                default:
                                    element.removeAttr("disabled");
                                    break;
                            }
                        }
                    }
                }
            }
        }
    }]);

这比你需要的多一点,但能让你知道你能实现什么。(您必须编写您的身份验证服务等)

例如,这里是我的身份验证服务的一部分:

angular.module('app')
    .factory("AuthService", ["$rootScope", "$http", "AuthSession", "AUTH_EVENTS", function ($rootScope, $http, AuthSession, AUTH_EVENTS) {
       AuthSession.load();
       $rootScope.$on('$stateChangeStart', function (event, nextState) {
            if (nextState.data && nextState.data.accessLevel && !service.isAuthorized(nextState.data.accessLevel)) {
                event.preventDefault();
                $rootScope.$broadcast('auth-change', AUTH_EVENTS.loginRequired, nextState.name);
            }
        });
        var service = {
            login: function (credentials) {
                return $http
                            .post('/api/account/login', credentials)
                            .success(function (data, status) {
                                if ((status < 200 || status >= 300) && data.length >= 1) {
                                    $rootScope.$broadcast("auth-change", AUTH_EVENTS.loginFailed);
                                    return;
                                }
                                AuthSession.create(data.AccessToken, data.User);
                                $rootScope.$broadcast("auth-change", AUTH_EVENTS.loginSuccess);
                            }).error(function (data, status) {
                                $rootScope.$broadcast("auth-change", AUTH_EVENTS.loginFailed);
                            });
            },
            logout: function () {
                AuthSession.destroy();
                $rootScope.$broadcast("auth-change", AUTH_EVENTS.logoutSuccess);
            },
            isAuthenticated: function () {
                return (AuthSession.token !== null);
            },
            isAuthorized: function (accessLevel) {
                if (!accessLevel) return true;
                return (this.isAuthenticated() && AuthSession.user.UserRoles.indexOf(accessLevel) !== -1);
            }
        }
        return service;
    }]);

该服务从服务器检索承载令牌,并将其存储在authsession服务中。用户角色也存储在其他用户信息的旁边。由于后端也是安全的,所以在客户端上更改用户角色的人不能写入后端。(客户端的一切只是为了用户的外观)

两种方式:

  1. 创建概要文件后,让用户详细信息表中的isProfileCreated(您需要创建一个)列更新。在角载荷时,调用并检查是否创建了轮廓。如果为true,请使用ng-show来显示(编辑和删除按钮)。

  2. 否则,如果要进行编辑,无论如何,您都需要从表中获取配置文件的详细信息。在这种情况下,如果没有创建概要文件,则让您的服务器发送false,如果创建了json对象,则让服务器发送json对象。在控制器中使用

    if(angular.isObject(profile)){

            $scope.showeditbutton = true;
            $scope.showdeletebutton = true;
    

    }