Module: ApiTokenable

Extended by:
ActiveSupport::Concern
Included in:
ApiToken
Defined in:
lib/app/models/concerns/api_tokenable.rb

Overview

API tokenable, support for the api token in user, but also may be applied elsewhere

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object



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
35
36
37
# File 'lib/app/models/concerns/api_tokenable.rb', line 9

def self.included(base)
  base.class_eval do
    # store api token
    field :api_token, type: String
    # if the api token should be reset
    field :reset_api_token, type: Mongoid::Boolean, default: true
    field :last_authenticated_at, type: Time
    field :last_authenticated_ip, type: String
    # call back to reset the api token.
    before_save :assign_api_token, if: :reset_api_token
    # set the index on api token
    index({ api_token: 1 }, background: true)

    def cycle_api_token
      self.set api_token: SecureRandom.urlsafe_base64
      api_token
    end

    private

    #
    # set the api token
    #
    def assign_api_token
      self.reset_api_token = false
      self.api_token = SecureRandom.urlsafe_base64
    end
  end
end