8000 added github app by czhu12 · Pull Request #141 · czhu12/canine · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

added github app #141

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions app/actions/providers/create_or_update_github_app_provider.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
class Providers::CreateOrUpdateGithubAppProvider
extend LightService::Action

expects :current_user, :installation_id
promises :provider

executed do |context|
installation = Github::App::Client.new.installation_exists?(context.installation_id)
context.provider = context.current_user.providers.where(provider: Provider::GITHUB_APP_PROVIDER).find do |p|
JSON.parse(p.auth)["installation_id"] == context.installation_id
end
if context.provider.nil?
context.provider = Provider.new(
user: context.current_user,
provider: Provider::GITHUB_APP_PROVIDER,
)
end
context.provider.assign_attributes(
access_token: context.installation_id,
auth: {
info: {
username: installation.account.login
},
installation_id: context.installation_id
}.to_json
)
context.provider.save!
end
end
18 changes: 18 additions & 0 deletions app/controllers/inbound_webhooks/github_app_controller.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
module InboundWebhooks
class GithubAppController < ApplicationController
def create
Rails.logger.info(params.to_json)
end

def callback
signed_id = params[:state]
user = GlobalID::Locator.locate_signed(signed_id)
raise StandardError, "User not found" unless user.present?
Providers::CreateOrUpdateGithubAppProvider.execute(
current_user: user,
installation_id: params[:installation_id],
)
redirect_to new_project_path, notice: "GitHub App was successfully connected."
end
end
end
14 changes: 8 additions & 6 deletions app/controllers/integrations/github/repositories_controller.rb
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
class Integrations::Github::RepositoriesController < ApplicationController
def index
client = Octokit::Client.new(access_token: current_account.github_provider.access_token)
if params[:q].present?
client.auto_paginate = true
@repositories = client.repos(current_account.github_username)
# Preference the github provider
provider = current_user.providers.where(provider: [ Provider::GITHUB_PROVIDER, Provider::GITHUB_APP_PROVIDER ]).first

client = Octokit::Client.new(bearer_token: provider.access_token)

10000 if provider.github?
@repositories = client.repos(provider.username)
@repositories = @repositories.select { |repo| repo.full_name.downcase.include?(params[:q].downcase) }
else
page = params[:page] || 1
@repositories = client.repos(current_account.github_username, page:)
@repositories = client.list_app_installation_repositories[:repositories]
end

respond_to do |format|
Expand Down
6 changes: 5 additions & 1 deletion app/controllers/projects_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,11 @@ def project_params

def set_provider
@selected_provider = params[:provider] || Provider::GITHUB_PROVIDER
@providers = current_user.providers.where(provider: @selected_provider)
if @selected_provider == Provider::GITHUB_PROVIDER
@providers = current_user.providers.where(provider: [ Provider::GITHUB_PROVIDER, Provider::GITHUB_APP_PROVIDER ])
else
@providers = current_user.providers.where(provider: @selected_provider)
end
# Temporary hack
@provider = @providers.first
end
Expand Down
20 changes: 20 additions & 0 deletions app/javascript/controllers/github_install_controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
connect() {
this.element.addEventListener('click', this.handleClick.bind(this))
}

handleClick(event) {
event.preventDefault()
const url = this.element.href
const popup = window.open(url, 'github-install', 'width=800,height=600')

const checkPopup = setInterval(() => {
if (popup.closed) {
clearInterval(checkPopup)
window.location.reload()
}
}, 1000)
}
}
5 changes: 5 additions & 0 deletions app/jobs/inbound_webhooks/github_app_job.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
class InboundWebhooks::GithubAppJob < ApplicationJob
def perform(inbound_webhook)
# TODO: Implement the job
end
end
29 changes: 28 additions & 1 deletion app/models/provider.rb
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ class Provider < ApplicationRecord
attr_accessor :username_param
GITHUB_PROVIDER = "github"
DOCKER_HUB_PROVIDER = "docker_hub"
AVAILABLE_PROVIDERS = [ GITHUB_PROVIDER, DOCKER_HUB_PROVIDER ].freeze
GITHUB_APP_PROVIDER = "github_app"
AVAILABLE_PROVIDERS = [ GITHUB_PROVIDER, DOCKER_HUB_PROVIDER, GITHUB_APP_PROVIDER ].freeze

