Rails:将params传递给before_filter authenticate_user

时间:2016-01-15 04:44:12

标签: ruby-on-rails devise

以下是我的控制器类:

class PController < ApplicationController

  before_filter authenticate_user! 

  def show
    logger.info("I am now logged in")
    if params.has_key?(:p) and params.has_key?(:t)
      # Do something
    end

  end
end

我想将GET参数传递给authenticate_user进行处理。成功登录后,将返回同一控制器以及参数。请帮助我学习实现这一目标的方法。

2 个答案:

答案 0 :(得分:0)

Devise已经为您做到了,但如果您想自己做,可以创建一个不同的方法来验证用户,如下所示:

class PController < ApplicationController

  before_filter :restrict_access 

  def show
    logger.info("I am now logged in")
    if params.has_key?(:p) and params.has_key?(:t)
      # Do something
    end

  end
end



def restrict_access
    user = User.find_by(email: params[:session][:email].downcase)
    if user && user.authenticate(params[:session][:password])
      # Log the user in and redirect to the show page.
    else
      flash[:danger] = 'Invalid email/password combination' # Not quite right!
      render 'login'
    end
  end
end

答案 1 :(得分:0)

理想情况下,我们会将请求网址存储到会话中,成功登录后,我们将返回该网址。为此,我在ApplicationController中定义了一些函数:

class ApplicationController < ActionController::Base

  after_filter :store_location

  # For devise    
  def after_sign_in_path_for(resource)
    previous_url
  end    

  private

  def previous_url
    url = session[:previous_url]
    url.present? ? url : '/'
  end

  def store_location
    # store last url - this is needed for post-login redirect to whatever the user last visited
    # we will store only get request which doesn't have /user/ pattern and not a ajax request
    should_store_url = request.get? && !request.path.include?('/users/') && !request.xhr?
    session[:previous_url] = request.fullpath if should_store_url
  end
end

如果我们使用Devise进行身份验证,Devise将自动为我们调用after_sign_in_path_for,否则,我们将手动调用此方法以便在登录前返回请求。

有关详细信息,我们可以here了解我们为什么需要覆盖after_sign_in_path_for以使其正常工作(Yup for Devise人)