5

I was wondering if any one knows how to serialize CanCan permissions to emberjs. I saw this StackOverflow Q &A by Jo_Liss where she explained how to Serialize permissions (e.g. CanCan) with active_model_serializers, but stopped at that level. Also this article linked to here, talks on how to check permission on the emberjs side, but nothing how on how to serialize the permission from the backend into emberjs.

I hope to have 3 kinds of user roles that is 'admin', 'author', 'user' and will want to use CanCan permissions on emberjs to control what they can access once they are in the logged-in route.

Community
  • 1
  • 1
brg
  • 3,915
  • 8
  • 37
  • 66

1 Answers1

9

You can use the UserSerializer to serialize the users CanCan Ability:

class UserSerializer < ActiveModel::Serializer
  attributes :id, :name, :email, :ability

  def ability
    Ability.new(self).as_json
  end
end

That will return something like:

user: {
  id: 1,
  name: "xxx",
  email: "xxx",
  ability: rules: [
    {
      match_all: false,
      base_behavior: false,
      actions: [
        "edit"
      ],
      subjects: [
        "user"
      ],
      conditions: { },
      block: null
    },
    {
      match_all: false,
      base_behavior: true,
      actions: [
        "read"
      ],
      subjects: [
        "user"
      ],
      conditions: { },
      block: null
    }
  ]
}

You would need to implement some sort of can? and cannot? helper in javascript to process the abilities.

Hope that helps.

delwyn
  • 664
  • 4
  • 10
  • 1
    **One possible way to define some sort of 'can' or 'canRead' property to check user authorization** can be seen here, just to close the loop **http://jsfiddle.net/machty/Wjtcj/31/** and **http://stackoverflow.com/questions/13372214/emberjs-1-x-pre-ember-router-and-ember-computed-issues/13393756#comment18297460_13393756** – brg Nov 15 '12 at 14:16