验证失败时暂停请求

时间:2015-06-21 12:51:29

标签: ruby-on-rails authentication

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

  def authenticate
    authenticate_player || render_unauthorized
  end

  def authenticate_player
    @player = Player.find_by(authentication_token: params[:token])
  end

  def render_unauthorized
    render json: 'Access Denied', status: :unauthorized and return
  end

然后在我的PlayerController中我有

class PlayersController&lt; ApplicationController的   before_action:authenticate_player,仅限:[:rank]

def rank
    ranked = PlayerRanker.rank(@player)

    if ranked
      render(json: { rank: ranked})
    else
      render(json: { error: 'Player not ranked' }, status: :not_found)
    end
  end

但是当我在没有身份验证令牌的情况下发送时,该方法继续进行,因为它从:unauthorized返回authenticate_player ..然后继续。如何渲染并返回并暂停所有返回?

我查找的其他示例显示将回报放在每个动作中。我想在一个单独的方法中使用它。

1 个答案:

答案 0 :(得分:0)

return只返回一个值并暂停当前函数的执行。你想要的是提出异常。

# lib/errors.rb
class NotAuthorizedException < StdError; end
def authenticate_player
  @player = Player.find_by(authentication_token: params[:token])
  raise NotAuthorizedException, 'Not authorized to view Player' unless @player
end

然后在ApplicationController中设置rescue_from处理程序。

class ApplicationController < ActionController::Base
  # ...
  rescue_from NotAuthorizedException, with: :not_authorized

  private

    def not_authorized
      render json: 'Access Denied', status: :unauthorized
    end
end

但是,如果您不是为了学习而创建自己的授权解决方案,我建议您使用CanCanCan等库。