belongs_to :user

Expand Down Expand Up @@ -77,9 +78,35 @@ def github?
provider == GITHUB_PROVIDER
end

def github_app?
provider == GITHUB_APP_PROVIDER
end

def access_token
if github_app?
@_app_client ||= Github::App::Client.create_client_for_installation(JSON.parse(auth)["installation_id"])
@_app_client.bearer_token
else
super
end
end

def github_app?
provider == GITHUB_APP_PROVIDER
end

def twitter_refresh_token!(token); end

def used!
update!(last_used_at: Time.current)
end

def access_token
if github_app?
@_app_client ||= Github::App::Client.create_client_for_installation(JSON.parse(auth)["installation_id"])
@_app_client.bearer_token
else
super
end
end
end
52 changes: 52 additions & 0 deletions app/services/github/app/client.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
class Github::App::Client
CLOCK_DRIFT_SECONDS = 60
JWT_EXPIRATION_SECONDS = 10.minutes.to_i
JWT_ALGORITHM = "RS256"

GITHUB_APP_ID = ENV['GITHUB_APP_ID']
GITHUB_APP_NAME = ENV['GITHUB_APP_NAME']
GITHUB_APP_CLIENT_ID = ENV['GITHUB_APP_CLIENT_ID']
GITHUB_APP_PEM = ENV['GITHUB_APP_PEM']

def self.update_installation_url(installation_id)
"https://github.com/settings/installations/#{installation_id}"
end

def self.install_url_for_user(user)
signed_id = user.to_sgid(expires_in: 10.minutes).to_s
F438 "https://github.com/apps/#{GITHUB_APP_NAME}/installations/new?state=#{signed_id}"
end

def self.create_client_for_installation(installation_id)
app_client = new
installation_client = Octokit::Client.new(bearer_token: app_client.jwt)
token = installation_client.create_app_installation_access_token(installation_id)[:token]
Octokit::Client.new(bearer_token: token)
end

def jwt
JWT.encode(jwt_payload, private_key, JWT_ALGORITHM)
end

def installation_exists?(installation_id)
client = Octokit::Client.new(bearer_token: jwt)
client.installation(installation_id)
rescue Octokit::NotFound
false
end

private

def jwt_payload
current_time = Time.now.to_i
{
iat: current_time - CLOCK_DRIFT_SECONDS,
exp: current_time + JWT_EXPIRATION_SECONDS,
iss: GITHUB_APP_CLIENT_ID
}
end

def private_key
OpenSSL::PKey::RSA.new(GITHUB_APP_PEM.split('\n').join("\n"))
end
end
4 changes: 2 additions & 2 deletions app/views/integrations/github/repositories/_index.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@
class="border-b border-b-gray-500 flex justify-between items-center px-4 py-2"
data-github-select-repository-target="repositories"
>
<span><%= repo.full_name %></span>
<span><%= repo[:full_name] %></span>
<button
type="button"
class="btn btn-outline btn-sm"
data-action="github-select-repository#selectRepository"
data-repository-name="<%= repo.full_name %>">Connect</button>
data-repository-name="<%= repo[:full_name] %>">Connect</button>
</li>
<% end %>
21 changes: 12 additions & 9 deletions app/views/integrations/github/repositories/_modal.html.erb
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
<turbo-frame id="github-repositories-frame">
<dialog aria-label="Modal" class="modal" id="github-repositories-modal" data-github-select-repository-target="modal">
<div class="modal-box px-6 py-0 w-11/12 max-w-5xl bg-base-200">
<div class="modal-box px-6 pb-12 w-11/12 max-w-5xl bg-base-200">
<div class="modal-action">
<button type="button" data-action="github-select-repository#closeModal" class="btn btn-sm btn-circle btn-ghost absolute right-2 top-2">✕</button>
</div>
<div class="p-2">
<h2 class="text-2xl font-bold mb-4">Select Repository</h2>
<p class="mb-6">Select the repo you would like to back this service, or use an existing public repository's URL.</p>
<p class="mb-6">Select the repo you would like to back this service.</p>

