2012-06-09 35 views
1

我試圖用sinatra來構建[Ryan Bates的'從頭開始的身份驗證]] [1],但驗證不起作用。我收到一個「未定義的方法password_hash」錯誤。未定義的方法`password_hash'數據映射器的錯誤

其他所有工作。我檢查了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 

user.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 

回答

0

添加attr_reader :password_hash解決它。