Devise token_authenticatable deprecated, what is the alternative?

harinsa picture harinsa · Sep 21, 2013 · Viewed 20.2k times · Source

I have been using token_authenticatable before to secure my API, however, I have found that it was deprecated? What should I use instead and why did they deprecate it?

Answer

Neal picture Neal · Sep 28, 2013

I wanted to keep backwards compatibility so I just moved everything into a concern to avoid the warning. Here's my code and associated specs:

/app/models/concerns/token_authenticatable.rb

module TokenAuthenticatable
  extend ActiveSupport::Concern

  module ClassMethods
    def find_by_authentication_token(authentication_token = nil)
      if authentication_token
        where(authentication_token: authentication_token).first
      end
    end
  end

  def ensure_authentication_token
    if authentication_token.blank?
      self.authentication_token = generate_authentication_token
    end
  end

  def reset_authentication_token!
    self.authentication_token = generate_authentication_token
    save
  end

  private

  def generate_authentication_token
    loop do
      token = Devise.friendly_token
      break token unless self.class.unscoped.where(authentication_token: token).first
    end
  end
end

/app/models/user.rb

class User < ActiveRecord::Base
    include TokenAuthenticatable
end

/app/models/employee.rb

class Employee < ActiveRecord::Base
    include TokenAuthenticatable
end

/spec/models/user_spec.rb

describe User do
    it_behaves_like 'token_authenticatable'
end

/spec/models/employee_spec.rb

describe Employee do
    it_behaves_like 'token_authenticatable'
end

spec/shared_examples/token_authenticatable.rb

shared_examples 'token_authenticatable' do
  describe '.find_by_authentication_token' do
    context 'valid token' do
      it 'finds correct user' do
        class_symbol = described_class.name.underscore
        item = create(class_symbol, :authentication_token)
        create(class_symbol, :authentication_token)

        item_found = described_class.find_by_authentication_token(
          item.authentication_token
        )

        expect(item_found).to eq item
      end
    end

    context 'nil token' do
      it 'returns nil' do
        class_symbol = described_class.name.underscore
        create(class_symbol)

        item_found = described_class.find_by_authentication_token(nil)

        expect(item_found).to be_nil
      end
    end
  end

  describe '#ensure_authentication_token' do
    it 'creates auth token' do
      class_symbol = described_class.name.underscore
      item = create(class_symbol, authentication_token: '')

      item.ensure_authentication_token

      expect(item.authentication_token).not_to be_blank
    end
  end

  describe '#reset_authentication_token!' do
    it 'resets auth token' do
    end
  end
end