1

我正在尝试使用 sinatra 构建 [Ryan Bates 的“authenticaion”][1],但身份验证不起作用。我收到“未定义的方法密码哈希”错误。

其他一切都在工作。我检查了 datamapper 文档,特别是对于延迟加载,但找不到任何有用的东西。代码如下。我在做什么错?

main.rb(仅相关部分)

post "/login" do
  user = User.authenticate params[:email], params[:password]
  if user
    session[:user_id] = user.id
    redirect "/"
  else
    session[:errors] = "No such user or bad password."
    redirect "/login"
  end
end

用户.rb

require 'data_mapper'
require 'dm-validations'
require 'bcrypt'

module Kimsin

  DataMapper.setup :default, 'sqlite3:///home/barerd/RProjects/kimsin/users.db' 

  class User 
    attr_accessor :password, :confirm_password

    include DataMapper::Resource

    property :id, Serial
    property :email, String, :required => true, :unique => true, :format => :email_address,
    :messages => { :presence => "We need your email address.", :is_unique => "We already have that email.", :format => "Doesn't look like an email adress.."}
    property :password_salt, String
    property :password_hash, String, :length => 80
    validates_presence_of :password, :confirm_password, :messages => { :presence => "You have to type a password and confirm it." }
    validates_format_of :password, :confirm_password, :with => /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])([\x20-\x7E]){8,40}$/, :messages => { :format => "The password should be 8 to 40 characters long and contain at least one digit, one lowercase and one uppercase letter and one special character." }

    before :save, :encrypt_password

    def self.authenticate email, password
      user = User.all :email.like => email
      if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt)
        user
      else
        nil
      end
    end

    def encrypt_password
      if password != nil
        self.password_salt = BCrypt::Engine.generate_salt
        self.password_hash = BCrypt::Engine.hash_secret password, password_salt
      end
    end
  end

  DataMapper.finalize
end
4

1 回答 1

0

添加一个attr_reader :password_hash解决它。

于 2012-06-09T09:47:10.170 回答