parm530
11/8/2017 - 3:24 PM

Admin Panel

Guide to creating an admin panel in a rails app

  • ... refers to the global module namspace folder, ex. summit

Admin Panel

  • To be able to create admins, add an admin flag to users
rails g migration add_admin_to... admin:boolean
  • Select a user to become admin, head into rails c:
  Users.first.update_column :admin, true
  • To keep the admin logic encapsulated, you will need an admin namespace:
    • Create an admin folder in core/app/controllers/.../
    • Inside this folder, create a controller admin_controller.rb
    • The admin panel should be available at /admin and should be defaulted to the index action
    • Adding routes:
namespace :admin do
  get '/' => 'admin#index'
end
  • Add the link to the navbar, checking first to see if the user.admin == true, if current_user.admin?, then provide the link_to the admin page
  • Add the view.
  • NOTE: You must create 2 folders named admin before creating the actual file
    • The first folder is for the namespaced admin
    • The second one is for the controller, named AdminController: app/views/.../admin/admin/index.html.erb
    • Need an admin_controller
    • May need other controllers, so you will need routes for them as well under the namspaced routes

CanCan Gem

  • CanCan gem is used to ensure that other users are not permitted to access certain routes!
    • What a user can and cannot do are defined in the ability file, defined in the core module
  • To generate this file:
rails g cancan:ability
  • CanCan uses a method called current_ability to get an ability object
  • When using custom namespaces, you'll need to override this method.
  • You can do so in the ApplicationController
  def current_ability
    @current_ability ||= Samurai::Ability.new(current_user)
  end
  • CanCan raises an exception when someone tries to access a forbidden resource, it is better to show a 403 page when this happens. To do so, in the application_controller:
rescue_from CanCan::AccessDenied do |exception|
  render :file => 'static/403.html", :status => 403, :layout => false
end
  • Create a directory called static and a file called 403.html, inside of engines/core/views/.../
  • Add Authorization Checks in Controllers
    • place this line in the controllers:
authorize_resource class: false
  • class: false, is used to specify that this controller is not linked to a model
  • This line is used to confirm the access for a user.
  • Finally, add the abilities to the ability file!
if user.admin?
  can :manage, :all
else
  can :read, :dashboard
end