Module: ActsAsTokenable::Tokenable

Defined in:
lib/acts_as_tokenable/tokenable.rb

Instance Method Summary collapse

Instance Method Details

#acts_as_tokenableObject



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/acts_as_tokenable/tokenable.rb', line 3

def acts_as_tokenable
  class_eval do
    has_many :tokens, as: :tokenable, dependent: :destroy, class_name: '::ActsAsTokenable::Token', :foreign_key => :tokenable_id

    def add_token(options = {})
      options = options.reverse_merge(default_options)

      self.tokens.create(options)
    end

    class << self
      def find_by_token(token_id, token_hash)
        token_record = ActsAsTokenable::Token.active.find_by(:token_id => token_id)

        return nil unless token_record

        if BCrypt::Password.new(token_hash) == token_record.token
          token_record.try(:tokenable)
        else
          nil
        end
      end
    end

    private
      def default_options
        {
          :expires_at => 30.days.from_now
        }
      end
  end
end