Module: HaveAPI::Server::ServerHelpers

Defined in:
lib/haveapi/server.rb

Instance Method Summary collapse

Instance Method Details

#access_control ⇒ Object



170
171
172
173
174
175
176
177
178
179
180
# File 'lib/haveapi/server.rb', line 170

def access_control
  return unless request.env['HTTP_ORIGIN'] && request.env['HTTP_ACCESS_CONTROL_REQUEST_METHOD']

  halt 200, {
    'access-control-allow-origin' => '*',
    'access-control-allow-methods' => 'GET,POST,OPTIONS,PATCH,PUT,DELETE',
    'access-control-allow-credentials' => 'false',
    'access-control-allow-headers' => settings.api_server.allowed_headers,
    'access-control-max-age' => (60 * 60).to_s
  }, ''
end

#add_vary_header(name) ⇒ Object



106
107
108
109
110
# File 'lib/haveapi/server.rb', line 106

def add_vary_header(name)
  values = response['Vary'].to_s.split(/\s*,\s*/).reject(&:empty?)
  values << name unless values.include?(name)
  headers 'Vary' => values.join(', ')
end

#api_version ⇒ Object



324
325
326
# File 'lib/haveapi/server.rb', line 324

def api_version
  @v
end

#authenticate!(v) ⇒ Object



129
130
131
# File 'lib/haveapi/server.rb', line 129

def authenticate!(v)
  require_auth! unless authenticated?(v)
end

#authenticated?(v) ⇒ Boolean

Returns:



133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/haveapi/server.rb', line 133

def authenticated?(v)
  if @current_user
    resolve_request_locale
    return @current_user
  end

  begin
    @current_user = settings.api_server.send(:do_authenticate, v, request)
  rescue HaveAPI::Authentication::TokenConflict => e
    unless @formatter
      @formatter = OutputFormatter.new
      @formatter.supports?([])
    end

    report_error(400, {}, e.message)
  end
  settings.api_server.call_hooks_for(:post_authenticated, args: [@current_user])
  resolve_request_locale
  @current_user
end

#authenticated_versions ⇒ Object



154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
# File 'lib/haveapi/server.rb', line 154

def authenticated_versions
  ret = settings.api_server.versions.each_with_object({}) do |v, users|
    users[v] = settings.api_server.send(:do_authenticate, v, request)
  rescue HaveAPI::Authentication::TokenConflict => e
    unless @formatter
      @formatter = OutputFormatter.new
      @formatter.supports?([])
    end

    report_error(400, {}, e.message)
  end

  resolve_request_locale(ret[settings.api_server.default_version] || ret.values.compact.first)
  ret
end

#base_url ⇒ Object



246
247
248
249
250
251
252
253
254
255
# File 'lib/haveapi/server.rb', line 246

def base_url
  scheme = if request.env['HTTP_X_FORWARDED_SSL'] == 'on'
             'https'

           else
             request.env['rack.url_scheme']
           end

  "#{scheme}://#{request.env['HTTP_HOST']}"
end

#current_user ⇒ Object



182
183
184
# File 'lib/haveapi/server.rb', line 182

def current_user
  @current_user
end

#doc(file) ⇒ Object



240
241
242
243
244
# File 'lib/haveapi/server.rb', line 240

def doc(file)
  path = documentation_article_path(file)
  shared_documentation_links(markdown(File.read(path), with_toc_data: true, tables: true,
                                                       fenced_code_blocks: true, lax_spacing: true))
end

#documentation_clients ⇒ Object



279
280
281
282
# File 'lib/haveapi/server.rb', line 279

def documentation_clients
  # The server's @documentation_clients owns profiles, not this request list.
  @documentation_available_clients ||= HaveAPI::ClientExample.clients.select { |client| client.available?(documentation_context(client)) } # rubocop:disable Naming/MemoizedInstanceVariableName
end

#documentation_context(client = nil, **changes) ⇒ Object



257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
# File 'lib/haveapi/server.rb', line 257

def documentation_context(client = nil, **changes)
  @documentation_context ||= HaveAPI::ClientExample::Context.new(
    version: @v, host:, base_url: "#{base_url}#{root.end_with?('/') ? root : "#{root}/"}",
    version_url: "#{base_url}#{root.end_with?('/') ? root : "#{root}/"}v#{@v}/",
    description: @help, locale: documentation_locale
  )
  profile = if client
              settings.api_server.documentation_client_profiles(@v)[client.code&.to_sym]
            end
  parent = @documentation_context
  # Snapshot each selected resource once in this request, before client
  # profile/detail derivation, and share it across that resource's panels.
  if changes[:resource] && changes[:resource_path]
    resource = changes.delete(:resource)
    path = changes.delete(:resource_path).map { |part| part.to_s.dup.freeze }.freeze
    @documentation_resource_contexts ||= {}
    key = [resource.__id__, path]
    parent = @documentation_resource_contexts[key] ||= parent.with(resource_path: path, resource:)
  end
  parent.with(profile:, **changes)
end

#documentation_example_variants(kind, auth_method: nil, auth_description: nil, **changes) ⇒ Object



291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
# File 'lib/haveapi/server.rb', line 291

