Class: Apiphobic::Tokens::JsonWebToken

Inherits:
Object
  • Object
show all
Includes:
Configurable, RolePredicable
Defined in:
lib/apiphobic/tokens/json_web_token.rb

Constant Summary collapse

TRANSFORMATION_EXCEPTIONS =
[
  JSON::JWT::Exception,
  JSON::JWT::InvalidFormat,
  JSON::JWT::VerificationFailed,
  JSON::JWT::UnexpectedAlgorithm,
  OpenSSL::PKey::RSAError,
  OpenSSL::Cipher::CipherError,
].freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from RolePredicable

#method_missing, #respond_to_missing?

Methods included from Configurable

#configuration, included

Constructor Details

#initialize(data:, headers: {}, private_key: configuration.private_key) ⇒ JsonWebToken

Returns a new instance of JsonWebToken.



33
34
35
36
37
38
39
40
# File 'lib/apiphobic/tokens/json_web_token.rb', line 33

def initialize(data:,
               headers:     {},
               private_key: configuration.private_key)

  self.data        = data
  self.headers     = headers
  self.private_key = private_key
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class Apiphobic::Tokens::RolePredicable

Instance Attribute Details

#dataObject

Returns the value of attribute data.



29
30
31
# File 'lib/apiphobic/tokens/json_web_token.rb', line 29

def data
  @data
end

#headersObject

Returns the value of attribute headers.



29
30
31
# File 'lib/apiphobic/tokens/json_web_token.rb', line 29

def headers
  @headers
end

#private_keyObject

Returns the value of attribute private_key.



29
30
31
# File 'lib/apiphobic/tokens/json_web_token.rb', line 29

def private_key
  @private_key
end

Class Method Details

.build(id: SecureRandom.uuid, audience: configuration.default_audience, expiration: Time.now.utc.to_i + (60 * configuration.default_expiration_in_minutes), issuer: configuration.default_issuer, issued_at: Time.now.utc, not_before: Time.now.utc, owner: nil, roles: configuration.default_roles, subject: configuration.default_subject, subject_id:, token_private_key: configuration.private_key) ⇒ Object

rubocop:disable Metrics/ParameterLists, Metrics/LineLength



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/apiphobic/tokens/json_web_token.rb', line 51

def self.build(id:                SecureRandom.uuid,
               audience:          configuration.default_audience,
               expiration:        Time.now.utc.to_i + (60 * configuration.default_expiration_in_minutes),
               issuer:            configuration.default_issuer,
               issued_at:         Time.now.utc,
               not_before:        Time.now.utc,
               owner:             nil,
               roles:             configuration.default_roles,
               subject:           configuration.default_subject,
               subject_id:,
               token_private_key: configuration.private_key)

  owner ||= subject_id

  new(
    private_key: token_private_key,
    data:        {
      'aud' => audience,
      'exp' => expiration.to_i,
      'iat' => issued_at.to_i,
      'iss' => issuer,
      'jti' => id,
      'nbf' => not_before.to_i,
      'own' => owner,
      'rol' => roles.join(','),
      'sid' => subject_id,
      'sub' => subject,
    },
  )
end

.build_from_request(request_token) ⇒ Object



42
43
44
45
46
47
48
# File 'lib/apiphobic/tokens/json_web_token.rb', line 42

def self.build_from_request(request_token)
  return Tokens::JsonWebTokens::Null.instance unless request_token

  data, headers = *request_token

  new(data: data, headers: headers)
end

.from_jwe(encrypted_token, private_key: configuration.private_key) ⇒ Object



226
227
228
229
230
231
232
233
234
235
236
237
238
# File 'lib/apiphobic/tokens/json_web_token.rb', line 226

def self.from_jwe(encrypted_token,
                  private_key: configuration.private_key)

  return JsonWebTokens::Null.instance if encrypted_token.to_s == ''

  decrypted_token = JSON::JWT
                      .decode(encrypted_token, private_key)
                      .plain_text

  from_jws(decrypted_token, private_key: private_key)
rescue *TRANSFORMATION_EXCEPTIONS => error
  raise ::Erratum::Errors::InvalidToken.wrap(error)
end

.from_jws(signed_token, private_key: configuration.private_key) ⇒ Object



240
241
242
243
244
245
246
247
248
249
250
251
252
# File 'lib/apiphobic/tokens/json_web_token.rb', line 240

def self.from_jws(signed_token,
                  private_key: configuration.private_key)

  return JsonWebTokens::Null.instance if signed_token.to_s == ''

  decoded = JSON::JWT.decode(signed_token, private_key)

  new(data:        decoded.to_h,
      headers:     decoded.header,
      private_key: private_key)
rescue *TRANSFORMATION_EXCEPTIONS => error
  raise ::Erratum::Errors::InvalidToken.wrap(error)
end

Instance Method Details

#audienceObject



150
151
152
# File 'lib/apiphobic/tokens/json_web_token.rb', line 150

def audience
  data['aud']
end

#available?Boolean

rubocop:enable Metrics/ParameterLists, Metrics/LineLength

Returns:

  • (Boolean)


83
84
85
# File 'lib/apiphobic/tokens/json_web_token.rb', line 83

def available?
  not_before <= (Time.now.to_i + configuration.default_availability_leeway_in_seconds)
end

#blank?Boolean

Returns:

  • (Boolean)


87
88
89
# File 'lib/apiphobic/tokens/json_web_token.rb', line 87

def blank?
  data.empty?
end

#empty?Boolean

Returns:

  • (Boolean)


95
96
97
# File 'lib/apiphobic/tokens/json_web_token.rb', line 95

def empty?
  data.empty?
end

#expirationObject



