Class: EY::GateKeeper::Client::Middleware::Authentication

Inherits:
Object
  • Object
show all
Defined in:
lib/ey_gatekeeper/client/middlewares/authentication.rb

Instance Method Summary collapse

Constructor Details

#initialize(app, key_callback, secret_callback, token_setter, impersonation_token_callback) ⇒ Authentication

Returns a new instance of Authentication.



7
8
9
10
# File 'lib/ey_gatekeeper/client/middlewares/authentication.rb', line 7

def initialize(app, key_callback, secret_callback, token_setter, impersonation_token_callback)
  @app, @key_callback, @secret_callback, @token_setter, @impersonation_token_callback =
    app, key_callback, secret_callback, token_setter, impersonation_token_callback
end

Instance Method Details

#add_impersonation_token_to(env) ⇒ Object



22
23
24
25
26
27
# File 'lib/ey_gatekeeper/client/middlewares/authentication.rb', line 22

def add_impersonation_token_to(env)
  impersonation_token = @impersonation_token_callback.call
  if impersonation_token
    env.update('HTTP_X_IMPERSONATION_TOKEN' => impersonation_token)
  end
end

#add_token_to(env) ⇒ Object



16
17
18
19
20
# File 'lib/ey_gatekeeper/client/middlewares/authentication.rb', line 16

def add_token_to(env)
  if @token
    env.update('HTTP_AUTH_TOKEN' => @token.token)
  end
end

#authenticate(env) ⇒ Object



58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/ey_gatekeeper/client/middlewares/authentication.rb', line 58

def authenticate(env)
  key = @key_callback.call
  secret = @secret_callback.call

  env.update('HTTP_AUTHORIZATION' => ["#{key}:#{secret}"].pack("m*").gsub("\n", ""))
  env.update('REQUEST_PATH' => '/_authenticate')
  env.update('PATH_INFO' => '/_authenticate')

  auth_response = EY::GateKeeper::Client::ServerResponse.new(@app.call(env))

  if auth_response.status == 200
    JSON.parse(auth_response.body.join)
  end
end

#call(env) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/ey_gatekeeper/client/middlewares/authentication.rb', line 29

def call(env)
  if need_token?
    get_token(env.dup)
  end

  add_token_to(env)
  add_impersonation_token_to(env)

  app_response = EY::GateKeeper::Client::ServerResponse.new(@app.call(env))
  return app_response unless @token

  if app_response.needs_gatekeeper_token_refresh?
    get_token(env.dup)
    add_token_to(env)
    app_response = EY::GateKeeper::Client::ServerResponse.new(@app.call(env))
  end

  app_response.to_rack
end

#get_token(env) ⇒ Object



49
50
51
52
53
54
55
56
# File 'lib/ey_gatekeeper/client/middlewares/authentication.rb', line 49

def get_token(env)
  if auth_response = authenticate(env)
    @token = EY::GateKeeper::Token.new(auth_response)
  else
    @token = nil
  end
  @token_setter.call(@token) if @token_setter
end

#need_token?Boolean

Returns:

  • (Boolean)


12
13
14
# File 'lib/ey_gatekeeper/client/middlewares/authentication.rb', line 12

def need_token?
  @token.nil? || @token.expired?
end