Class: KeycloakAdmin::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/keycloak-admin/client/client.rb

Instance Method Summary collapse

Constructor Details

#initialize(configuration) ⇒ Client

Returns a new instance of Client.



6
7
8
# File 'lib/keycloak-admin/client/client.rb', line 6

def initialize(configuration)
  @configuration = configuration
end

Instance Method Details

#create_payload(value) ⇒ Object



53
54
55
56
57
58
59
60
61
# File 'lib/keycloak-admin/client/client.rb', line 53

def create_payload(value)
  if value.nil?
    ""
  elsif value.kind_of?(Array)
    "[#{value.map(&:to_json) * ","}]"
  else
    value.to_json
  end
end

#created_id(response) ⇒ Object



45
46
47
48
49
50
51
# File 'lib/keycloak-admin/client/client.rb', line 45

def created_id(response)
  unless response.status == 201
    raise UnexpectedResponseError.new(response.status, response.reason_phrase)
  end
  (_head, _separator, id) = response.headers[:location].rpartition("/")
  id
end

#current_tokenObject

Cached on @configuration, not on this instance, since a new Client subclass is created for nearly every call (e.g. KeycloakAdmin.realm(x).users creates a fresh UserClient) - caching here alone would fetch a new token on almost every request.



17
18
19
# File 'lib/keycloak-admin/client/client.rb', line 17

def current_token
  @configuration.cached_token || @configuration.cache_token(fetch_token)
end

#execute_httpObject



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/keycloak-admin/client/client.rb', line 29

def execute_http
  replayed = false
  begin
    yield
  rescue Faraday::TimeoutError
    raise
  rescue Faraday::ClientError, Faraday::ServerError => e
    if !replayed && e.response && e.response[:status] == 401 && !@configuration.cached_token.nil?
      @configuration.clear_cached_token!
      replayed = true
      retry
    end
    raise ApiError.from_response(e.response)
  end
end

#headersObject



21
22
23
24
25
26
27
# File 'lib/keycloak-admin/client/client.rb', line 21

def headers
  {
    Authorization: "Bearer #{current_token.access_token}",
    content_type: :json,
    accept:       :json
  }
end

#server_urlObject



10
11
12
# File 'lib/keycloak-admin/client/client.rb', line 10

def server_url
  @configuration.server_url&.sub(/\/+\z/, "")
end