Class: JWTea::Kettle

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

Instance Method Summary collapse

Constructor Details

#initialize(secret:, store:, algorithm: nil, expires_in: nil) ⇒ Kettle

Returns a new instance of Kettle.



9
10
11
12
13
14
# File 'lib/jw_tea/kettle.rb', line 9

def initialize(secret:, store:, algorithm: nil, expires_in: nil)
  @secret = secret
  @store = store
  @algorithm = algorithm || ::JWTea.configuration.default_algorithm
  @expires_in = (expires_in || ::JWTea.configuration.default_expires_in).to_i
end

Instance Method Details

#brew(data) ⇒ Object



16
17
18
19
20
21
# File 'lib/jw_tea/kettle.rb', line 16

def brew(data)
  exp = @expires_in.seconds.from_now.to_i
  token = ::JWTea::Token.build(data, exp, @secret, @algorithm)
  @store.save(token.jti, token.exp, @expires_in)
  token
end

#decode(encoded_token) ⇒ Object



38
39
40
41
# File 'lib/jw_tea/kettle.rb', line 38

def decode(encoded_token)
  token = pour(encoded_token)
  token.data
end

#encode(data) ⇒ Object



33
34
35
36
# File 'lib/jw_tea/kettle.rb', line 33

def encode(data)
  token = brew(data)
  token.encoded
end

#inspectObject

Prevent sentitive data from being accidentally logged to console



54
55
56
# File 'lib/jw_tea/kettle.rb', line 54

def inspect
  "#<#{self.class} expires_in: #{@expires_in}, store: #{@store}>"
end

#pour(encoded_token) ⇒ Object



23
24
25
26
27
28
29
30
31
# File 'lib/jw_tea/kettle.rb', line 23

def pour(encoded_token)
  with_token(encoded_token) do |token|
    raise ::JWTea::InvalidToken.new('token revoked') unless token_exists?(token)

    token
  end
rescue ::JWT::DecodeError => e
  raise ::JWTea::InvalidToken.new(e.message)
end

#revoke(encoded_token) ⇒ Object



43
44
45
# File 'lib/jw_tea/kettle.rb', line 43

def revoke(encoded_token)
  with_token(encoded_token) { |token| @store.delete(token.jti) }
end

#to_hObject

Prevent sentitive data from being accidentally rendered to json



59
60
61
# File 'lib/jw_tea/kettle.rb', line 59

def to_h
  { expires_in: @expires_in }.freeze
end

#valid?(encoded_token) ⇒ Boolean

Returns:

  • (Boolean)


47
48
49
50
51
# File 'lib/jw_tea/kettle.rb', line 47

def valid?(encoded_token)
  with_token(encoded_token) { |token| token_exists?(token) }
rescue JWT::DecodeError
  false
end