简体   繁体   中英

Cancancan Cant get it work with User and Admin

So i am using Cancancan gem in my application.I have Users authenticated with the Devise/Omniauth gems and Admins that they are authenticated with a simple custom authentication. I want to achieve

ability.rb

def initialize(userOrAdmin)

if userOrAdmin.user?
    can :read, User 
    return unless user.present?
    can :manage, User, id: user.id
  elsif userOrAdmin.admin? 
    can [:update, :read] , Admin, id: admin.id
  end
 end
end

but that doesnt work. I tried to override the ability method like that

application_controller

 def current_ability

   if current_admin?
     @current_ability ||= Ability.new(current_admin)
   elsif current_user?
     @current_ability ||= Ability.new(current_user)
   end
 end

but i am getting a nomethod current_admin error probably because Cancancan assumes a current_admin from device but cant find it although i am using an current_admin method of my own.

I also tried to assign roles with the enum in both User.rb and Admin.rb and change ability.rb properly but i got an undefined method admin? for User error

Cancancan verion 2.0

I found a solution that works application_controller.rb

def current_ability
 if current_user
        return if current_admin.present?
     @current_ability ||= Ability.new(current_user)
   elsif current_admin
        return unless current_admin.present?
     @current_ability ||= Ability.new(current_admin)
   end
 end

end

ability.rb

class Ability
  include CanCan::Ability
  def initialize(userOrAdmin)
    if userOrAdmin.is_a? User
      can :read, User
      can [:update, :read], User, id: userOrAdmin.id
    elsif userOrAdmin.is_a?  Admin
      can :read, Admin
      can [:update, :read], Admin, id: userOrAdmin.id
   end
 end
end

Althought this works without errors . Whenever i am signed in both like a user and admin the admin role appears CanCan not authorized error .

After some searching, I found some helpful articles:

I suggest you try the following:

# Ability.rb
class Ability
  include CanCan::Ability

  def initialize(user)
  # Everyone:
    can :read, User
  # Users:
    return unless user.present?
    can :manage, User, user_id: user.id
  # Admins:
    return unless user.admin?
    can :manage, :all
  end
end
# Routes.rb
devise_for :users  # current_user:
devise_for :admins  # current_admin: 
# Application_Controller.rb
def current_ability
  @current_ability ||= current_admin ? AdminAbility.new(current_admin) : UserAbility.new(current_user)
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM