如何在meanjs中复制管理仪表板以创建用户目录

时间:2016-07-28 21:34:43

标签: meanjs

我是meanjs的新手,但我目前正在尝试创建一个用户可以相互连接的简单应用。

现在我只想实现一个功能,用户可以通过搜索查看彼此,除了我一直遇到403错误。我试图通过复制构成管理员“管理用户”视图的文档来修复它。

我不想让每个人都拥有“管理员”角色,所以我为用户添加了一项新政策,只为他们提供“获取”权限。我还为从admin文件修改的普通用户添加了新的路由,视图和控制器。

它工作得很好但是在以非管理员角色登录时,我仍然无法让系统允许访问新的userDirectory视图。我认为这与auth.interceptor.client.service.js文件和modules / core / client / app / init.js文件以及由我制作的新文件提供的$ state有关但我试过修改它们仍然在我的应用程序正文中抛出/禁止的视图。

我不知道我还能做些什么。任何帮助将不胜感激。

应用程序以home.client.view.html视图开头:

<section ng-controller="HomeController">

  </div>
  <div class="jumbotron text-center" ng-hide="authentication.user">
    <div class="row">
      <div class="col-md-6 col-md-offset-3 col-sm-6 col-sm-offset-3 col-xs-12">
        <img alt="MEAN.JS" class="img-responsive text-center" src="modules/core/client/img/brand/Logo.png" />
      </div>
    </div>
    <br>
    <div class="row">
      <p class="lead">
        An app
      </p>
    </div>
    <div class="row">
      <p>
        <!-- <a class="btn btn-primary btn-lg" href="http://meanjs.org" target="_blank">Learn more</a> -->
      </p>
    </div>
  </div>
  <div ng-if="authentication.user">
    <h2>Congratulations! You are logged in.</h2>
    <div ng-include="'/modules/users/client/views/user/user-directory.client.view.html'"></div>
    <!-- <div ng-include="'/api/users'"></div> -->

  </div>

</section>

以下是我对userDirectory的观点(从modules / users / client / views / admin / list-users.client.view.html修改):

<section ng-controller="UserDirectoryController">
  <div class="page-header">
    <div class="row">
      <div class="col-md-4">
        <h1>Users</h1>
      </div>
      <div class="col-md-4" style="margin-top: 2em">
        <input class="form-control col-md-4" type="text" ng-model="search" placeholder="Search" ng-change="figureOutItemsToDisplay()" />
      </div>
    </div>
  </div>
  <div class="list-group">
    <a ng-repeat="user in pagedSearchItems" ui-sref="users.user({userId: user._id})" class="list-group-item">
      <h4 class="list-group-item-heading" ng-bind="user.username"></h4>
      <p class="list-group-item-text" ng-bind="user.email"></p>
    </a>
  </div>

  <pagination boundary-links="true" max-size="8" items-per-page="itemsPerPage" total-items="filterLength" ng-model="currentPage" ng-change="pageChanged()"></pagination>
</section>

我的控制器(从modules / users / client / controllers / admin / list-users.client.controller.js修改):

'use strict';

angular.module('users.user').controller('UserDirectoryController', ['$scope', '$filter', 'User',
  function ($scope, $filter, User) {
    User.query(function (data) {
      $scope.users = data;
      $scope.buildPager();
    });

    $scope.buildPager = function () {
      $scope.pagedSearchItems = [];
      $scope.itemsPerPage = 15;
      $scope.currentPage = 1;
      $scope.figureOutItemsToDisplay();
    };

    $scope.figureOutItemsToDisplay = function () {
      $scope.filteredItems = $filter('filter')($scope.users, {
        $: $scope.search
      });
      $scope.filterLength = $scope.filteredItems.length;
      var begin = (($scope.currentPage - 1) * $scope.itemsPerPage);
      var end = begin + $scope.itemsPerPage;
      $scope.pagedSearchItems = $scope.filteredItems.slice(begin, end);
    };

    $scope.pageChanged = function () {
      $scope.figureOutItemsToDisplay();
    };
  }
]);

我的服务(从modules / users / client / services / users.client.service.js修改):

'use strict';

// Users service used for communicating with the users REST endpoint
angular.module('users').factory('User', ['$resource',
  function ($resource) {
    return $resource('api/userDirectory', {}, {
      update: {
        method: 'PUT'
      }
    });
  }
]);

//TODO this should be Users service
angular.module('users.user').factory('User', ['$resource',
  function ($resource) {
    return $resource('api/userDirectory/:userId', {
      userId: '@_id'
    }, {
      update: {
        method: 'PUT'
      }
    });
  }
]);

