forked from anhnk/SupportBee-Apps
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrun_app.rb
120 lines (101 loc) · 2.67 KB
/
run_app.rb
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
require 'sinatra/base'
require 'sinatra-initializers'
class RunApp < Sinatra::Base
register Sinatra::Initializers
unless PLATFORM_ENV == 'production'
enable :logging
enable :dump_errors
enable :show_exceptions
end
before do
return if PLATFORM_ENV == 'development'
x_supportbee_key = request.env['HTTP_X_SUPPORTBEE_KEY'] ? request.env['HTTP_X_SUPPORTBEE_KEY'] : ''
return if x_supportbee_key == SECRET_CONFIG['key']
halt 403, {'Content-Type' => 'application/json'}, '{"error" : "Access forbidden"}'
end
def self.setup(app_class)
get "/#{app_class.slug}" do
content_type :json
{app_class.slug => app_class.api_hash}.to_json
end
get "/#{app_class.slug}/schema" do
response = app_class.schema
content_type :json
{app_class.slug => response}.to_json
end
get "/#{app_class.slug}/config" do
response = app_class.configuration
content_type :json
{app_class.slug => response}.to_json
end
post "/#{app_class.slug}/valid" do
data, payload = parse_request
response = {}
app = app_class.new(data, payload)
if app.valid?
status 200
else
status 400
response = app.errors
end
content_type :json
{ errors: response }.to_json
end
post "/#{app_class.slug}/event/:event" do
data, payload = parse_request
event = params[:event]
if app_class.trigger_event(event, data, payload)
status 204
else
status 500
end
end
post "/#{app_class.slug}/action/:action" do
data, payload = parse_request
action = params[:action]
begin
result = app_class.trigger_action(action, data, payload)
status result[0]
body result[1] if result[1]
rescue Exception => e
puts "#{e.message} \n #{e.backtrace}"
status 500
end
end
unless PLATFORM_ENV == 'production'
get "/#{app_class.slug}/console" do
@app_name = app_class.name
@app_slug = app_class.slug
@schema = app_class.schema
@config = app_class.configuration
haml :console
end
end
end
SupportBeeApp::Base.apps.each do |app|
app.setup_for(self)
end
get "/" do
apps = {}
SupportBeeApp::Base.apps.each do |app|
next if app.access == 'test'
apps[app.slug] = app.api_hash
end
content_type :json
{:apps => apps}.to_json
end
def parse_request
parse_json_request
end
def parse_json_request
req = JSON.parse(request.body.read)
[req['data'], req['payload']]
end
def self.logger
LOGGER
end
def logger
self.class.logger
end
run! if app_file == $0
end