Authenticate using Devise and Rails Admin for particular routes
Asked Answered
J

1

6

I use Rails Admin and Devise for admin and user model. I have added one column "admin" to the user model to indicate its identity.

In the config/routes.rb, I mount /admin for RailsAdmin:Engine

I want to only allow current_user.admin users to access /admin, otherwise, redirect user to home page.

How can I implement this in the cleanest code?

Jerusalem answered 4/3, 2013 at 9:51 Comment(0)
S
15

on your admin controllers:

class MyAdminController < ApplicationController
  before_filter :authenticate_user!
  before_filter :require_admin
end

on your application controller:

class ApplicationController < ActionController::Base


  def require_admin
    unless current_user && current_user.role == 'admin'
      flash[:error] = "You are not an admin"
      redirect_to root_path
    end        
  end
end

Sorry, didn't notice it was with rails admin, you can do:

# in config/initializer/rails_admin.rb

RailsAdmin.config do |config|
  config.authorize_with do |controller|
    unless current_user.try(:admin?)
      flash[:error] = "You are not an admin"
      redirect_to main_app.root_path
    end
  end
end
Sinegold answered 4/3, 2013 at 10:0 Comment(2)
Thank you so much. But how can I overwrite the default Rails_admin engine? There is no admincontroller that I can subclass.Jerusalem
As per documentation redirection should be redirect_to main_app.root_pathPallua

© 2022 - 2024 — McMap. All rights reserved.