162
163
164
# File 'lib/apiphobic/tokens/json_web_token.rb', line 162

def expiration
  data['exp']
end

#expiration_dateObject



166
167
168
# File 'lib/apiphobic/tokens/json_web_token.rb', line 166

def expiration_date
  Time.at(expiration)
end

#expired?Boolean

Returns:

  • (Boolean)


99
100
101
# File 'lib/apiphobic/tokens/json_web_token.rb', line 99

def expired?
  expiration <= (Time.now.to_i - configuration.default_expiration_leeway_in_seconds)
end

#future_issuance?Boolean

Returns:

  • (Boolean)


103
104
105
# File 'lib/apiphobic/tokens/json_web_token.rb', line 103

def future_issuance?
  issued_at > Time.now.to_f
end

#idObject



170
171
172
# File 'lib/apiphobic/tokens/json_web_token.rb', line 170

def id
  data['jti']
end

#issued_atObject



154
155
156
# File 'lib/apiphobic/tokens/json_web_token.rb', line 154

def issued_at
  data['iat']
end

#issuerObject



158
159
160
# File 'lib/apiphobic/tokens/json_web_token.rb', line 158

def issuer
  data['iss']
end

#not_beforeObject



174
175
176
# File 'lib/apiphobic/tokens/json_web_token.rb', line 174

def not_before
  data['nbf']
end

#not_before_dateObject



178
179
180
# File 'lib/apiphobic/tokens/json_web_token.rb', line 178

def not_before_date
  Time.at(not_before)
end

#owner_idObject



182
183
184
# File 'lib/apiphobic/tokens/json_web_token.rb', line 182

def owner_id
  data['own']
end

#present?Boolean

Returns:

  • (Boolean)


91
92
93
# File 'lib/apiphobic/tokens/json_web_token.rb', line 91

def present?
  data.any?
end

#rolesObject



194
195
196
# File 'lib/apiphobic/tokens/json_web_token.rb', line 194

def roles
  @roles ||= data.fetch('rol', '').split(',')
end

#subjectObject



190
191
192
# File 'lib/apiphobic/tokens/json_web_token.rb', line 190

def subject
  data['sub']
end

#subject_idObject



186
187
188
# File 'lib/apiphobic/tokens/json_web_token.rb', line 186

def subject_id
  data['sid']
end

#to_hObject



198
199
200
# File 'lib/apiphobic/tokens/json_web_token.rb', line 198

def to_h
  [data, headers]
end

#to_jweObject



218
219
220
# File 'lib/apiphobic/tokens/json_web_token.rb', line 218

def to_jwe
  @to_jwe ||= to_jws.encrypt(private_key, 'RSA-OAEP', 'A256GCM')
end

#to_jwe_sObject



222
223
224
# File 'lib/apiphobic/tokens/json_web_token.rb', line 222

def to_jwe_s
  @to_jwe_s ||= to_jwe.to_s
end

#to_jwsObject



210
211
212
# File 'lib/apiphobic/tokens/json_web_token.rb', line 210

def to_jws
  @to_jws ||= to_jwt.sign(private_key, 'RS256')
end

#to_jws_sObject



214
215
216
# File 'lib/apiphobic/tokens/json_web_token.rb', line 214

def to_jws_s
  @to_jws_s ||= to_jws.to_s
end

#to_jwtObject



202
203
204
# File 'lib/apiphobic/tokens/json_web_token.rb', line 202

def to_jwt
  @to_jwt ||= JSON::JWT.new(data)
end

#to_jwt_sObject



206
207
208
# File 'lib/apiphobic/tokens/json_web_token.rb', line 206

def to_jwt_s
  @to_jwt_s ||= to_jwt.to_s
end

#valid?Boolean

Returns:

  • (Boolean)


107
108
109
110
111
# File 'lib/apiphobic/tokens/json_web_token.rb', line 107

def valid?
  validate!
rescue Erratum::Errors::InvalidToken
  false
end

#valid_audience?Boolean

Returns:

  • (Boolean)


113
114
115
116
# File 'lib/apiphobic/tokens/json_web_token.rb', line 113

def valid_audience?
  configuration.available_audiences.empty? ||
  configuration.available_audiences.include?(audience)
end

#valid_id?Boolean

Returns:

  • (Boolean)


118
119
120
# File 'lib/apiphobic/tokens/json_web_token.rb', line 118

def valid_id?
  id =~ /[a-f0-9]{8}\-[a-f0-9]{4}\-[a-f0-9]{4}\-[a-f0-9]{4}\-[a-f0-9]{12}/i
end

#valid_issuer?Boolean

Returns:

  • (Boolean)


122
123
124
125
# File 'lib/apiphobic/tokens/json_web_token.rb', line 122

def valid_issuer?
  configuration.available_issuers.empty? ||
  configuration.available_issuers.include?(issuer)
end

#valid_role?Boolean

Returns:

  • (Boolean)


127
128
129
130
131
# File 'lib/apiphobic/tokens/json_web_token.rb', line 127

def valid_role?
  roles.empty?                         ||
  configuration.available_roles.empty? ||
  (configuration.available_roles & roles).any?
end

#valid_subject?Boolean

Returns:

  • (Boolean)


133
134
135
136
# File 'lib/apiphobic/tokens/json_web_token.rb', line 133

def valid_subject?
  configuration.available_subjects.empty? ||
  configuration.available_subjects.include?(subject)
end

#validate!Object



138
139
140
141
142
143
144
145
146
147
148
# File 'lib/apiphobic/tokens/json_web_token.rb', line 138

def validate!
  validate_id!
  validate_availability!
  validate_expiration!
  validate_issuance!
  validate_issuer!
  validate_role!
  validate_subject!

  true
end