Class: MailRoom::JWT

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

Overview

Responsible for validating and generating JWT token

Constant Summary collapse

DEFAULT_ISSUER =
'mailroom'
DEFAULT_ALGORITHM =
'HS256'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(header:, secret_path:, issuer:, algorithm:) ⇒ JWT

Returns a new instance of JWT.



16
17
18
19
20
21
# File 'lib/mail_room/jwt.rb', line 16

def initialize(header:, secret_path:, issuer:, algorithm:)
  @header = header
  @secret_path = secret_path
  @issuer = issuer || DEFAULT_ISSUER
  @algorithm = algorithm || DEFAULT_ALGORITHM
end

Instance Attribute Details

#algorithmObject (readonly)

Returns the value of attribute algorithm.



14
15
16
# File 'lib/mail_room/jwt.rb', line 14

def algorithm
  @algorithm
end

#headerObject (readonly)

Returns the value of attribute header.



14
15
16
# File 'lib/mail_room/jwt.rb', line 14

def header
  @header
end

#issuerObject (readonly)

Returns the value of attribute issuer.



14
15
16
# File 'lib/mail_room/jwt.rb', line 14

def issuer
  @issuer
end

#secret_pathObject (readonly)

Returns the value of attribute secret_path.



14
15
16
# File 'lib/mail_room/jwt.rb', line 14

def secret_path
  @secret_path
end

Instance Method Details

#tokenObject



27
28
29
30
31
32
33
34
35
36
37
# File 'lib/mail_room/jwt.rb', line 27

def token
  return nil unless valid?

  secret = Base64.strict_decode64(File.read(@secret_path).chomp)
  payload = {
    nonce: SecureRandom.hex(12),
    iat: Time.now.to_i, # https://github.com/jwt/ruby-jwt#issued-at-claim
    iss: @issuer
  }
  ::JWT.encode payload, secret, @algorithm
end

#valid?Boolean

Returns:

  • (Boolean)


23
24
25
# File 'lib/mail_room/jwt.rb', line 23

def valid?
  [@header, @secret_path, @issuer, @algorithm].none?(&:nil?)
end