-
Notifications
You must be signed in to change notification settings - Fork 6
/
app.rb
100 lines (79 loc) · 2.06 KB
/
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
# frozen_string_literal: true
require 'sinatra'
require 'sinatra/contrib'
require_relative 'config/sentry'
# Main app class
class Application < Sinatra::Base
# NOTE: Сonnect sentry only if there is a special setting
use Sentry::Rack::CaptureExceptions if sentry?
register Sinatra::Namespace
set :host_authorization, { permitted_hosts: [] }
AUTH_TOKEN = Settings.auth_token
AUTH_DIGEST_TOKEN = Settings.auth_digest_token
namespace '/api' do # rubocop:disable Metrics/BlockLength
before do
content_type :json
authorize_resource
@controller = ClientsController.new
end
get '/clients' do
controller.index
end
get '/clients/:id' do
config = controller.show(params['id'])
case params['format']
when 'qr'
content_type 'image/png'
send_file Utils::QrCodeBuilder.build(config)
when 'conf'
content_type 'text/plain'
Utils::ConfigFileBuilder.build(config)
else
config
end
rescue Errors::ConfigNotFoundError
halt 404
end
delete '/clients/:id' do
controller.destroy(params['id'])
rescue Errors::ConfigNotFoundError
halt 404
end
patch '/clients/:id' do
controller.update(params['id'], request_body)
rescue Errors::ConfigNotFoundError
halt 404
rescue JSON::Schema::ValidationError => e
halt 400, { error: e }.to_json
end
post '/clients' do
status 201
controller.create(request_body)
end
end
get '/healthz' do
{
status: :ok,
version: instance_versions
}.to_json
end
private
attr_reader :controller
def authorize_resource
token = request.env['HTTP_AUTHORIZATION']
halt 403 unless token
if AUTH_DIGEST_TOKEN
halt 403 unless Digest::SHA256.hexdigest(token[7..]) == AUTH_DIGEST_TOKEN
else
halt 403 unless token[7..] == AUTH_TOKEN
end
end
def instance_versions
File.read('VERSION').gsub('v', '').gsub("\n", '')
end
def request_body
JSON.parse(request.body.read)
rescue JSON::ParserError
{}
end
end