-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.ru
59 lines (47 loc) · 1.47 KB
/
config.ru
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
56
57
58
59
require 'json'
require 'rack'
require 'dotenv'
require_relative 'lib/devto_publisher'
# Загружаем переменные окружения из .env файла
Dotenv.load
class WebhookServer
def initialize
@secret = ENV['WEBHOOK_SECRET']
@publisher = DevtoPublisher::Client.new
unless @secret
puts "Error: Please set WEBHOOK_SECRET environment variable"
exit 1
end
end
def call(env)
request = Rack::Request.new(env)
# Check request method
return error_response(405, "Method not allowed") unless request.post?
# Validate secret key
secret_header = request.env['HTTP_X_SECRET']
return error_response(401, "Invalid secret key") unless valid_secret?(secret_header)
# Read and validate request body
begin
body = request.body.read
payload = JSON.parse(body)
rescue JSON::ParserError
return error_response(400, "Invalid JSON format")
end
# Post article to dev.to
begin
result = @publisher.create_article(payload)
[200, { 'content-type' => 'application/json' }, [result.to_json]]
rescue DevtoPublisher::Error => e
error_response(500, e.message)
end
end
private
def valid_secret?(header_secret)
return false unless header_secret
Rack::Utils.secure_compare(@secret, header_secret)
end
def error_response(status, message)
[status, { 'content-type' => 'application/json' }, [{ error: message, status: 500 }.to_json]]
end
end
run WebhookServer.new