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.



308
309
310
311
312
313
314
315
316
317
318
# File 'lib/haveapi/server.rb', line 308

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
  @default_locale = :en
  self.available_locales = HaveAPI::I18n.available_locales
  self.locale_header = 'Accept-Language'
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.



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

def action_state_auth
  @action_state_auth
end

#auth_chainObject (readonly)

Returns the value of attribute auth_chain.



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

def auth_chain
  @auth_chain
end

#available_localesObject

Returns the value of attribute available_locales.



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

def available_locales
  @available_locales
end

#default_localeObject

Returns the value of attribute default_locale.



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

def default_locale
  @default_locale
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.



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

def extensions
  @extensions
end

#locale_headerObject

Returns the value of attribute locale_header.



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

def locale_header
  @locale_header
end

#module_nameObject (readonly)

Returns the value of attribute module_name.



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

def module_name
  @module_name
end

#parameter_i18n_scopeObject

Returns the value of attribute parameter_i18n_scope.



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

def parameter_i18n_scope
  @parameter_i18n_scope
end

#rootObject (readonly)

Returns the value of attribute root.



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

def root
  @root
end

#routesObject (readonly)

Returns the value of attribute routes.



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

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.



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

def versions
  @versions
end

Instance Method Details

#action_state_auth_required?(route) ⇒ Boolean

Returns:



892
893
894
895
896
897
# File 'lib/haveapi/server.rb', line 892

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

#activate_locale(locale) ⇒ Object



330
331
332
333
# File 'lib/haveapi/server.rb', line 330

def activate_locale(locale)
  allow_i18n_locales([locale])
  ::I18n.locale = locale
end

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



910
911
912
913
914
915
916
# File 'lib/haveapi/server.rb', line 910

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:



906
907
908
# File 'lib/haveapi/server.rb', line 906

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

#allow_header(name) ⇒ Object



948
949
950
951
# File 'lib/haveapi/server.rb', line 948

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

#allow_i18n_locales(locales) ⇒ Object



335
336
337
338
339
340
341
342
343
# File 'lib/haveapi/server.rb', line 335

def allow_i18n_locales(locales)
  requested = Array(locales).compact.map { |locale| locale.to_s.to_sym }
  current = ::I18n.available_locales
  missing = requested.reject do |locale|
    current.any? { |available| available.to_s == locale.to_s }
  end

  ::I18n.available_locales = current + missing unless missing.empty?
end

#allowed_headersObject



953
954
955
956
957
# File 'lib/haveapi/server.rb', line 953

def allowed_headers
  return @allowed_headers_str if @allowed_headers_str

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

#appObject



959
960
961
# File 'lib/haveapi/server.rb', line 959

def app
  @sinatra
end

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



918
919
920
921
# File 'lib/haveapi/server.rb', line 918

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

#describe(context) ⇒ Object



827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
# File 'lib/haveapi/server.rb', line 827

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



874
875
876
# File 'lib/haveapi/server.rb', line 874

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

#describe_version(context) ⇒ Object



852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
# File 'lib/haveapi/server.rb', line 852

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:



923
924
925
926
927
928
929
930
931
# File 'lib/haveapi/server.rb', line 923

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

#locale(&block) ⇒ Object



345
346
347
348
# File 'lib/haveapi/server.rb', line 345

def locale(&block)
  @locale_resolver = block if block
  @locale_resolver
end

#locale_header_value(request) ⇒ Object



357
358
359
# File 'lib/haveapi/server.rb', line 357

def locale_header_value(request)
  request.env["HTTP_#{locale_header.to_s.upcase.tr('-', '_')}"]
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.



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
434
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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
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
# File 'lib/haveapi/server.rb', line 409

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
      setup_request_locale

      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, {}, HaveAPI.message('haveapi.errors.action_not_found')) unless @halted
    end

    error do
      report_exception(env['sinatra.error'])
    end

    after do
      restore_request_locale

      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



703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
# File 'lib/haveapi/server.rb', line 703

def mount_action(v, route)
  @sinatra.method(route.http_method).call(route.sinatra_path) do
    context = nil

    begin
      setup_formatter

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

      raw_body = request.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, {}, HaveAPI.message('haveapi.errors.unsupported_content_type'))
      end

      begin
        body = raw_body.empty? ? nil : JSON.parse(raw_body)
      rescue JSON::ParserError
        report_error(400, {}, HaveAPI.message('haveapi.errors.bad_json_syntax'))
      end

      if !raw_body.empty? && !body.is_a?(Hash)
        report_error(400, {}, HaveAPI.message('haveapi.errors.json_body_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, {}, HaveAPI.message('haveapi.authorization.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
        )
      ]
    rescue Exception => e # rubocop:disable Lint/RescueException
      report_exception(e, context)
    end
  end

  @sinatra.options route.sinatra_path do |*args|
    ctx = nil

    begin
      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, {}, HaveAPI.message('haveapi.authorization.insufficient_permissions'))
        end
      rescue ValidationError => e
        report_error(400, e.to_hash, e.message_value)
      rescue StandardError => e
        tmp = settings.api_server.call_hooks_for(:description_exception, args: [ctx, e])
        report_error(
          tmp[:http_status] || 500,
          {},
          tmp[:message] || HaveAPI.message('haveapi.errors.server_error')
        )
      end

      @formatter.format(true, desc)
    rescue Exception => e # rubocop:disable Lint/RescueException
      report_exception(e, ctx)
    end
  end
end

#mount_nested_resource(v, routes) ⇒ Object



687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
# File 'lib/haveapi/server.rb', line 687

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



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

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



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 588

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

#parameter_metadata_i18n_items(version: @default_version) ⇒ Object



878
879
880
881
882
883
# File 'lib/haveapi/server.rb', line 878

def (version: @default_version)
  routes = @routes.fetch(version)
  context = Context.new(self, version:, doc: true)

  (routes[:resources], context)
end

#path_for_action(version, action) ⇒ Object



885
886
887
888
889
890
# File 'lib/haveapi/server.rb', line 885

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



933
934
935
936
937
938
939
940
941
942
943
944
945
946
# File 'lib/haveapi/server.rb', line 933

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

#request_locale(request) ⇒ Object



350
351
352
353
354
355
# File 'lib/haveapi/server.rb', line 350

def request_locale(request)
  HaveAPI::I18n.accept_language(
    locale_header_value(request),
    available_locales
  )
end

#resolved_locale(request:, current_user:) ⇒ Object



361
362
363
364
365
366
367
368
369
370
371
# File 'lib/haveapi/server.rb', line 361

def resolved_locale(request:, current_user:)
  locale = if @locale_resolver
             @locale_resolver.call(
               request:,
               current_user:,
               default_locale:
             )
           end

  HaveAPI::I18n.normalize_locale(locale, available_locales) || default_locale
end

#start!Object



963
964
965
# File 'lib/haveapi/server.rb', line 963

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)


390
391
392
393
394
395
396
397
398
399
400
401
402
# File 'lib/haveapi/server.rb', line 390

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



641
642
643
644
645
646
647
# File 'lib/haveapi/server.rb', line 641

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



899
900
901
# File 'lib/haveapi/server.rb', line 899

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