我正在使用在 2 个 rails 应用程序之间共享的数据库。
使用 BCrypt 和 has_secure_password 对用户进行身份验证的 web 应用程序,以及我的应用程序,一个 REST API,使用 Devise 对用户进行身份验证。密码哈希是相同的。
所以,我想使用字段 password_digest 而不是 encrypted_password 通过设计进行身份验证,但我不知道如何!(我在文档中寻找,但一无所获)。所以,我必须将我的密码哈希从 password_digest 复制/粘贴到 encrypted_password 中。
这是我的会话控制器代码:
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