Class: SimpleJwtAuth::Middleware::Grape::Jwt

Inherits:
Grape::Middleware::Base
  • Object
show all
Defined in:
lib/simple_jwt_auth/middleware/grape/jwt.rb

Constant Summary collapse

ENV_AUTH_KEY =
'HTTP_AUTHORIZATION'
ENV_PAYLOAD_KEY =
'grape_jwt.payload'

Instance Method Summary collapse

Constructor Details

#initialize(app, options = nil) ⇒ Jwt

Returns a new instance of Jwt.



10
11
12
# File 'lib/simple_jwt_auth/middleware/grape/jwt.rb', line 10

def initialize(app, options = nil)
  super(app, **(options || {}))
end

Instance Method Details

#call(env) ⇒ Object

rubocop:disable Metrics/AbcSize, Metrics/MethodLength



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/simple_jwt_auth/middleware/grape/jwt.rb', line 15

def call(env)
  return app.call(env) if test_env?(env)

  token = env.fetch(ENV_AUTH_KEY, '').split.last

  begin
    payload, _header = SimpleJwtAuth::Decode.new(token).call
    env[ENV_PAYLOAD_KEY] = payload

    logger.debug "Authorized request, JWT payload: #{payload}"

    app.call(env)
  rescue SimpleJwtAuth::Errors::Forbidden => e
    logger.warn "JWT issuer forbidden: #{e.message}"
    rack_response(403, e.message)
  rescue SimpleJwtAuth::Errors::IssuerError => e
    logger.warn "JWT issuer error: #{e.message}"
    rack_response(400, e.message)
  rescue JWT::DecodeError => e
    logger.warn "Unauthorized request, JWT error: #{e.message}"
    rack_response(401, e.message)
  end
end