Jérôme
Jérôme

Reputation: 11

Rails, ActiveAdmin, Cancancan: how to prevent access to a resource in /admin?

I am very new to Rails (6.1.4). I tried to follow the beginner's tutorial and it worked quite well.

Then I tried to adapt a bit to my own goal which is to simply perform CRUD actions on "laboratoires". It worked well either.

Then I wanted to try ActiveAdmin with Devise and Cancancan with this "laboratoires" little application.

I was very impressed to see how simple it was to install and make it work. But then I realised that each user, whatever one's role (I have admin role, referent role and consultation role) can access to /admin/laboratoires.

I would like that only users with admin role could access /admin/laboratoires. The other users should only access /laboratoires.

I thought that I could simply complete my ability.rb model with a cannot line, this way (I tried on referent role):

# frozen_string_literal: true
class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new # guest user (not logged in)

    if user.admin_role?
      can :manage, :all 
   
    elsif user.referent_role?
      can [:read, :create, :update, :destroy], Laboratoire
      cannot [:read, :create, :update, :destroy], ActiveAdmin::Page, name: "Laboratoire", namespace_name: "admin" 
    
    elsif user.consultation_role?
      can [:read], Laboratoire
  
  end

end

But it doesn't seem to work and it seems I don't understand something here.

Does anyone know what I wrote wrong? Maybe I need to provide some other informations but I am not sure yet to precisely understand which ones are relevant, to say it simply...

==== UPDATE 2021-08-05 : Well, I actually think I have just found the answer to my own question. I think I got confused between authorization and authentication. I just realised the ActiveAdmin's parameter config.authentication_method can help me to handle this point. So I wrote a method in the application controller that ActiveAdmin call through this parameter to prevent non admin users to access ActiveAdmin. It seems to work perfectly well now :).

Upvotes: 0

Views: 941

Answers (1)

Saiqul Haq
Saiqul Haq

Reputation: 2397

there is full documentation here https://activeadmin.info/13-authorization-adapter.html and make sure you installed cancancan gem, not cancan gem, it's been abandoned

so you need to update your ActiveAdmin initializer, usually located at config/initializers/active_admin.rb and update it based on the guide

config.authorization_adapter = ActiveAdmin::CanCanAdapter
config.on_unauthorized_access = :access_denied

update application_controller.rb file

class ApplicationController < ActionController::Base
  protect_from_forgery

  def access_denied(exception)
    redirect_to admin_organizations_path, alert: exception.message
  end
end

Upvotes: 0

Related Questions