def documentation_example_variants(kind, auth_method: nil, auth_description: nil, **changes)
  documentation_clients.flat_map do |client|
    context = documentation_context(client, **changes, detail: :simple)
    simple = client.render(kind, context:, auth_method:, auth_description:)
    next [] unless simple

    levels = client.detail_levels_for(kind, context:, result: simple, auth_method:, auth_description:)
    unless [[:simple], %i[simple thorough]].include?(levels)
      raise ArgumentError, 'Invalid documentation example detail levels'
    end

    variants = levels.filter_map do |detail|
      result = detail == :simple ? simple : client.render(kind, context: context.with(detail:), auth_method:, auth_description:)
      [client, detail, result] if result
    end
    @documentation_page_details ||= {}
    @documentation_page_details[client.id] = (@documentation_page_details.fetch(client.id, []) | variants.map { |_client, detail, _result| detail })
    variants
  end
end

#documentation_panels(kind, auth_method: nil, auth_description: nil, **changes) ⇒ Object



284
285
286
287
288
289
# File 'lib/haveapi/server.rb', line 284

def documentation_panels(kind, auth_method: nil, auth_description: nil, **changes)
  documentation_clients.filter_map do |client|
    result = client.render(kind, context: documentation_context(client, **changes), auth_method:, auth_description:)
    [client, result] if result
  end
end

#host ⇒ Object



312
313
314
# File 'lib/haveapi/server.rb', line 312

def host
  request.env['HTTP_HOST'].split(':').first
end

#pretty_format(obj) ⇒ Object



186
187
188
189
# File 'lib/haveapi/server.rb', line 186

def pretty_format(obj)
  ret = ''
  PP.pp(obj, ret)
end

#report_error(code, headers, msg) ⇒ Object



199
200
201
202
203
204
205
206
207
208
# File 'lib/haveapi/server.rb', line 199

def report_error(code, headers, msg)
  @halted = true
  unless @formatter
    @formatter = OutputFormatter.new
    @formatter.supports?([])
  end

  content_type @formatter.content_type, charset: 'utf-8'
  halt code, headers, @formatter.format(false, nil, msg, version: false)
end

#report_exception(exception, context = nil) ⇒ Object



210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
# File 'lib/haveapi/server.rb', line 210

def report_exception(exception, context = nil)
  context ||= Context.new(
    settings.api_server,
    request: self,
    params:,
    endpoint: true
  )

  tmp =
    begin
      settings.api_server.call_hooks_for(
        :request_exception,
        args: [context, exception]
      )
    rescue StandardError => e
      warn "HaveAPI request exception hook failed: #{e.class}: #{e.message}"
      {}
    end

  report_error(
    tmp[:http_status] || 500,
    {},
    tmp[:message] || HaveAPI.message('haveapi.errors.server_error')
  )
end

#require_auth! ⇒ Object



191
192
193
194
195
196
197
# File 'lib/haveapi/server.rb', line 191

def require_auth!
  report_error(
    401,
    { 'www-authenticate' => 'Basic realm="Restricted Area"' },
    HaveAPI.message('haveapi.authentication.required')
  )
end

#resolve_request_locale(user = current_user) ⇒ Object



89
90
91
92
93
94
95
96
97
98
# File 'lib/haveapi/server.rb', line 89

def resolve_request_locale(user = current_user)
  setup_request_locale
  return @haveapi_locale if @haveapi_locale_requested

  @haveapi_locale = settings.api_server.resolved_locale(
    request:,
    current_user: user
  )
  settings.api_server.activate_locale(@haveapi_locale)
end

#restore_request_locale ⇒ Object



100
101
102
103
104
# File 'lib/haveapi/server.rb', line 100

def restore_request_locale
  return unless @haveapi_locale_setup

  settings.api_server.activate_locale(@haveapi_previous_locale)
end

#root ⇒ Object



236
237
238
# File 'lib/haveapi/server.rb', line 236

def root
  settings.api_server.root
end

#setup_formatter ⇒ Object



112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
# File 'lib/haveapi/server.rb', line 112

def setup_formatter
  return if @formatter

  @formatter = OutputFormatter.new
  accept = request.accept
rescue ArgumentError, EncodingError
  @formatter.supports?([])
  report_error(400, {}, HaveAPI.message('haveapi.errors.bad_accept_header'))
else
  unless @formatter.supports?(accept)
    @halted = true
    halt 406, "Not Acceptable\n"
  end

  content_type @formatter.content_type, charset: 'utf-8'
end

#setup_request_locale ⇒ Object



68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/haveapi/server.rb', line 68

def setup_request_locale
  return if @haveapi_locale_setup

  server = settings.api_server
  @haveapi_previous_locale = ::I18n.locale
  locale_header_value = server.locale_header_value(request)
  @haveapi_locale_requested = !locale_header_value.nil?
  @haveapi_explicit_locale = server.request_locale(request)
  @haveapi_locale = if @haveapi_locale_requested
                      @haveapi_explicit_locale || server.default_locale
                    else
                      server.resolved_locale(
                        request:,
                        current_user: nil
                      )
                    end
  server.activate_locale(@haveapi_locale)
  add_vary_header(server.locale_header) if server.locale_header
  @haveapi_locale_setup = true
end

#sort_hash(hash) ⇒ Object



320
321
322
# File 'lib/haveapi/server.rb', line 320

def sort_hash(hash)
  hash.sort { |a, b| a[0] <=> b[0] }
end

#urlescape(v) ⇒ Object



316
317
318
# File 'lib/haveapi/server.rb', line 316

def urlescape(v)
  CGI.escape(v)
end

#version ⇒ Object



328
329
330
# File 'lib/haveapi/server.rb', line 328

def version
  HaveAPI::VERSION
end