cancan permissions on backbone.js

Writing a plugin/gem which does authorization is quite challenging, especially when it comes to a multi-tenant application, it is quite complicated. Sometime back we wrote a plugin overriding authlogic, which takes of both authentication and setting up authorization rules for a user. We called it watchman. Its pretty old now. And then we found our love with cancan. While working on a backbone.js project, we needed the use of the can? method provided by cancan on the javascript layer.And that application involved user permissions which are controlled by a site admin for different roles. Basically we store the permissions on the database with a set of Booleans. First approach was to write a javascript helper which will do an ajax call and find out of the access. It was slowwwwwwwwwwwwwww.The next approach was to create a backbone model which holds the permissions. It worked really well!! An example on how we did that.

//views/layouts/application.html.haml
:javascript
  -if current_user
    :javascript
      $(document).ready(function() {
        window.Permission = Backbone.Model.extend({
          defaults: {
          "canDestroyBlog": #{can? :destroy, Blog},
          "canCreateComment": #{can? :create, Comment},
          "canEditComment": #{can? :edit, Comment},
          "canCreateProject": #{can? :create, Project},
          "canViewProject": #{can? :view, Project}
          }
        });
      }); 

//in your javascript
permission = new window.Permission
permission.attributes.canEditComment
=> true

permission.attributes.canCreateProject
=> false

PS: The permissions don’t get updated unless there is a page refresh at the user side.
This may not be a perfect solution, but it reduces much noise and complexity at the javascript layer.


3 Comments on “cancan permissions on backbone.js”

  1. Dhruva Sagar says:

    I would suggest you to use permission.get(‘canCreateProject’) instead of accessing it via attributes hash/object, it’s cleaner & verbose :) .

  2. paulyoungdesign says:

    What if I were to overwrite everything using the console to true? Would that grant me permission to do everything?

  3. vagmi says:

    You would obviously have something like cancan on the server side as well. This only makes it error out quicker on the client. The app will be more responsive and hence better to use.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.