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

sincerelybrittany

Brittany

Posted on August 8, 2020

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

πŸ’– πŸ’ͺ πŸ™… 🚩
sincerelybrittany
Brittany

Posted on August 8, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related