### Github Webhook Controller Setup in Rails Source: https://github.com/ssaunier/github_webhook/blob/master/README.md This Ruby code defines a controller for handling GitHub webhooks in a Rails application. It includes the GithubWebhook::Processor module and provides example methods for handling 'push' and 'create' events, along with a private method to specify the webhook secret. ```ruby # app/controllers/github_webhooks_controller.rb class GithubWebhooksController < ActionController::API include GithubWebhook::Processor # Handle push event def github_push(payload) # TODO: handle push webhook end # Handle create event def github_create(payload) # TODO: handle create webhook end private def webhook_secret(payload) ENV['GITHUB_WEBHOOK_SECRET'] end end ``` -------------------------------- ### Install Github Webhook Gem and Configure Routes Source: https://context7.com/ssaunier/github_webhook/llms.txt Add the `github_webhook` gem to your Gemfile and run `bundle install`. Then, configure a webhook route in `config/routes.rb` to handle incoming JSON requests for the GitHub webhook. ```ruby # Gemfile gem 'github_webhook', '~> 1.4' # Run bundle install # $ bundle install # config/routes.rb Rails.application.routes.draw do resource :github_webhooks, only: :create, defaults: { formats: :json } end ``` -------------------------------- ### Configure GithubWebhook Logger Source: https://context7.com/ssaunier/github_webhook/llms.txt Demonstrates how to configure the logger for GithubWebhook. It shows automatic configuration in Rails applications via Railtie and manual configuration for non-Rails environments or custom logging setups. This includes setting the logger instance and its log level. ```ruby # Automatic in Rails applications (via Railtie) # GithubWebhook.logger = Rails.logger # Manual configuration (for non-Rails or custom logging) GithubWebhook.logger = Logger.new(STDOUT) GithubWebhook.logger.level = Logger::INFO # Custom logger example GithubWebhook.logger = ActiveSupport::TaggedLogging.new( Logger.new(Rails.root.join('log', 'webhooks.log')) ) ``` -------------------------------- ### Add Github Webhook Gem to Gemfile Source: https://github.com/ssaunier/github_webhook/blob/master/README.md This snippet shows how to add the github_webhook gem to your Rails application's Gemfile for installation. It specifies the gem name and a version constraint. ```ruby gem 'github_webhook', '~> 1.4' ``` -------------------------------- ### Test GitHub Webhooks with curl Source: https://context7.com/ssaunier/github_webhook/llms.txt This section provides bash commands using `curl` to test your GitHub webhook endpoint. It includes generating an HMAC signature for the payload using `openssl` and sending POST requests with the appropriate headers, including `X-GitHub-Event` and `X-Hub-Signature-256`. Examples are shown for testing 'push' and 'pull_request' events. ```bash # Generate HMAC signature for payload SECRET="your_webhook_secret" PAYLOAD='{"action":"opened","repository":{"full_name":"myorg/myrepo"},"sender":{"login":"testuser"}}' SIGNATURE="sha256=$(echo -n "$PAYLOAD" | openssl dgst -sha256 -hmac "$SECRET" | cut -d' ' -f2)" # Send test push event curl -X POST http://localhost:3000/github_webhooks \ -H "Content-Type: application/json" \ -H "X-GitHub-Event: push" \ -H "X-Hub-Signature-256: $SIGNATURE" \ -d "$PAYLOAD" # Send test pull_request event PAYLOAD='{"action":"opened","number":1,"pull_request":{"title":"Test PR","number":1},"repository":{"full_name":"myorg/myrepo"}}' SIGNATURE="sha256=$(echo -n "$PAYLOAD" | openssl dgst -sha256 -hmac "$SECRET" | cut -d' ' -f2)" curl -X POST http://localhost:3000/github_webhooks \ -H "Content-Type: application/json" \ -H "X-GitHub-Event: pull_request" \ -H "X-Hub-Signature-256: $SIGNATURE" \ -d "$PAYLOAD" ``` -------------------------------- ### Add Webhook to GitHub Repository using Octokit Source: https://github.com/ssaunier/github_webhook/blob/master/README.md This Ruby code demonstrates how to add a webhook to a GitHub repository using the Octokit client within a Rails console. It requires the 'octokit' gem, sets up an Octokit client, and then uses the 'subscribe' method to register the webhook with a callback URL and secret. ```ruby require "octokit" client = Octokit::Client.new(:login => 'ssaunier', :password => 's3cr3t!!!') repo = "ssaunier/github_webhook" callback_url = "yourdomain.com/github_webhooks" webhook_secret = "a_gr34t_s3cr3t" # Must be set after that in ENV['GITHUB_WEBHOOK_SECRET'] # Create the WebHook client.subscribe "https://github.com/#{repo}/events/push.json", callback_url, webhook_secret ``` -------------------------------- ### Create GitHub Webhooks with Octokit Gem (Ruby) Source: https://context7.com/ssaunier/github_webhook/llms.txt This Ruby code snippet demonstrates how to programmatically create GitHub webhooks using the Octokit gem. It authenticates with GitHub using a personal access token, specifies the repository, webhook URL, content type, and secret. You can also select specific events to subscribe to and choose whether the webhook is active. Remember to store the generated webhook secret securely. ```ruby # Install octokit: gem install octokit require 'octokit' # Authenticate with GitHub (use personal access token in production) client = Octokit::Client.new(access_token: ENV['GITHUB_TOKEN']) # Create webhook for a repository repo = 'myorg/myrepo' webhook_url = 'https://myapp.com/github_webhooks' webhook_secret = SecureRandom.hex(32) # Generate secure secret # Subscribe to specific events client.create_hook( repo, 'web', { url: webhook_url, content_type: 'json', secret: webhook_secret }, { events: ['push', 'pull_request', 'issues', 'release'], active: true } ) # Store the secret securely (e.g., in Rails credentials or environment) # ENV['GITHUB_WEBHOOK_SECRET'] = webhook_secret # List existing webhooks hooks = client.hooks(repo) hooks.each { |hook| puts "Hook #{hook.id}: #{hook.config.url}" } # Delete a webhook # client.remove_hook(repo, hook_id) ``` -------------------------------- ### Configure Github Webhook Route in Rails Source: https://github.com/ssaunier/github_webhook/blob/master/README.md This code configures the routes file in a Rails application to handle incoming GitHub webhook POST requests. It sets up a resource route for 'github_webhooks' that only accepts the 'create' action and defaults to JSON format. ```ruby # config/routes.rb resource :github_webhooks, only: :create, defaults: { formats: :json } ``` -------------------------------- ### Handle GitHub Webhook Events in Ruby Source: https://context7.com/ssaunier/github_webhook/llms.txt This Ruby code defines a controller to process various GitHub webhook events. It uses the `github_` naming convention for handler methods. The `payload` object contains event-specific data. Ensure the `GITHUB_WEBHOOK_SECRET` environment variable is set for signature verification. ```ruby class GithubWebhooksController < ActionController::API include GithubWebhook::Processor # Ping event - automatically handled, logs hook info # def github_ping(payload) - built-in # Repository events def github_create(payload) # Branch or tag created ref_type = payload[:ref_type] # "branch" or "tag" ref = payload[:ref] # branch/tag name Rails.logger.info "#{ref_type} '#{ref}' created" end def github_delete(payload) # Branch or tag deleted ref_type = payload[:ref_type] ref = payload[:ref] Rails.logger.info "#{ref_type} '#{ref}' deleted" end def github_fork(payload) # Repository forked forkee = payload[:forkee][:full_name] Rails.logger.info "Repository forked to #{forkee}" end # Code review events def github_pull_request_review(payload) review = payload[:review] pr = payload[:pull_request] state = review[:state] # approved, changes_requested, commented if state == 'approved' Rails.logger.info "PR ##{pr[:number]} approved by #{review[:user][:login]}" end end def github_pull_request_review_comment(payload) comment = payload[:comment] Rails.logger.info "Review comment: #{comment[:body]}" end # CI/CD events def github_deployment(payload) deployment = payload[:deployment] environment = deployment[:environment] Rails.logger.info "Deployment to #{environment} triggered" end def github_deployment_status(payload) status = payload[:deployment_status][:state] # pending, success, failure, error environment = payload[:deployment][:environment] Rails.logger.info "Deployment to #{environment}: #{status}" end def github_workflow_run(payload) workflow = payload[:workflow_run] conclusion = workflow[:conclusion] # success, failure, cancelled Rails.logger.info "Workflow '#{workflow[:name]}' #{conclusion}" end def github_check_run(payload) check = payload[:check_run] Rails.logger.info "Check '#{check[:name]}': #{check[:conclusion]}" end # Release events def github_release(payload) release = payload[:release] if payload[:action] == 'published' Rails.logger.info "Release #{release[:tag_name]} published" # Trigger package publishing, documentation updates, etc. end end # Security events def github_security_advisory(payload) advisory = payload[:security_advisory] Rails.logger.warn "Security advisory: #{advisory[:summary]}" end def github_dependabot_alert(payload) alert = payload[:alert] Rails.logger.warn "Dependabot alert: #{alert[:security_advisory][:summary]}" end private def webhook_secret(payload) ENV['GITHUB_WEBHOOK_SECRET'] end end ``` -------------------------------- ### Process GitHub Webhook Events in Rails Controller Source: https://context7.com/ssaunier/github_webhook/llms.txt Include `GithubWebhook::Processor` in your Rails controller to automatically verify signatures, parse payloads, and route events. Implement handler methods like `github_` to process specific GitHub events such as push, pull_request, issues, and star. ```ruby class GithubWebhooksController < ActionController::API include GithubWebhook::Processor # Handle push events (commits pushed to repository) def github_push(payload) repository = payload[:repository][:full_name] commits = payload[:commits] branch = payload[:ref].sub('refs/heads/', '') commits.each do |commit| Rails.logger.info "New commit #{commit[:id]} by #{commit[:author][:name]} on #{repository}/#{branch}" # Trigger CI/CD pipeline, notify team, update database, etc. end end # Handle pull request events def github_pull_request(payload) action = payload[:action] # opened, closed, synchronize, etc. pr = payload[:pull_request] case action when 'opened' Rails.logger.info "PR ##{pr[:number]} opened: #{pr[:title]}" # Auto-assign reviewers, run checks, etc. when 'closed' if pr[:merged] Rails.logger.info "PR ##{pr[:number]} merged by #{pr[:merged_by][:login]}" # Trigger deployment, update project board, etc. end end end # Handle issue events def github_issues(payload) action = payload[:action] issue = payload[:issue] if action == 'opened' Rails.logger.info "Issue ##{issue[:number]} created: #{issue[:title]}" # Auto-label, notify team, create ticket in project management tool end end # Handle repository star events def github_star(payload) if payload[:action] == 'created' user = payload[:sender][:login] repo = payload[:repository][:full_name] Rails.logger.info "#{user} starred #{repo}!" end end private # Required: Return the webhook secret for signature verification def webhook_secret(payload) ENV['GITHUB_WEBHOOK_SECRET'] end end ``` -------------------------------- ### Implement Webhook Secret Verification in Rails Controller Source: https://context7.com/ssaunier/github_webhook/llms.txt Implement the `webhook_secret` private method in your Rails controller to provide the secret token for HMAC-SHA256 signature verification. This method can use a single environment variable for a shared secret or dynamically determine the secret based on repository details for more advanced security. ```ruby class GithubWebhooksController < ActionController::API include GithubWebhook::Processor def github_push(payload) # Handle push event end private # Simple: Use single secret from environment variable def webhook_secret(payload) ENV['GITHUB_WEBHOOK_SECRET'] end # Advanced: Use different secrets per repository def webhook_secret(payload) repo_name = payload[:repository][:full_name] secrets = { 'myorg/frontend' => ENV['FRONTEND_WEBHOOK_SECRET'], 'myorg/backend' => ENV['BACKEND_WEBHOOK_SECRET'], 'myorg/infrastructure' => ENV['INFRA_WEBHOOK_SECRET'] } secrets[repo_name] || ENV['DEFAULT_WEBHOOK_SECRET'] end end ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.