Sha256: bf40803856ed384dbf2e8844ac672fcf302d8589c974f98a8a0b81e991a10bf8

Contents?: true

Size: 1.22 KB

Versions: 1

Compression:

Stored size: 1.22 KB

Contents

require 'active_support/concern'
require 'simple_token_authentication/token_generator'

module SimpleTokenAuthentication
  module TokenAuthenticatable
    extend ::ActiveSupport::Concern

    # Please see https://gist.github.com/josevalim/fb706b1e933ef01e4fb6
    # before editing this file, the discussion is very interesting.

    included do
      private :generate_authentication_token
      private :token_suitable?
      private :token_generator
    end

    # Set an authentication token if missing
    #
    # Because it is intended to be used as a filter,
    # this method is -and should be kept- idempotent.
    def ensure_authentication_token
      if authentication_token.blank?
        self.authentication_token = generate_authentication_token(token_generator)
      end
    end

    def generate_authentication_token(token_generator)
      loop do
        token = token_generator.generate_token
        break token if token_suitable?(token)
      end
    end

    def token_suitable?(token)
      self.class.where(authentication_token: token).count == 0
    end

    # Private: Get one (always the same) object which behaves as a token generator
    def token_generator
      @token_generator ||= TokenGenerator.new
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
simple_token_authentication-1.9.0 lib/simple_token_authentication/token_authenticatable.rb