<div class="rounded-lg">
<div class="mb-4">
Expand All @@ -22,13 +22,16 @@
</ul>
</div>

<div class="mt-6 p-4 rounded-lg">
<h3 class="text-lg font-semibold mb-2">Public Git Repository</h3>
<p class="mb-4">Use a public repository by entering the URL below. Features like PR Previews and Auto-Deploy are not available if the repository has not been configured for Render.</p>
<div class="flex gap-4">
<input type="text" placeholder="czhu12/whiteboarder" data-github-select-repository-target="publicRepository" class="input input-bordered w-full mb-4" />
<button type="button" data-action="github-select-repository#selectPublicRepository" class="btn btn-outline">Continue</button>
</div>
<div class="mt-6 p-4 rounded-lg flex flex-row gap-2 items-center">
<h3 class="text-lg inline font-semibold mb-2">Not seeing your repository?</h3>
<%= link_to(
Github::App::Client.install_url_for_user(current_user),
class: "btn btn-sm btn-outline ml-4",
data: { turbo: false, disable_with: t(".redirecting") },
) do %>
<iconify-icon icon="mdi:github" width="24" height="24"></iconify-icon>
Connect to Github
<% end %>
</div>
</div>
</div>
Expand Down
14 changes: 8 additions & 6 deletions app/views/projects/create/_missing_github_credentials.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@
<h1 class="text-2xl font-bold">Missing Credentials for Github</h1>
<p class="mt-2 text-gray-400">Please provide your Github credentials to continue.</p>
<div class="flex flex-row gap-4">
<div role="tooltip" data-tip="This feature is coming soon!" class="tooltip">
<%= link_to user_github_omniauth_authorize_path, class: "mt-6 btn btn-primary", disabled: true, data: { turbo: false, disable_with: t(".redirecting") } do %>
<iconify-icon icon="mdi:github" width="24" height="24"></iconify-icon>
Connect to Github
<% end %>
</div>
<%= link_to(
Github::App::Client.install_url_for_user(current_user),
class: "mt-6 btn btn-primary",
data: { turbo: false, disable_with: t(".redirecting") },
) do %>
<iconify-icon icon="mdi:github" width="24" height="24"></iconify-icon>
Connect to Github
<% end %>
<%= link_to "Manually Add Credentials", providers_path, class: "mt-6 btn btn-ghost", data: { turbo: false } %>
</div>
<div class="mt-6">
Expand Down
7 changes: 6 additions & 1 deletion config/routes.rb
BEA9
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,12 @@
end
end
namespace :inbound_webhooks do
resources :github, controller: :github, only: [ :create ]
resources :github, only: [ :create ]
resources :github_app, only: [ :create ] do
collection do
get :callback
end
end
end
get "/privacy", to: "static#privacy"
get "/terms", to: "static#terms"
Expand Down
21 changes: 21 additions & 0 deletions spec/actions/providers/create_github_app_provider_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
require 'rails_helper'

RSpec.describe Providers::CreateGithubAppProvider do
describe '.execute' do
let(:current_user) { create(:user) }
let(:installation_id) { '12345' }
let(:context) do
{
current_user: current_user,
installation_id: installation_id
}
end

it 'stores the installation_id in the auth JSON' do
result = described_class.execute(context)
auth_data = JSON.parse(result.provider.auth)

expect(auth_data['installation_id']).to eq(installation_id)
end
end
end
Loading
Loading
0