Class: AuthToken

Inherits:
Object
  • Object
show all
Defined in:
lib/auth_token.rb

Constant Summary collapse

DEFAULT_EXPIRE_INTERVAL =
1.year

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(args = {}) ⇒ AuthToken

Returns a new instance of AuthToken.



9
10
11
12
13
14
15
# File 'lib/auth_token.rb', line 9

def initialize(args={})
  @expire_interval = args[:expire_interval] || DEFAULT_EXPIRE_INTERVAL
  @payload    = args[:payload]
  @token      = args[:token]
  @expiration = @expire_interval.from_now.to_time.to_i
  @token      ||= issue if args[:payload]
end

Instance Attribute Details

#expire_intervalObject

Returns the value of attribute expire_interval.



7
8
9
# File 'lib/auth_token.rb', line 7

def expire_interval
  @expire_interval
end

#payloadObject

Returns the value of attribute payload.



7
8
9
# File 'lib/auth_token.rb', line 7

def payload
  @payload
end

#tokenObject

Returns the value of attribute token.



7
8
9
# File 'lib/auth_token.rb', line 7

def token
  @token
end

Instance Method Details

#decodedObject



39
40
41
# File 'lib/auth_token.rb', line 39

def decoded
  @token.blank? ? false : JWT.decode(@token, Rails.application.secrets.secret_key_base).first.symbolize_keys
end

#expirationObject

reset token if expired



31
32
33
# File 'lib/auth_token.rb', line 31

def expiration
  @expiration = expired? ? @expire_interval.from_now.to_time.to_i : @expiration
end

#expired?Boolean

Returns:

  • (Boolean)


35
36
37
# File 'lib/auth_token.rb', line 35

def expired?
  @token.blank? || Time.at(decoded[:expiration]) > Time.zone.now.to_time.to_i
end

#issueObject



17
18
19
20
# File 'lib/auth_token.rb', line 17

def issue
  @payload[:expiration] = expiration # Set expiration 
  @token =  JWT.encode(@payload, Rails.application.secrets.secret_key_base)
end

#valid?Boolean

Returns:

  • (Boolean)


22
23
24
25
26
27
28
# File 'lib/auth_token.rb', line 22

def valid?
  begin
    !expired? && !decoded.blank?
  rescue
    false
  end
end