Search code examples
ruby-on-railscancancanrolifydevise-invitable

Only Users with Owner Role can send invitation


Am working with Rolify,Devise,CanCanCan and devise_invitable, the setup has been perfect,i have two roles "owner" and "member", and i have 3 models, User,Project and Gig, User has_many Project and Project has_many Gig vice versa, my question is,how do i ensure only users with role "owner" can send invitation to a new user.

Ability.rb

  def initialize(user)
    # Define abilities for the passed in user here. For example:
    #
       user ||= User.new 

      if user.has_role? :owner
        can :invite, User
        can :manage, Project, user_id: user.id
      elsif user.has_role? :member
        can :manage, Gig, user_id: user.id
      else
        can :manage, Project
      end

role.rb

class Role < ApplicationRecord
has_and_belongs_to_many :users, :join_table => :users_roles


belongs_to :resource,
           :polymorphic => true,
           :optional => true


validates :resource_type,
          :inclusion => { :in => Rolify.resource_types },
          :allow_nil => true

scopify
end

user.rb

class User < ApplicationRecord

  resourcify
  rolify 

  has_many :projects,dependent: :destroy
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :invitable, :database_authenticatable, :confirmable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

end

invitations_controller

 class InvitationsController < Devise::InvitationsController
    before_action :is_owner?, only: [:new, :create]

    private 
    def is_owner?
        current_user.has_role? :owner
    end
end

Solution

  • For the benefit of others who may encounter such problem, here is how i got it work, modify the invitations_controller like this.

    class InvitationsController < Devise::InvitationsController
       def new
         if cannot?( :invite, User )
           raise CanCan::AccessDenied
         else
           build_resource
           resource.practice_id = current_practice_id
           render_with_scope :new
         end
       end
       def create
         if cannot?( :invite, User )
           raise CanCan::AccessDenied
         else
           super
         end
       end
    end