2013-04-05 54 views
2

我正在使用2 rails應用程序共享的數據庫。設計自定義密碼字段(紅寶石)

Web應用程序使用BCrypt和has_secure_password來驗證用戶,我的應用程序是一個REST API,使用Devise驗證用戶。密碼哈希是一樣的。

所以,我想使用字段password_digest而不是encrypted_pa​​ssword通過Devise進行身份驗證,我不知道如何! (我正在尋找文檔,但什麼也沒找到)。所以,我必須將密碼哈希從password_digest複製/粘貼到encrypted_pa​​ssword。

這裏我的會話控制器代碼:

class SessionsController < Devise::SessionsController 

before_filter :ensure_params_exist 

def create 
    build_resource 
    resource = User.find_for_database_authentication(:email => params[:email]) 
    return invalid_login_attempt unless resource 

    if resource.valid_password?(params[:password]) 
     #resource.ensure_authentication_token! #make sure the user has a token generated 
     sign_in("user", resource) 
     render :json => { :authentication_token => resource.authentication_token, :lastname => resource.lastname, :firstname => resource.firstname, :last_sign_in => resource.last_sign_in_at }, :status => :created 
    return 
    end 
    invalid_login_attempt 
end 

#def destroy 
# # expire auth token 
# @user=User.where(:authentication_token=>params[:auth_token]).first 
# @user.reset_authentication_token! 
# render :json => { :message => ["Session deleted."] }, :success => true, :status => :ok 
#end 


protected 
    def ensure_params_exist 
     return unless params[:email].blank? 
     render :json=>{:success=>false, :message=>"missing email parameter"}, :status=>422 
    end 

    def invalid_login_attempt 
     warden.custom_failure! 
     render :json => { :errors => ["Invalid email or password."] }, :success => false, :status => :unauthorized 
    end 

然後我的用戶模型

class User < ActiveRecord::Base 
    before_save :ensure_authentication_token 
    # Include default devise modules. Others available are: 
    # :token_authenticatable, :confirmable, 
    # :lockable, :timeoutable and :omniauthable 
    devise :database_authenticatable, :trackable, :token_authenticatable#, :registerable, 
     #:recoverable, :rememberable, :trackable, :validatable 

    # Setup accessible (or protected) attributes for your model 
    attr_accessible :email, :password, :password_confirmation, :remember_me, :client_id, :firstname, :group_id, :lastname, :password, :password_confirmation, :role_id, :group_ids, :auth_token, :password_digest, :encrypted_password 

    # Relations dans la base de données 
    belongs_to :client 
    belongs_to :role 

    has_many :memberships 
    has_many :groups, :through => :memberships 



end 

回答

2

我不知道如何BCrypt/has_secure_password作品,但您可以 使用虛擬屬性如下

def encrypted_password 
return password_digest 
end 

def encrypted_password= value 
return password_digest 
end 

甚至更​​好,使用別名方法 將encrypted_pa​​ssword和encrypted_pa​​ssword =設置爲password_digest和password_digest =的別名方法。

+0

嗨,謝謝你的回答。我應該在哪裏放置這些代碼?我在我的用戶模型中嘗試過,但它返回一個錯誤,並在我的Sessions控制器中,如果我嘗試此代碼,身份驗證不起作用。謝謝 – LBStephane 2013-04-05 14:08:51

+0

在用戶模型中。你得到了什麼錯誤?你提到了有關將password_digest複製並粘貼到加密密碼中以進行工作的內容。關於這一點的細節。 – manoj 2013-04-05 16:32:09