Sha256: 9f385d7f8c233389abbb2c0d1d8bbae253abde70306130da11572e890873818f

Contents?: true

Size: 1.37 KB

Versions: 8

Compression:

Stored size: 1.37 KB

Contents

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

module SimpleTokenAuthentication
  module ActsAsTokenAuthenticatable
    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

    module ClassMethods
      def acts_as_token_authenticatable(options = {})
        before_save :ensure_authentication_token
      end
    end
  end
end

Version data entries

8 entries across 8 versions & 2 rubygems

Version Path
simple_token_authentication-1.12.0 lib/simple_token_authentication/acts_as_token_authenticatable.rb
simple_token_authentication-1.11.0 lib/simple_token_authentication/acts_as_token_authenticatable.rb
simple_token_authentication-1.10.1 lib/simple_token_authentication/acts_as_token_authenticatable.rb
simple_token_authentication-1.10.0 lib/simple_token_authentication/acts_as_token_authenticatable.rb
simple_token_authentication-1.9.1 lib/simple_token_authentication/acts_as_token_authenticatable.rb
simple_token_authentication-1.8.0 lib/simple_token_authentication/acts_as_token_authenticatable.rb
stn-simple_token_authentication-1.7.1 lib/simple_token_authentication/acts_as_token_authenticatable.rb
simple_token_authentication-1.7.0 lib/simple_token_authentication/acts_as_token_authenticatable.rb