我应该如何构建这些before_actions?

时间:2014-05-02 02:24:09

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

目前,我的ApplicationController看起来像这样:

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  include CurrentUser

  protect_from_forgery with: :exception
  before_action :authorize
  before_action :get_current_user

  protected
    def authorize
      unless User.find_by(id: session[:user_id])
        redirect_to login_url, notice: "Please log in"
      end
    end
end

如您所见,authorize检查以确保用户登录,如果没有 - 将其重定向到登录页面。这非常有效。

在&#34;前面&#34;用户不必登录的页面,我这样做:

skip_before_action :authorize, only: [:names, :of, :ok, :pages]

现在,我已经添加了一些需要提升权限的页面,因此该方法(我认为)看起来像这样:

def check_for_elevated_role
    u = User.find(id: session[:user_id])
    unless u.role >= 10
        redirect_to some_url, notice: "Insufficient Role"
    end
end

我的问题是,实现此功能的最佳方式是什么?我应该将此作为之前的操作添加到我想要锁定的页面,或者(就像我使用授权一样),将其添加到ApplicationController并在用户不需要权限的页面上跳过此操作(这是安全的方式,对吧?)。无论如何,你能告诉我before_actions应该是什么样的吗?

1 个答案:

答案 0 :(得分:3)

我将此作为答案添加,因为它有点长作为评论。

您最有可能想要使用before_action创建一个不同的控制器并从该控制器继承

class AuthorizeController < ApplicationController
  before_action :authorize_admin

  protected

  def authorize_admin
    # your logic here
  end
end

class ControllerThatNeedsAuthorizationController < AuthorizeController
  skip_before_action :action_that_doesnt_need_authorization
end
相关问题