Class: HaveAPI::Server

Inherits:
Object
  • Object
show all
Includes:
Hookable
Defined in:
lib/haveapi/server.rb

Defined Under Namespace

Modules: DocHelpers, ServerHelpers

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Hookable

included

Constructor Details

#initialize(module_name = HaveAPI.module_name) ⇒ Server

Returns a new instance of Server.



219
220
221
222
223
224
225
226
# File 'lib/haveapi/server.rb', line 219

def initialize(module_name = HaveAPI.module_name)
  @module_name = module_name
  @allowed_headers = ['Content-Type']
  @auth_chain = HaveAPI::Authentication::Chain.new(self)
  @extensions = []
  @action_state_auth = :backend
  @validation_error_http_status = nil
end

Instance Attribute Details

#action_stateObject

Returns the value of attribute action_state.



9
10
11
# File 'lib/haveapi/server.rb', line 9

def action_state
  @action_state
end

#action_state_authObject

Returns the value of attribute action_state_auth.



10
11
12
# File 'lib/haveapi/server.rb', line 10

def action_state_auth
  @action_state_auth
end

#auth_chainObject (readonly)

Returns the value of attribute auth_chain.



10
11
12
# File 'lib/haveapi/server.rb', line 10

def auth_chain
  @auth_chain
end

#default_versionObject

Returns the value of attribute default_version.



9
10
11
# File 'lib/haveapi/server.rb', line 9

def default_version
  @default_version
end

#extensionsObject (readonly)

Returns the value of attribute extensions.



10
11
12
# File 'lib/haveapi/server.rb', line 10

def extensions
  @extensions
end

#module_nameObject (readonly)

Returns the value of attribute module_name.



10
11
12
# File 'lib/haveapi/server.rb', line 10

def module_name
  @module_name
end

#rootObject (readonly)

Returns the value of attribute root.



10
11
12
# File 'lib/haveapi/server.rb', line 10

def root
  @root
end

#routesObject (readonly)

Returns the value of attribute routes.



10
11
12
# File 'lib/haveapi/server.rb', line 10

def routes
  @routes
end

#validation_error_http_statusObject

Returns the value of attribute validation_error_http_status.



9
10
11
# File 'lib/haveapi/server.rb', line 9

def validation_error_http_status
  @validation_error_http_status
end

#versionsObject (readonly)

Returns the value of attribute versions.



10
11
12
# File 'lib/haveapi/server.rb', line 10

def versions
  @versions
end

Instance Method Details

#action_state_auth_required?(route) ⇒ Boolean

Returns:



699
700
701
702
703
704
# File 'lib/haveapi/server.rb', line 699

def action_state_auth_required?(route)
  return false unless route.action.resource == HaveAPI::Resources::ActionState
  return false if @auth_chain.empty?

  @action_state_auth == :required
end

#add_auth_module(v, name, mod, prefix: '', global: false) ⇒ Object



717
718
719
720
721
722
723
# File 'lib/haveapi/server.rb', line 717

def add_auth_module(v, name, mod, prefix: '', global: false)
  @routes[v] ||= { authentication: { name => { resources: {} } } }

  HaveAPI.get_version_resources(mod, v).each do |r|
    mount_resource("#{auth_prefix(v, prefix, global:)}/", v, r, @routes[v][:authentication][name][:resources])
  end
end

#add_auth_routes(v, provider, prefix: '', global: false) ⇒ Object

Parameters:



713
714
715
# File 'lib/haveapi/server.rb', line 713

def add_auth_routes(v, provider, prefix: '', global: false)
  provider.register_routes(@sinatra, auth_prefix(v, prefix, global:))
end

#allow_header(name) ⇒ Object



755
756
757
758
# File 'lib/haveapi/server.rb', line 755

def allow_header(name)
  @allowed_headers << name unless @allowed_headers.include?(name)
  @allowed_headers_str = nil
end

#allowed_headersObject



760
761
762
763
764
# File 'lib/haveapi/server.rb', line 760

def allowed_headers
  return @allowed_headers_str if @allowed_headers_str

  @allowed_headers_str = @allowed_headers.join(',')
end

#appObject



766
767
768
# File 'lib/haveapi/server.rb', line 766

def app
  @sinatra
end

#auth_prefix(v, prefix, global:) ⇒ Object



725
726
727
728
# File 'lib/haveapi/server.rb', line 725

def auth_prefix(v, prefix, global:)
  root = global ? "#{@root}_auth" : "#{version_prefix(v)}_auth"
  "#{root}/#{prefix}"
