Hello,
Very nice gem, but is there a tutorial - a nice way to set up authentication / login for the admin? Would be great to see how to do it elegantly..
thanks
Are you using authentication elsewhere in your app? I haven't tried this, but because Administrate is a Rails Engine I'm guessing you could override Adminstrate::ApplicationController to add authentication the same way you would in the rest of your app.
The most basic version would be to add an admin? method on your user model and test for it. For example
module Admin
class ApplicationController < Administrate::ApplicationController
before_action :authenticate_user!
before_filter :authenticate_admin
def authenticate_admin
redirect_to '/', alert: 'Not authorized.' unless current_user && current_user.admin?
end
end
@coneybeare:
Any change you could share an example app using Cancancan for roles with Administrate?
@introvert The commenters above are spot on-- you hook up your authentication inside the Admin::ApplicationController which gets generated for you by Administrate. See here. You have full control over that controller just like any other you'd have in Rails.
Hope that helps!
For anyone looking to restrict access to accessible records only, using cancan: You can find some info about what needs to be done here: https://administrate-prototype.herokuapp.com/authorization
What is mentioned there works well for filtering collections of records, but breaks when trying to authorize individual resources. The solution is to override the find_resource method. Here is the final working code:
# app/controllers/admin/application_controller.rb
rescue_from CanCan::AccessDenied do |exception|
flash[:notice] = "Access Denied."
redirect_to admin_root_path
end
# Override find_resource, because it initially calls scoped_resource.find()
# which breaks since we are overriding that method as well.
def find_resource(param)
resource_class.default_scoped.find(param)
end
# Limit the scope of the given resource
def scoped_resource
super.accessible_by(current_ability)
end
# Raise an exception if the user is not permitted to access this resource
def authorize_resource(resource)
raise CanCan::AccessDenied unless show_action?(params[:action], resource)
end
# Hide links to actions if the user is not allowed to do them
def show_action?(action, resource)
# translate :show action to :read for cancan
if ["show", :show].include?(action)
action = :read
end
can? action, resource
end
For access to the admin namespace in general, I used the methods mentioned in comments above.
Most helpful comment
The most basic version would be to add an admin? method on your user model and test for it. For example