基于活动的权限与Backbone,API设计理念?

时间:2013-02-05 00:15:07

标签: design-patterns backbone.js permissions knockout.js

我正在使用Backbone和Knockout以及Knockback(ko + bb桥接库)构建一个相当大的cms类型的应用程序,我正试图找出一种抽象权限的好方法。也很抱歉这部小说。

首先,这是一个非常非标准的架构,你可能会问第二个问题 - 你为什么不使用像Ember或Angular这样更全面的东西?采取的点。这就是现在的情况。 :)

所以这是我的窘境。我想在控制器和viewmodel级别获得优雅的api权限。

我有一个可供我使用的对象:

{
   'api/pages': {
     create: true, read: true, update: true, destroy: true
   },
   'api/links': {
     create: false, read: true, update: false, destroy: false
   }
   ...
}

所以在我的路由器/控制器中,我正在新建我的集合/模型/视图模型,然后在已有的视图上调用自定义的渲染方法。该视图负责释放视图模型等内容。

initialize: function() {
  this.pages = new PagesCollection();
  this.links = new LinksCollection();
},

list: function() {
  var vm = new PageListViewmodel(this.pages, this.links);
  // adminPage method is available through inheritance
  this.adminPage('path/to/template', vm); // delegates to kb.renderTemplate under the hood.
}

所以这个问题,这些集合是完全非结构化的,即。路由器对它们一无所知。

但我需要的是,如果您不允许查看特定资源,我会将其重定向到未经授权的页面。

因此,通过上面的示例,我考虑过滤器之前/之后的编码?但是你在哪里指定每个路由器方法试图访问的内容?

list: function() {
  this.authorize([this.pages, this.links], ['read'], function(pages, links) {
    // return view.
  });
}

以前的代码非常狡猾..

对于更简单的viewmodels,我有想做这样的事情 - ala Ruby的CanCan:

this.currentUser.can('read', collection) // true or false
// can() would just look at the endpoint and compare to my perms object.

2 个答案:

答案 0 :(得分:4)

您可以扩展路由器以包装路由回调,以便在允许操作之前执行有效性检查。

var Router = Backbone.Router.extend({
    routes: {
        "app/*perm": "go"
    },

    route: function(route, name, callback) {
        if (!callback) callback = this[name];

        var f = function() {
            var perms = this.authorized(Backbone.history.getFragment());
            if (perms === true) {
                callback.apply(this, arguments);
            } else {
                this.trigger('denied', perms);
            }
        };
        return Backbone.Router.prototype.route.call(this, route, name, f);
    },

    authorized: function(path) {
        // check if the path is authorized
    },

    go: function(perm) {
       // perform action
    }
});

如果路径已获得授权,则路径将照常执行,否则将触发拒绝事件。

authorized方法可以基于映射到权限对象的路径列表,如下所示

var permissions = {
   'api/pages': {
     create: true, read: true, update: true, destroy: true
   },
   'api/links': {
     create: false, read: true, update: false, destroy: false
   }
}
var Router = Backbone.Router.extend({
    routes: {
        "app/*perm": "go"
    },

    // protected paths, with the corresponding entry in the permissions object
    permissionsMap: {
        "app/pages": 'api/pages',
        "app/links": 'api/links',
    },

    route: function(route, name, callback) {
        // see above
    },

    // returns true if the path is allowed
    // returns an object with the path and the permission key used if not
    authorized: function(path) {
        var paths, match, permkey, perms;

        // find an entry for the current path
        paths = _.keys(this.permissionsMap);
        match = _.find(paths, function(p) {
            return path.indexOf(p)===0;            
        });
        if (!match) return true;

        //check if the read permission is allowed
        permkey = this.permissionsMap[match];
        if (!permissions[permkey]) return true;
        if (permissions[permkey].read) return true;

        return {
            path: path,
            permission: permkey
        };
    },

    go: function(perm) {}
});

演示http://jsfiddle.net/t2vMA/1/

答案 1 :(得分:1)

Nikoshr的回答给了我一些可以运行的东西。我不认为实际上会覆盖route本身。但这是我的解决方案。我应该在问题中提到它 - 但有时路由器动作需要多个集合。

这方面的代码非常粗糙,需要测试 - 但它确实有效!小提琴here

以下是相关部分 - 这两种方法负责授权。

authorize: function(namedRoute) {
  if (this.permissions && this.collections) {
    var perms = this.permissions[namedRoute];
    if (!perms) {
      perms = {};
      // if nothing is specified for a particular  route, we
      // assume read access required for all registered controllers.
      _.each(_.keys(this.collections), function(key) {
        return perms[key] = [];
      });
    }

    var authorized = _.chain(perms)
      .map(function(reqPerms, collKey) {
        var collection = this.collections[collKey],
            permKey = _.result(collection, 'url');

        // We implicitly check for 'read'
        if (!_.contains('read')) {
          reqPerms.push('read');
        }

        return _.every(reqPerms, function(ability) {
          return userPermissions[permKey][ability];
        });
      }, this)
      .every(function(auth){ return auth; })
      .value();
    return authorized;
  }
  return true;
},
route: function(route, name, callback) {
  if (!callback) { callback = this[name]; }
  var action = function() {
    // allow anonymous routes through auth check.
    if (!name || this.authorize(name)) {
      callback.apply(this, arguments);
    } else {
      this.trigger('denied');
    }
  }
  Backbone.Router.prototype.route.call(this, route, name, action);
  return this;
}

每个控制器/路由器都继承自perm路由器,每个操作的权限都映射如下:

// Setup
routes: {
  'list'     : 'list',
  'list/:id' : 'detail',
  'create'   : 'create'
},

// Collection are registered so we can
// keep track of what actions use them
collections: {
  pages: new PagesCollection([{id:1, title: 'stuff'}]),
  links: new LinksCollection([{id:1, link: 'things'}])
},

// If a router method is not defined,
// 'read' access is assumed to be
// required for all registered collections.
permissions: {
  detail: {
    pages: ['update'],
    links: ['update']
  },
  create: {
    pages: ['create'],
    links: ['create', 'update']
  }
},