Admin Authorization with CanCan
Asked Answered
I

3

9

A have a bunch of controllers with the Admin namespace. I want to restrict access to these unless the user is an admin. Is there a way to do this using CanCan without having to call unauthorized! in every method of every controller?

Irvingirwin answered 19/1, 2011 at 16:24 Comment(0)
J
8

Add an application controller to your namespace and a before filter to it.

class ApplicationController < ActionController::Base
end

class Admin::ApplicationController < ApplicationController 
  # these goes in your namespace admin folder
  before_filter :check_authorized

  def check_authorized
    redirect_to root_path unless can? :admin, :all
  end
end

class SomeadminController < Admin::ApplicationController
   def some_action
     # do_stuff
   end
end
Joel answered 19/1, 2011 at 16:32 Comment(0)
S
1

The Admin Namespaces wiki page for CanCan lists out several solutions to this problem.

  • As @mark suggested, have a base controller for admins which checks authorization for every action.
    • You may not need to use CanCan at all for this if all you require is to check that users have an admin flag.
  • For handling admins differently from each other (as opposed to differently from regular users only), consider a separate AdminAbility class (this is a little off-topic, but could prove relevant).
Selfcontrol answered 31/7, 2012 at 15:39 Comment(0)
S
0

now rails_admin has full support with Cancan, you can find it in its official website, there is a wiki page for this topic:

Rails Admin's authorization with CanCan:

Silvas answered 14/3, 2012 at 3:39 Comment(2)
Did he mention rails_admin?Wideman
yes you are right, he didn't mention rails_admin. I don't suggest using rails_admin since it's no so good as I thought.Silvas

© 2022 - 2024 — McMap. All rights reserved.