railsadminteam / rails_admin

RailsAdmin is a Rails engine that provides an easy-to-use interface for managing your data
MIT License
7.89k stars 2.26k forks source link

Prohibit to authenticate ordinal users with Devise #3556

Closed tagirahmad closed 2 years ago

tagirahmad commented 2 years ago

Describe the bug

I can't make it possible to authenticate in rails admin only admin users and prohibit to log in "ordinal" users.

My below decision not works correctly. Even if it raises CanCan::AccessDenied, eventually it still logins in as non-admin user as well.

Reproduction steps

I've added such kind configurations:

The User model:

class User < ApplicationRecord
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable, :trackable

  enum :role, admin: 'admin', user: 'user'
end

User's role field is t.enum :role, enum_type: :user_role, default: "user", null: false

In routes.rb:

mount RailsAdmin::Engine => '/admin', as: 'rails_admin'
devise_for :admins, class_name: 'User'

In rails_admin.rb:

config.authenticate_with do
  warden.authenticate! scope: :admin
end
config.current_user_method(&:current_admin)

config.authorize_with :cancancan

In ability.rb:

if user.admin?
  can :access, :rails_admin
  can :manage, :all
else
  can :authorize
end

In application_controller.rb

rescue_from CanCan::AccessDenied do |exception|
  redirect_to main_app.new_admin_session_path, alert: exception.message
end

Expected behavior

Allow to authenticate rails_admin only for Users who have role == 'admin' field in database.

Additional context

mshibuya commented 2 years ago

You're mixing up authentication and authorization. Your assumption is wrong, doing something for authorization doesn't change how authorization is performed.