I'm using a database shared between 2 rails apps.
A webapp using BCrypt and has_secure_password to authenticate user, and my app, an REST API, using Devise to authenticate users. Password hash is the same.
So, I would like to use the field password_digest instead of encrypted_password to authenticate via Devise and I don't know how ! (I'm seeking in the documentation but find nothing). So, I have to copy / paste my password hash from password_digest to encrypted_password yet.
Here my session controller Code :
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
end
And then my User Model
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
I am not aware about how BCrypt/has_secure_password works, but you can either use virtual attributes as follows
def encrypted_password
return password_digest
end
def encrypted_password= value
return password_digest
end
Or even better, use alias methods set encrypted_password and encrypted_password= as alias methods for password_digest and password_digest=.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With