summaryrefslogtreecommitdiff
path: root/lib/api/integrations/jira_connect/subscriptions.rb
blob: a6e931ba7bb9ab672b50d626facf1c28708c5c8f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# frozen_string_literal: true

module API
  class Integrations
    module JiraConnect
      class Subscriptions < ::API::Base
        feature_category :integrations

        before { authenticate! }

        namespace :integrations do
          namespace :jira_connect do
            resource :subscriptions do
              desc 'Subscribe a namespace to a JiraConnectInstallation'
              params do
                requires :jwt, type: String, desc: 'JWT token for authorization with the Jira Connect installation'
                requires :namespace_path, type: String, desc: 'Path for the namespace that should be subscribed'
              end
              post do
                not_found! unless Feature.enabled?(:jira_connect_oauth, current_user)

                jwt = Atlassian::JiraConnect::Jwt::Symmetric.new(params[:jwt])
                installation = JiraConnectInstallation.find_by_client_key(jwt.iss_claim)

                if !installation || !jwt.valid?(installation.shared_secret) || !jwt.verify_context_qsh_claim
                  unauthorized!('JWT authentication failed')
                end

                jira_user = installation.client.user_info(jwt.sub_claim)

                result = ::JiraConnectSubscriptions::CreateService.new(
                  installation,
                  current_user,
                  namespace_path: params['namespace_path'],
                  jira_user: jira_user
                ).execute

                if result[:status] == :success
                  status :created
                  { success: true }
                else
                  render_api_error!(result[:message], result[:http_status])
                end
              end
            end
          end
        end
      end
    end
  end
end