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

How to restrict access to admin namespace

我有一个前端和管理部分。有 3 个角色 super_admin、管理员、用户。当使用 super_admin 或 admin 登录时,我应该能够访问 /admin/ 命名空间,这是有效的。但是当我以用户身份登录时,我应该无法访问 /admin/ 命名空间,它应该重定向 404 页面或索引页面。我正在使用 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/ 路径时,它会重定向到管理部分。我如何将其限制在仅用于用户角色的路由中?

  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 && 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