Search code examples
ruby-on-railsruby-on-rails-4

How to properly set up the admin role in my app


I am using "devise" and "namespaced" to make the administration of a website but the method "admin?" (current_user.admin?), where did it come from ? if its supposed to be a field on my table "user"? when it became a method?

class Admin::ApplicationController < ApplicationController

  before_action :authorize_admin!

  def index
  end

  private
    def authorize_admin!
      authenticate_user!
      unless current_user.admin?
        redirect_to root_path, alert: "You must be an admin to do that."
     end 
  end
end

Solution

  • Your approach of add an administrator to your app is not very functional, what if you need to add more roles?

    My suggestion is to use a gem for your roles like Rolify, with Rolify you can create any role, and use a gem for allow and deny perms like Cancancan

    For example with Rolify you can add the admin role like this:

    user = User.find(1)
    user.add_role :admin
    

    Then with Cancancan you can define perms for each controller action or per set of controller actions, let's say you have a model Post and only admins can manage them:

    #app/models/ability.rb
    class Ability
      include CanCan::Ability
    
      def initialize(user)
        user ||= User.new # guest user (not logged in)
        if user.has_role? :admin
           can :manage, :all
        else
           can :read, :all
        end
      end
    end
    

    The above is telling rails that the :admin role can manage all the models in your app, and all the other roles (including guest users) can read all the models in your app. For more information about defining perms check the Wiki of Cancancan

    Now if you want to show a message when a user is trying to enter to a non-authorized resource you can rescue the exception of Cancancan:

    #In your application_controller.rb
    rescue_from CanCan::AccessDenied do |exception|
        if exception.message.match(/are not/i)
            redirect_to root_path, :alert => "Oouch... no estás autorizado para acceder a esta página"
        else
            redirect_to root_path, :alert => exception.message
        end
     end
    

    Rolify and Cancancan integrate smoothly with Devise, so this is the right now for creating roles and perms in your app. I hope have helped you.