end

#describe(context) ⇒ Object



641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
# File 'lib/haveapi/server.rb', line 641

def describe(context)
  original_user = context.current_user
  auth_users_by_version = context.auth_users_by_version
  authenticated_description = auth_users_by_version&.values&.any?

  ret = { default_version: @default_version, versions: {} }

  context.version = @default_version
  context.current_user = auth_users_by_version ? auth_users_by_version[@default_version] : original_user
  ret[:versions][:default] = describe_version(context) unless authenticated_description && context.current_user.nil?

  @versions.each do |v|
    user = auth_users_by_version ? auth_users_by_version[v] : original_user
    next if authenticated_description && user.nil?

    context.version = v
    context.current_user = user
    ret[:versions][v] = describe_version(context)
  end

  ret
ensure
  context.current_user = original_user
end

#describe_resource(r, hash, context) ⇒ Object



688
689
690
# File 'lib/haveapi/server.rb', line 688

def describe_resource(r, hash, context)
  r.describe(hash, context)
end

#describe_version(context) ⇒ Object



666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
# File 'lib/haveapi/server.rb', line 666

def describe_version(context)
  ret = {
    authentication: @auth_chain.describe(context),
    resources: {},
    meta: Metadata.describe,
    help: version_prefix(context.version)
  }

  # puts JSON.pretty_generate(@routes)

  @routes[context.version][:resources].each do |resource, children|
    r_name = resource.resource_name.underscore
    r_desc = describe_resource(resource, children, context)

    unless r_desc[:actions].empty? && r_desc[:resources].empty?
      ret[:resources][r_name] = r_desc
    end
  end

  ret
end

#json_content_type?(request) ⇒ Boolean

Returns:



730
731
732
733
734
735
736
737
738
# File 'lib/haveapi/server.rb', line 730

def json_content_type?(request)
  media_type = if request.respond_to?(:media_type)
                 request.media_type
               else
                 request.content_type.to_s.split(';').first
               end

  media_type == 'application/json' || media_type.to_s.end_with?('+json')
end

#mount(prefix = '/') ⇒ Object

