DEV Community

Brittany
Brittany

Posted on

Day 68 - #100DaysofCode - Making Sure Only Admin Can CRUD Application - W/O CanCanCan

I used the rails admin gem to add admin to my website. It was easy! I added gem 'rails_admin', '~> 2.0' to my Gemfile and ran bundle install in my terminal. Then, I updated my users table to have a boolean for admin, below is a sample users schema:

  create_table "users", force: :cascade do |t|
    t.string "username"
    t.text "email"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.string "password_digest"
    t.boolean "admin", default: false
    t.string "encrypted_password", limit: 128
    t.string "confirmation_token", limit: 128
    t.string "remember_token", limit: 128
    t.index ["email"], name: "index_users_on_email"
    t.index ["remember_token"], name: "index_users_on_remember_token"
  end
Enter fullscreen mode Exit fullscreen mode

Then I ran rails g rails_admin:install and rails db:migrate.

I went over to http://localhost:3000/admin in my browser and I was able to see my admin dashboard.

One problem though, ANYONE WHO IS ANYONE COULD SEE MY ADMIN DASHBOARD.

So when I ran rails g rails_admin:install it gave me the rails admin file in config/initializers/rails_admin.rb

I wanted to only allow users that had admin privileges to be able to see the admin dashboard. I ran into a few issues while trying to add cancancan so I added it manually in the config/initializers/rails_admin.rb file:

RailsAdmin.config do |config|

  ### Popular gems integration
  # config.authorize_with :cancancan

  config.parent_controller = "::ApplicationController"

  config.authorize_with do
    if !current_user || !current_user.admin?
      redirect_to(main_app.root_path, alert: "You are not permitted to view this page")
    end
  end

  config.actions do
    dashboard                     # mandatory
    index                         # mandatory
    new
    export
    bulk_delete
    show
    edit
    delete
    show_in_app
  end
end

Enter fullscreen mode Exit fullscreen mode

The above will redirect anyone back to the main root page, if they are not admin.

I plan to use cancancan in my next project with the devise gem but for now this simple fix worked well.

Thanks for reading!

Sincerely,
Brittany

Top comments (2)

Collapse
 
tlylt profile image
Liu Yongliang

Day 68! Impressive:) By the way, I am very curious as to how to create those DEV series liquid tag within the article like yours, what's the syntax that you use to include that?

Collapse
 
sincerelybrittany profile image
Brittany

Hi Liu! Thank you ☺️ I created a series within Dev.to. When you create a series it automatically makes the liquid tags. Check this article out and let me know if you need any help :)