0

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

任何有关此问题的帮助将不胜感激。

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
4

2 回答 2

0

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

Parameters: {"session"=>{"email"=>"xxx@yyy.com", "password"=>"[FILTERED]"}}

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

于 2012-02-27T02:00:19.393 回答
0

您的数据库是否存储 password_digest 或 encrypted_pa​​ssword 列?michael hartl 的较早教程使用了 password_digest,现在它们似乎是 encrypted_pa​​ssword。

于 2012-11-14T06:20:11.610 回答