Load routes for all resource from included API versions. All routes are mounted under prefix ‘path`. If no default version is set, the last included version is used.



264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
# File 'lib/haveapi/server.rb', line 264

def mount(prefix = '/')
  @root = prefix

  @sinatra = Sinatra.new do
    # Preload template engine for .md -- without this, tilt will not search
    # for markdown files with extension .md, only .markdown
    Tilt[:md]

    set :views, "#{settings.root}/views"
    set :public_folder, "#{settings.root}/public"
    set :bind, '0.0.0.0'

    if settings.development?
      set :dump_errors, true
      set :raise_errors, true
      set :show_exceptions, false
    end

    helpers Sinatra::Cookies
    helpers ServerHelpers
    helpers DocHelpers

    before do
      if request.env['HTTP_ORIGIN']
        headers 'access-control-allow-origin' => '*',
                'access-control-allow-credentials' => 'false'
      end
    end

    not_found do
      setup_formatter
      report_error(404, {}, 'Action not found') unless @halted
    end

    after do
      if Object.const_defined?(:ActiveRecord)
        ActiveRecord::Base.connection_handler.clear_active_connections!
      end
    end
  end

  @sinatra.set(:api_server, self)

  @routes = {}
  @default_version ||= @versions.last

  # Mount root
  @sinatra.get @root do
    auth_users_by_version = authenticated_versions

    @api = settings.api_server.describe(Context.new(
                                          settings.api_server,
                                          user: auth_users_by_version[settings.api_server.default_version],
                                          params:,
                                          auth_users_by_version:
                                        ))

    content_type 'text/html'
    erb :index, layout: :main_layout
  end

  @sinatra.options @root do
    setup_formatter
    access_control
    ret = nil

    ret = case params[:describe]
          when 'versions'
            {
              versions: settings.api_server.versions,
              default: settings.api_server.default_version
            }

          when 'default'
            auth_users_by_version = authenticated_versions

            settings.api_server.describe_version(Context.new(
                                                   settings.api_server,
                                                   version: settings.api_server.default_version,
                                                   user: auth_users_by_version[settings.api_server.default_version],
                                                   doc: true,
                                                   params:,
                                                   auth_users_by_version:
                                                 ))

          else
            auth_users_by_version = authenticated_versions

            settings.api_server.describe(Context.new(
                                           settings.api_server,
                                           user: auth_users_by_version[settings.api_server.default_version],
                                           doc: true,
                                           params:,
                                           auth_users_by_version:
                                         ))
          end

    @formatter.format(true, ret)
  end

  # Doc
  @sinatra.get "#{@root}doc" do
    content_type 'text/html'
    erb :main_layout do
      doc(:index)
    end
  end

  @sinatra.get "#{@root}doc/readme" do
    content_type 'text/html'

    erb :main_layout do
      markdown File.new("#{settings.views}/../../../README.md").read
    end
  end

  @sinatra.get "#{@root}doc/json-schema" do
    content_type 'text/html'
    erb :doc_layout, layout: :main_layout do
      @content = File.read(File.join(settings.root, '../../doc/json-schema.html'))
      @sidebar = erb :'doc_sidebars/json-schema'
    end
  end

  @sinatra.get %r{#{@root}doc/([^.]+)(\.md)?} do |f, _|
    content_type 'text/html'
    erb :doc_layout, layout: :main_layout do
      begin
        @content = doc(f)
      rescue Errno::ENOENT
        halt 404
      end

      begin
        @sidebar = erb :"doc_sidebars/#{f}"
      rescue Errno::ENOENT
        @sidebar = ''
      end
    end
  end

  # Login/logout links
  @sinatra.get "#{root}_login" do
    if current_user
      redirect back
    else
      authenticate!(settings.api_server.default_version) # FIXME
    end
  end

  @sinatra.get "#{root}_logout" do
    require_auth!
  end

  @auth_chain << HaveAPI.default_authenticate if @auth_chain.empty?
  @auth_chain.setup(@versions)

  @extensions.each { |e| e.enabled(self) }

  call_hooks_for(:pre_mount, args: [self, @sinatra])

  # Mount default version first
  mount_version(@root, @default_version)

  @versions.each do |v|
    mount_version(version_prefix(v), v)
  end

  call_hooks_for(:post_mount, args: [self, @sinatra])
end

#mount_action(v, route) ⇒ Object



529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
# File 'lib/haveapi/server.rb', line 529

def mount_action(v, route)
  @sinatra.method(route.http_method).call(route.sinatra_path) do
    setup_formatter

    if route.action.auth || settings.api_server.action_state_auth_required?(route)
      authenticate!(v)
    else
      authenticated?(v)
    end

    raw_body = request.body.read
    body_method = !%i[get head options].include?(route.http_method.to_sym)

    if body_method && !raw_body.empty? && !settings.api_server.send(:json_content_type?, request)
      report_error(415, {}, 'Unsupported Content-Type')
    end

    begin
      body = raw_body.empty? ? nil : JSON.parse(raw_body)
    rescue JSON::ParserError
      report_error(400, {}, 'Bad JSON syntax')
    end

    if !raw_body.empty? && !body.is_a?(Hash)
      report_error(400, {}, 'JSON body must be an object')
    end

    action_params = settings.api_server.send(:path_params, route, params)
    action_input = body_method ? (body || {}) : request.GET

    context = Context.new(
      settings.api_server,
      version: v,
      request: self,
      action: route.action,
      path: route.path,
      path_params: action_params,
      input: action_input,
      user: current_user,
      endpoint: true,
      resource_path: route.resource_path
    )

    action = route.action.new(request, v, action_params, action_input, context)

    unless action.authorized?(current_user)
      report_error(403, {}, 'Access denied. Insufficient permissions.')
    end

    status, reply, errors, http_status = action.safe_exec
    @halted = true

    [
      http_status || 200,
      @formatter.format(
        status,
        status ? reply : nil,
        status ? nil : reply,
        errors,
        version: false
      )
    ]
  end

  @sinatra.options route.sinatra_path do |*args|
    setup_formatter
    access_control
    route_method = route.http_method.to_s.upcase

    pass if params[:method] && params[:method] != route_method

    if route.action.auth || settings.api_server.action_state_auth_required?(route)
      authenticate!(v)
    else
      authenticated?(v)
    end

    ctx = Context.new(
      settings.api_server,
      version: v,
      request: self,
      action: route.action,
      path: route.path,
      args:,
      params:,
      user: current_user,
      endpoint: true,
      resource_path: route.resource_path,
      doc: true
    )

    begin
      desc = route.action.describe(ctx)

      unless desc
        report_error(403, {}, 'Access denied. Insufficient permissions.')
      end
    rescue ValidationError => e
      report_error(400, e.to_hash, e.message)
    rescue StandardError => e
      tmp = settings.api_server.call_hooks_for(:description_exception, args: [ctx, e])
      report_error(
        tmp[:http_status] || 500,
        {},
        tmp[:message] || 'Server error occured'
      )
    end

    @formatter.format(true, desc)
  end
end

#mount_nested_resource(v, routes) ⇒ Object



513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
# File 'lib/haveapi/server.rb', line 513

def mount_nested_resource(v, routes)
  ret = { resources: {}, actions: {} }

  routes.each do |route|
    if route.is_a?(Hash)
      ret[:resources][route.keys.first] = mount_nested_resource(v, route.values.first)

    else
      ret[:actions][route.action] = route.path
      mount_action(v, route)
    end
  end

  ret
end

#mount_resource(prefix, v, resource, hash) ⇒ Object



496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
# File 'lib/haveapi/server.rb', line 496

def mount_resource(prefix, v, resource, hash)
  hash[resource] = { resources: {}, actions: {} }

  resource.routes(prefix).each do |route|
    if route.is_a?(Hash)
      hash[resource][:resources][route.keys.first] = mount_nested_resource(
        v,
        route.values.first
      )

    else
      hash[resource][:actions][route.action] = route.path
      mount_action(v, route)
    end
  end
end

#mount_version(prefix, v) ⇒ Object



435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
# File 'lib/haveapi/server.rb', line 435

def mount_version(prefix, v)
  @routes[v] ||= {}
  @routes[v][:resources] = {}

  @sinatra.get prefix do
    authenticated?(v)

    @v = v
    @help = settings.api_server.describe_version(Context.new(
                                                   settings.api_server,
                                                   version: v,
                                                   user: current_user,
                                                   params:
                                                 ))

    content_type 'text/html'
    erb :doc_layout, layout: :main_layout do
      @content = erb :version_page
      @sidebar = erb :version_sidebar
    end
  end

  @sinatra.options prefix do
    setup_formatter
    access_control
    authenticated?(v)

    @formatter.format(true, settings.api_server.describe_version(Context.new(
                                                                   settings.api_server,
                                                                   version: v,
                                                                   user: current_user,
                                                                   doc: true,
                                                                   params:
                                                                 )))
  end

  # Register blocking resource
  HaveAPI.get_version_resources(@module_name, v).each do |resource|
    mount_resource(prefix, v, resource, @routes[v][:resources])
  end

  if action_state
    mount_resource(
      prefix,
      v,
      HaveAPI::Resources::ActionState,
      @routes[v][:resources]
    )
  end

  validate_resources(@routes[v][:resources])
end

#path_for_action(version, action) ⇒ Object



692
693
694
695
696
697
# File 'lib/haveapi/server.rb', line 692

def path_for_action(version, action)
  routes = @routes && @routes[version]
  return unless routes

  find_action_path(routes[:resources], action)
end

#path_params(route, params) ⇒ Object



740
741
742
743
744
745
746
747
748
749
750
751
752
753
# File 'lib/haveapi/server.rb', line 740

def path_params(route, params)
  route.action.path_param_names(route.path).each_with_object({}) do |name, ret|
    value = if params.has_key?(name.to_sym)
              params[name.to_sym]
            elsif params.has_key?(name)
              params[name]
            end

    next if value.nil?

    ret[name] = value
    ret[name.to_sym] = value
  end
end

#start!Object



770
771
772
# File 'lib/haveapi/server.rb', line 770

def start!
  @sinatra.run!
end

#use_version(v, default: false) ⇒ Object

Include specific version ‘v` of API.

‘default` is set only when including concrete version. Use set_default_version otherwise.

Parameters:

  • v (:all, Array<String>, String)


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

def use_version(v, default: false)
  @versions ||= []

  if v == :all
    @versions = HaveAPI.versions(@module_name)
  elsif v.is_a?(Array)
    @versions += v
    @versions.uniq!
  else
    @versions << v
    @default_version = v if default
  end
end

#validate_resources(resources) ⇒ Object



488
489
490
491
492
493
494
# File 'lib/haveapi/server.rb', line 488

def validate_resources(resources)
  resources.each_value do |r|
    r[:actions].each_key(&:validate_build)

    validate_resources(r[:resources])
  end
end

#version_prefix(v) ⇒ Object



706
707
708
# File 'lib/haveapi/server.rb', line 706

def version_prefix(v)
  "#{@root}v#{v}/"
end