Class: Rack::JWTAuthMiddleware

Inherits:
Object
  • Object
show all
Defined in:
lib/rack-jwt-token-auth.rb

Instance Method Summary collapse

Constructor Details

#initialize(app, &decoder) ⇒ JWTAuthMiddleware

Returns a new instance of JWTAuthMiddleware.



5
6
7
# File 'lib/rack-jwt-token-auth.rb', line 5

def initialize(app, &decoder)
  @app, @decoder = app, decoder
end

Instance Method Details

#call(env) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/rack-jwt-token-auth.rb', line 9

def call(env)
  begin
    if env['HTTP_AUTHORIZATION']
      token = env['HTTP_AUTHORIZATION'].match(/JWT token="(.+)"/)[1]
      env['user'] = @decoder.call(token)
    end
  rescue JWT::DecodeError => error
    body = {message: error.message}.to_json

    headers = {
      'Content-Type' => 'application/json',
      'Content-Length' => body.bytesize.to_s
    }

    return [401, headers, [body]]
  end

  @app.call(env)
end