如何限制对admin命名空间的访问

时间:2015-01-10 05:34:58

标签: ruby-on-rails ruby-on-rails-4

我有一个前端和管理部分。有3roles super_admin,admin,user。使用super_admin或admin登录时,我应该能够访问/ admin / namespace,这是有效的。但是当我以用户身份登录时,我应该无法访问/ admin / namespace,它应该重定向404page或索引页面。我使用cancan来限制控制器的访问。

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

当我使用用户角色登录并转到/ admin / path时,它会重定向到admin部分。如何仅在用户角色的路由中限制它?

1 个答案:

答案 0 :(得分:5)

1)为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 or VALID_ROLES.include?(current_user.role)
      redirect_to root_path # change this to your 404 page if needed
    end
  end

end

2)从Admin :: BaseController

继承admin命名空间中的所有控制器

管理员/ home_controller.rb

class Admin::HomeController < Admin::BaseController

  def index
  end

end