ruby-on-railsrubydevisemd5bcrypt

Devise: sign in with two possible encrypted passwords


My app works with the Devise gem for authentication, but I want customize it for sign in with two possible encrypted passwords, due to my previous app worked with MD5. I've two fields in my users table: encrypted_password and encrypted_old_password (I've created), I want check if exists the value encrypted_password and if the password sent matches the one set, otherwise, check if it does with MD5 and if true, then replace the value encrypted_password.

How I do this?


Solution

  • I don't know if my answer is fancy, but works for me. I hope someone can improve what I did.

    class SessionsController < Devise::SessionsController
    
      def create
        recover_old_password unless user_signed_in?
    
        resource = warden.authenticate! auth_options
        set_flash_message(:notice, :signed_in) if is_navigational_format?
        sign_in resource_name, resource
    
        respond_with resource, :location => after_sign_in_path_for(resource)
      end
    
      def recover_old_password
    
        email = params[:user]['email']
        pass  = Digest::MD5.hexdigest params[:user]['password']
    
        @user = User.find_by_email_and_encrypted_old_password(email, pass)
    
        if @user.blank?
    
          resource = warden.authenticate! auth_options
          respond_with resource, :location => after_sign_in_path_for(resource)
    
        elsif
    
          if !@user.encrypted_password.nil?
            @user.encrypted_password = BCrypt::Password.create params[:user]['password']
            @user.save
            create
          end  
    
        end
    
      end
    
    end