angular.module('users.user').factory('User', ['$resource',
  function ($resource) {
    return $resource('api/userDirectory/:userId', {
      userId: '@_id'
    }, {
      update: {
        method: 'PUT'
      }
    });
  }
]);

我的新路由.js(从modules / users / server / routes / admin.server.routes.js修改):

'use strict';

/**
 * Module dependencies.
 */
var userPolicy = require('../policies/userDirectory.server.policy'),
  userDirectory = require('../controllers/userDirectory.server.controller');

module.exports = function (app) {
  // User route registration first. Ref: #713
  require('./users.server.routes.js')(app);

  // Users collection routes
  app.route('/api/userDirectory')
    .get(userPolicy.isAllowed, userDirectory.list);

  //Single user routes
  app.route('/api/userDirectory/:userId')
    .get(userPolicy.isAllowed, userDirectory.read);

  // Finish by binding the user middleware
  app.param('userId', userDirectory.userByID);
};

最后我的userDirectory新策略(从modules / users / server / policies / admin.server.policy.js修改):

'use strict';

/**
 * Module dependencies.
 */
var acl = require('acl');

// Using the memory backend
acl = new acl(new acl.memoryBackend());

/**
 * Invoke User Permissions
 */
exports.invokeRolesPolicies = function () {
  acl.allow([{
    roles: ['user'],
    allows: [{
      resources: '/api/userDirectory',
      permissions: ['post', 'get']
    }, {
      resources: '/api/userDirectory/:userId',
      permissions: ['post', 'get']
    }]
  }]);
};

/**
 * Check If User Policy Allows
 */
exports.isAllowed = function (req, res, next) {
  var roles = (req.user) ? req.user.roles : ['guest'];

// Check for user roles
  acl.areAnyRolesAllowed(roles, req.route.path, req.method.toLowerCase(), function (err, isAllowed) {
    if (err) {
      // An authorization error occurred.
      return res.status(500).send('Unexpected authorization error');
    } else {
      if (isAllowed) {
        // Access granted! Invoke next middleware
        return next();
      } else {
        return res.status(403).json({
          message: 'User is not authorized'
        });
      }
    }
  });
};

1 个答案:

答案 0 :(得分:1)

我认为最简单的方法是向服务器添加一条新路由,只有用户才能访问并创建服务以检索该数据。

(这只是从数据库获取数据的服务,您可以在任何视图/控制器中使用它,或创建只能由用户/管理员访问的新视图)

在您的模块(客户端)中创建服务以执行http post / get to the server:

(function() {
 'use strict';
 angular
   .module('yourModule')
   .factory('UserListService', function($http) {
     var routes = {};
     routes.getUserList = function(username) {
       return $http.post('/api/userlist', username); //you can do a 'post' to search for one username or just 'get' to see all users.
     };
     return routes;
   }
 );
})();

然后在modulses/yourModule/server/routes添加路线:

app.route('/api/userlist').all(yourModulePolicy.isAllowed)
.post(yourModule.getUserList); //get or post its up to you

请勿忘记在modulses/yourModule/server/policies

中添加权限
roles: ['user'],
allows: [{
  resources: '/api/userlist',
  permissions: ['post'] //get or post
}]

然后在modulses/yourModule/server/controllers

中处理请求
exports.getUserList = function(req, res) {
  var name_to_search = req.body.username;
  //here you can query the database for all users or the name you
  //received in the post.
  //NOTE: if you query the user DB there can be sensitive information
  //such as the hashed password etc, make sure you delete that here
  //before you respond with the user/user list
  res.jsonp(user_list);
};

之后,您可以使用客户端控制器中的用户信息,如下所示:

UserListService.getUserList({
   username: 'john'
 }).then(function(data) {
   vm.userlist = data.data;
 });

确保将UserListService注入控制器并将其传递给控制器​​函数:

YourController.$inject = ['UserListService'];

function YourController(UserListService){...}

希望这有帮助,我对整个平均堆栈也不熟悉,甚至不知道这是否是最好的解决方案,但它会起作用。

编辑:

使用控制器在客户端创建新视图时,需要将其添加到modules/yourModule/client/config/yourModule.client.routes.js

中的客户端路由
.state('your.state', {
        url: '-yourUrl',
        templateUrl: 'modules/yourModule/client/views/user-list.client.view.html',
        controller: 'YourController',
        controllerAs: 'vm',
        data: {
          roles: ['user', 'admin'],
          pageTitle: 'User List'
        }
      })