Maxence
Maxence

Reputation: 2339

How to prevent access to Admin namespace

I am building an Admin namespace and would like to know if there is a solution to prevent access to all controllers within this namespace to logged-in admins only.

The only solution I have found so far is adding the following to every controller:

before_action :require_admin

def require_admin
  unless current_user.admin?
    redirect_to root_path
  end
end

I am looking for something more global.

Upvotes: 2

Views: 165

Answers (2)

FixerRB
FixerRB

Reputation: 326

You can also add that code to ApplicationContoller instead of adding it to every controller and use skip_before_action :require_admin in controllers that don't need admin privileges.

Upvotes: 0

Dave Schweisguth
Dave Schweisguth

Reputation: 37637

Just use inheritance:

  • Create an AdminController.
  • Make it extend ApplicationController.
  • Make your admin controllers extend AdminController.
  • Put the filter and method in AdminController.
  • Delete the filter and method from your concrete admin controllers.

Upvotes: 4

Related Questions