User.authenticate方法在Rails 3中返回nil?

时间:2012-02-26 22:52:36

标签: ruby-on-rails ruby-on-rails-3 railstutorial.org

即使用户在数据库中存在正确的电子邮件和密码,User.authenticate方法也会返回nil。从Sessions控制器中的Create操作或Rails控制台(irb)调用authenticate方法时会发生这种情况。

非常感谢任何有关此问题的帮助。

class SessionsController < ApplicationController

    def new
    end

    def create
      user = User.authenticate(params[:session][:email],
                                   params[:session][:password])
      if user.nil?
        flash.now[:error] = "Invalid email/password combination"
        render 'new'
      else
        sign_in user
        redirect_to user
      end       
    end

    def destroy
      sign_out
      render 'pages/options'
    end

end

这是我的用户模型:

class User < ActiveRecord::Base

  attr_accessor :password
  attr_accessible :first_name, :last_name, :email, :password, :password_confirmation,    
                  :account_type, :email_confirmed, :weight

  validates :password,  :presence => true,
                    :confirmation => true,
                    :length => { :within => 6..40 }

  before_save :encrypt_password

  def has_password?(submitted_password)
    encrypted_password == encrypt(submitted_password)
  end

  def self.authenticate(email, submitted_password) 
    user = find_by_email(email)
    return nil if user.nil?
    return user if user.has_password?(submitted_password)
  end

  def self.authenticate_with_salt(id, cookie_salt)
    user = find_by_id(id)
    (user && user.salt == cookie_salt) ? user : nil 
  end

  private #################################################

  def encrypt_password
    self.salt = make_salt if new_record?
    self.encrypted_password = encrypt(password)
  end

  def encrypt(string)
    secure_hash("#{salt}--#{string}")
  end

  def make_salt
    secure_hash("#{Time.now.utc}--#{password}")
  end

  def secure_hash(string)
    Digest::SHA2.hexdigest(string)
  end

  def generate_email_conf_code
    email_conf_code = secure_hash("#{Time.now.utc}")
    self.email_conf_code = email_conf_code
  end

end

2 个答案:

答案 0 :(得分:0)

尝试检查您的服务器日志。您也可以直接在终端上监控它们。查找服务器上收到的会话电子邮件。在Rails 3.1.1

上看起来像这样
Parameters: {"session"=>{"email"=>"xxx@yyy.com", "password"=>"[FILTERED]"}}

看到您正确收到电子邮件。如果没有,我猜你知道该怎么做。

答案 1 :(得分:0)

您的数据库是否存储了password_digest或encrypted_pa​​ssword列? michael hartl的旧教程使用了password_digest,现在他们看起来似乎是encrypted_pa​​ssword。