【问题标题】:Rails controller and permissions for usersRails 控制器和用户权限
【发布时间】:2017-03-21 18:27:05
【问题描述】:

我遇到了一个非常简单的 Rails 问题。

我有一个博客控制器,其中包含以下几行:

skip_before_action :check_admin, only: [:index, :show], raise: false

...

private
...

def check_admin
  redirect_to(root_path) unless current_user && current_user.admin?
end

我希望行为如下:

如果用户未登录或已登录并且其角色不是管理员,并尝试访问其他操作而不是 :index 和 :show,它应该重定向到根路径。

但是现在,当用户未登录时,它会为每个操作显示用户登录页面,而它允许任何已登录用户的每个操作,甚至不允许管理员用户。

我正在使用 Devise 和 CanCanCan。我的ability.rb 看起来像这样:

def initialize(user)
  can :read, :all                   # allow everyone to read everything
  if user && user.admin?
    can :access, :rails_admin       # only allow admin users to access Rails Admin
    can :dashboard                  # allow access to dashboard
    can :manage, :all
  end
end

我哪里失败了?

编辑:我将控制器中的操作调用更改为:

before_action :check_admin, except: [:index, :show]

现在,已登录的用户会显示所需的行为,而对于未登录的用户,它仍会针对包括索引和显示在内的每个操作重定向到用户登录页面。

编辑 2:我在 application_controller.rb 中有 before_action :authenticate_user!,而其他一些控制器设置为 skip_before_action :authenticate_user!, :only => [:index]。但在我看来,这不应该干扰博客控制器......

另外,我在config/initializers/rails_admin.rb 中有以下内容:

RailsAdmin.config do |config|

  ### Popular gems integration

  ## == Devise ==
  config.authenticate_with do
    warden.authenticate! scope: :user
  end
  config.current_user_method(&:current_user)

【问题讨论】:

  • 这是对三元运算符的严重滥用。为什么不只是redirect_to(root_path) unless current_user && current_user.admin?
  • @meagar 我试过你的线,结果是一样的
  • 这不是一个答案,只是评论
  • 我还是用你的台词编辑了这个问题;)
  • 你有 before_action :authenticate_user! ?在您的控制器或任何其他设计身份验证调用中? (包括在应用程序控制器中)

标签: ruby-on-rails redirect devise controller action


【解决方案1】:

问题是你有 before_action :authenticate_user!在您的应用程序控制器中。如果你看到你的控制器定义,:

class BlogController< ApplicationController

'

你需要

Class BlogController < ApplicationController
skip_before_action :authenticate_user!, :only => [:index, :show]

【讨论】:

  • 所以没有办法告诉控制器重定向到未登录用户的根路径,不是吗?添加您的行实际上会将它们重定向到登录路径
  • 是的,我的回答是,博客控制器中的所有操作(索引和显示除外)都将被重定向到未登录用户的 root_path。它应该可以工作,你可以在这里阅读:guides.rubyonrails.org/action_controller_overview.html#filters
  • 你能解释一下吗?我在控制器顶部添加了您的行,以便 check_admin 操作过滤器遵循该行。但是,如果未登录的用户执行禁止操作,则会显示登录路径,而不是根路径。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-27
  • 1970-01-01
  • 2017-03-20
  • 2017-08-30
相关资源
最近更新 更多