ruby-on-rails - 您无权访问此页面。在尝试与管理员联系时
问题描述
每次我尝试使用管理员连接到我的后台时,我都会收到您无权访问此页面的信息。即使一切都设置为应该接受管理员。我已经检查过了,我所有的员工都是管理员,所以不应该这样做!
我试图限制基本用户权限,我尝试使用每个帐户访问该页面,但我总是收到此错误,即使所有员工都是管理员!
能力.rb
class Ability
include CanCan::Ability
def initialize(employee)
employee ||= Employee.new # guest employee (not logged in)
if employee.admin?
can :access, :rails_admin # only allow admin employees to access Rails Admin
can :read, :dashboard
can :manage, :all
authorize!(:dashboard, @employee)
end
end
end
员工控制器.rb
class EmployeesController < ApplicationController
def employee_params
params.require(:employee).permit(:email, :encrypted_password, :password_confirmation, :role)
end
end
可访问的.rb
module Accessible
extend ActiveSupport::Concern
included do
before_action :check_employee
end
protected
def check_employee
if current_employee.admin
flash.clear
redirect_to(rails_admin.dashboard_path) && return
elsif current_employee
flash.clear
redirect_to(new_employee_session_path) && return
end
end
end
rails_admin.rb
RailsAdmin.config do |config|
config.parent_controller = "::ApplicationController"
config.authorize_with do |controller|
if current_employee.admin?
redirect_to main_app.new_account_session_path, flash: {error: 'Please Login to Continue..'}
elsif !current_employee.admin?
redirect_to main_app.root_path, flash: {error: 'You are not Admin'}
end
end
## == CancanCan ==
config.authorize_with :cancancan
config.actions do
dashboard # mandatory
index # mandatory
new
export
bulk_delete
show
edit
delete
show_in_app
end
end
路线.rb
Rails.application.routes.draw do
devise_for :users, path: 'users'
devise_for :employees, path: 'employee'
namespace :user do
resources :users
end
namespace :employee do
resources :employees
end
mount RailsAdmin::Engine => '/admin', as: 'rails_admin'
root 'index#Index'
get '/Index', to: 'index#Index'
get '/ResidentialServices', to: 'pages#ResidentialServices'
get '/CorporateServices', to: 'pages#CorporateServices'
get '/Quotes', to: 'pages#Quotes'
get '/Awards', to: 'pages#Awards'
end
将管理员添加到员工迁移
class AddAdminToEmployees < ActiveRecord::Migration[5.2]
def change
add_column :employees, :admin, :boolean, default: false
end
end
员工(您可以看到我已将我的管理员设置为 true :
Employee.create!(lastName: 'xxx', firstName: 'xxx', title: 'Comm Rep', email: 'xxx@xx.xx', encrypted_password: BCrypt::Password.create('123456'), admin: 'true')
我希望管理员能够访问后台
解决方案
您不应该在ability.rb 中传递变量而不是实例变量吗?
authorize!(:dashboard, employee)
代替
authorize!(:dashboard, @employee)
推荐阅读
- java - Java 8 原始流到集合的映射方法
- python - 使用apply lambda和str从python中的列获取子字符串
- sql-order-by - 如何使用 Criteria Builder 创建临时列 + when + order by
- c++ - 如何在没有警告的情况下将 float 转换为 size_t
- react-native - React Native 中的倒数计时器
- javascript - 动态引导轮播项目
- angular-library - 安装和使用 igniteui-angular 控件后在 Angular 库中构建错误
- c# - 如何让主项目使用 NewtonSoft.Json 和使用 Json.Net.Unity3D 的子项目?
- windows - Windows 命名管道连接
- delphi - Delphi firebird 查询 - 触发 OnFetchRecords