Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize Cancan permissions to emberjs

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.

like image 517
brg Avatar asked Nov 11 '12 08:11

brg


1 Answers

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.

like image 148
delwyn Avatar answered Nov 15 '22 07:11

delwyn