Class: RubyAPI::Plugins::JWT

Inherits:
RubyAPI::Plugin show all
Defined in:
lib/fastrb/plugins/jwt.rb

Class Method Summary collapse

Methods inherited from RubyAPI::Plugin

inherited, option, options, plugin_name, register_cli, register_routes

Class Method Details

.decode(token) ⇒ Object



14
15
16
17
18
19
20
21
# File 'lib/fastrb/plugins/jwt.rb', line 14

def self.decode(token)
  secret = options[:secret]
  algorithm = options[:algorithm]
  payload, _header = ::JWT.decode(token, secret, true, algorithm: algorithm)
  payload
rescue StandardError
  nil
end

.encode(payload) ⇒ Object



23
24
25
26
27
# File 'lib/fastrb/plugins/jwt.rb', line 23

def self.encode(payload)
  secret = options[:secret]
  algorithm = options[:algorithm]
  ::JWT.encode(payload, secret, algorithm)
end

.on_load(app) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
# File 'lib/fastrb/plugins/jwt.rb', line 29

def self.on_load(app)
  app.before do |ctx|
    header_value = ctx.request.get_header("HTTP_AUTHORIZATION")
    next unless header_value

    prefix = options[:prefix]
    token = header_value.sub(/\A#{Regexp.escape(prefix)}/, "")
    payload = decode(token)
    ctx.set(:jwt_payload, payload) if payload
  end
end