summaryrefslogtreecommitdiff
path: root/app/controllers/jira_connect/events_controller.rb
blob: 76ac15f7631d46dbd74795973e0b530c238fc898 (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
52
53
54
55
# frozen_string_literal: true

class JiraConnect::EventsController < JiraConnect::ApplicationController
  # See https://developer.atlassian.com/cloud/jira/software/app-descriptor/#lifecycle

  skip_before_action :verify_atlassian_jwt!
  before_action :verify_asymmetric_atlassian_jwt!, if: :signed_install_active?

  before_action :verify_atlassian_jwt!, only: :uninstalled, unless: :signed_install_active?
  before_action :verify_qsh_claim!, only: :uninstalled, unless: :signed_install_active?

  def installed
    return head :ok if !signed_install_active? && atlassian_jwt_valid?

    return head :ok if current_jira_installation

    installation = JiraConnectInstallation.new(event_params)

    if installation.save
      head :ok
    else
      head :unprocessable_entity
    end
  end

  def uninstalled
    if JiraConnectInstallations::DestroyService.execute(current_jira_installation, jira_connect_base_path, jira_connect_events_uninstalled_path)
      head :ok
    else
      head :unprocessable_entity
    end
  end

  private

  def event_params
    params.permit(:clientKey, :sharedSecret, :baseUrl).transform_keys(&:underscore)
  end

  def verify_asymmetric_atlassian_jwt!
    asymmetric_jwt = Atlassian::JiraConnect::AsymmetricJwt.new(auth_token, jwt_verification_claims)

    return head :unauthorized unless asymmetric_jwt.valid?

    @current_jira_installation = JiraConnectInstallation.find_by_client_key(asymmetric_jwt.iss_claim)
  end

  def jwt_verification_claims
    {
      aud: jira_connect_base_url(protocol: 'https'),
      iss: event_params[:client_key],
      qsh: Atlassian::Jwt.create_query_string_hash(request.url, request.method, jira_connect_base_url)
    }
  end
end