Class: Daidan::Middleware::JwtAuthentication

Inherits:
Object
  • Object
show all
Defined in:
lib/daidan/middleware/jwt_authentication.rb

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ JwtAuthentication

Returns a new instance of JwtAuthentication.



4
5
6
# File 'lib/daidan/middleware/jwt_authentication.rb', line 4

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/daidan/middleware/jwt_authentication.rb', line 8

def call(env)
  auth_header = env['HTTP_AUTHORIZATION']

  if auth_header && auth_header.start_with?('Bearer ')
    token = auth_header.split(' ').last
    begin
      payload, = JWT.decode(
        token,
        ENV['JWT_SECRET'],
        true,
        algorithm: 'HS256'
      )

      env['current_user_id'] = payload['user_id']
    rescue JWT::ExpiredSignature
      env['current_user_id'] = nil
    rescue JWT::DecodeError
      env['current_user_id'] = nil
    end
  else
    env['current_user_id'] = nil
  end

  @app.call(env)
end