【问题标题】:How to restrict access to admin namespace如何限制对管理员命名空间的访问
【发布时间】:2022-05-04 00:44:47
【问题描述】:

我有一个前端和管理部分。有 3 个角色 super_admin、admin、user。使用 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/ 路径时,它会重定向到管理部分。我如何将它限制在仅用于用户角色的路由中?

【问题讨论】:

  • 你能把你的路线文件的 devise_for 部分贴出来
  • 我已经发布了。谢谢
  • 请为角色表列名提供一条记录

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


【解决方案1】:
  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 命名空间中的所有控制器

admin/home_controller.rb

class Admin::HomeController < Admin::BaseController

  def index
  end

end      

【讨论】:

  • 我们如何为restrict_user_by_role 编写规范?
猜你喜欢
  • 2021-11-07
  • 1970-01-01
  • 1970-01-01
  • 2017-08-26
  • 1970-01-01
  • 2015-04-26
  • 2018-11-21
  • 2019-08-11
  • 2011-11-03
相关资源
最近更新 更多