Reputation: 1528
I have a frontend and admin section. there are 3roles super_admin,admin,user. When logged in with super_admin or admin i should be able to access /admin/ namespace, which is working. But when I am logged in as user, i should not be able to access /admin/ namespace, it should redirect 404page or index page. I am using cancan to restrict access of controllers.
namespace :admin do
// admin routes
end
//Devise for user model
devise_for :users
//Role model
class Role < ActiveRecord::Base
has_many :users
end
//User model
class User < ActiveRecord::Base
belongs_to :role
end
//Role table columns
id name
1 super_admin
2 admin
3 user
When I am logged in with user role and go to /admin/ path, it redirects to admin section. How do i restrict it in routes only for user role?
Upvotes: 2
Views: 2594
Reputation: 945
Add base controller for admin namespace admin/base_controller.rb
class Admin::BaseController < ApplicationController
before_filter :restrict_user_by_role
# edit valid roles here
VALID_ROLES = ['super_admin', 'admin']
protected
# redirect if user not logged in or does not have a valid role
def restrict_user_by_role
unless current_user && VALID_ROLES.include?(current_user.role)
redirect_to root_path # change this to your 404 page if needed
end
end
end
Inherit all controllers in admin namespace from Admin::BaseController
admin/home_controller.rb
class Admin::HomeController < Admin::BaseController
def index
end
end
Upvotes: 8