Class: JWTEasy::Encoder

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

Overview

Encoder object for generating new tokens.

  • This is usually not instantiated directly, but rather by way of calling JWTEasy.encode.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data, configuration = nil) ⇒ Encoder

Initializes a new encoder instance.

  • If no configuration object is passed or is nil, the value of JWTEasy.configuration is used as the configuration object

Parameters:

  • data (Object)

    the data to be encoded

  • configuration (Configuration) (defaults to: nil)

    the configuration object



19
20
21
22
# File 'lib/jwt_easy/encoder.rb', line 19

def initialize(data, configuration = nil)
  @data           = data
  @configuration  = configuration || JWTEasy.configuration
end

Instance Attribute Details

#configurationObject (readonly)

Returns the value of attribute configuration.



9
10
11
# File 'lib/jwt_easy/encoder.rb', line 9

def configuration
  @configuration
end

#dataObject (readonly)

Returns the value of attribute data.



9
10
11
# File 'lib/jwt_easy/encoder.rb', line 9

def data
  @data
end

Instance Method Details

#encodeString

Encodes the data with the configured options.

Returns:

  • (String)

    the encoded token



27
28
29
# File 'lib/jwt_easy/encoder.rb', line 27

def encode
  JWT.encode(payload, configuration.secret, configuration.algorithm)
end

#expiration_timeInteger

Calculates the expiration time if configured.

Returns:

  • (Integer)

    the expiration time



48
49
50
# File 'lib/jwt_easy/encoder.rb', line 48

def expiration_time
  Time.now.to_i + configuration.expiration_time
end

#not_before_timeInteger

Calculates the not before time if configured.

Returns:

  • (Integer)

    the not before time



55
56
57
# File 'lib/jwt_easy/encoder.rb', line 55

def not_before_time
  Time.now.to_i - configuration.not_before_time
end

#payloadObject

Determines the structure of the payload to be encoded.

Returns:

  • (Object)

    the payload to be encoded



34
35
36
37
38
39
40
41
42
43
# File 'lib/jwt_easy/encoder.rb', line 34

def payload
  case configuration.claim
  when CLAIM_EXPIRATION_TIME
    { data: data, exp: expiration_time }
  when CLAIM_NOT_BEFORE_TIME
    { data: data, nbf: not_before_time }
  else
    data
  end
end