From 8e015c5cd2ab19e0340a2745ab2b15ff677739c9 Mon Sep 17 00:00:00 2001 From: Cool Fire Date: Mon, 20 Jan 2020 01:35:55 +0100 Subject: [PATCH] Add some support for slack/mattermost compatible webhooks --- Gemfile | 2 ++ Gemfile.lock | 2 +- config.ru | 4 +++- config.yaml | 3 +++ nanoapi_app.rb | 24 ++++++++++++++++++++++++ 5 files changed, 33 insertions(+), 2 deletions(-) diff --git a/Gemfile b/Gemfile index c6fbb05..4af3879 100644 --- a/Gemfile +++ b/Gemfile @@ -1,2 +1,4 @@ +# frozen_string_literal: true + source 'https://rubygems.org' gem 'sinatra' diff --git a/Gemfile.lock b/Gemfile.lock index 737d831..a9ded45 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -19,4 +19,4 @@ DEPENDENCIES sinatra BUNDLED WITH - 1.14.6 + 2.1.4 diff --git a/config.ru b/config.ru index 4a022b7..3f6fa7c 100644 --- a/config.ru +++ b/config.ru @@ -1,3 +1,5 @@ -require File.expand_path '../nanoapi_app.rb', __FILE__ +# frozen_string_literal: true + +require File.expand_path 'nanoapi_app.rb', __dir__ run Sinatra::Application diff --git a/config.yaml b/config.yaml index 4c9f70d..55a70a1 100644 --- a/config.yaml +++ b/config.yaml @@ -1,2 +1,5 @@ --- key: foobar +webhook_keys: + - foobar_key + - barfoo_key diff --git a/nanoapi_app.rb b/nanoapi_app.rb index aa513f6..e838152 100644 --- a/nanoapi_app.rb +++ b/nanoapi_app.rb @@ -1,4 +1,5 @@ # frozen_string_literal: true + require 'json' require 'sinatra' require 'socket' @@ -9,6 +10,11 @@ def check_key(key) halt 401 if key != config['key'] end +def check_webhook_key(key) + config = YAML.load_file 'config.yaml' + halt 401 unless config['webhook_keys'].include? key +end + def forward_message(message) sock = TCPSocket.open 'localhost', 2000 sock.puts message @@ -30,3 +36,21 @@ post '/v1/message' do 'Message accepted' end + +post '/v1/webhook/:webhook_key' do + check_webhook_key params[:webhook_key] + + halt 400 unless params.key? :payload + + payload = JSON.parse(params[:payload]) + halt 400 unless payload.key? 'text' + + payload['channel'] = '#shells' unless payload.key? 'channel' + payload['username'] = 'webhook' unless payload.key? 'username' + + forward_message({ + dest: payload['channel'], + message: "#{payload['username']}: #{params['text']}" + }.to_json) + 'OK' +end -- GitLab