Class: KeycloakAdmin::Client

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

Instance Method Summary collapse

Constructor Details

#initialize(configuration) ⇒ Client

Returns a new instance of Client.



8
9
10
# File 'lib/keycloak-admin/client/client.rb', line 8

def initialize(configuration)
  @configuration = configuration
end

Instance Method Details

#create_payload(value) ⇒ Object



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

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



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

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.



19
20
21
# File 'lib/keycloak-admin/client/client.rb', line 19

def current_token
  @configuration.fetch_token_once { fetch_token }
end

#execute_httpObject



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

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



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

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

#server_urlObject



12
13
14
# File 'lib/keycloak-admin/client/client.rb', line 12

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