forked from seven1m/do-install-button
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.rb
100 lines (88 loc) · 2.53 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
require 'bundler/setup'
require 'sinatra'
require 'haml'
require 'rest_client'
require 'json'
require 'yaml'
require 'pry'
require './installer'
config = YAML.load(File.read('config.yml'))
CALLBACK_URL = "#{config['this_host']}/auth/callback"
SIGN_UP_URL = "https://www.digitalocean.com/?refcode=#{config['ref_code']}"
CLIENT_ID = config['client_id']
CLIENT_SECRET = config['client_secret']
enable :sessions, :logging
enable :show_exceptions if development?
set :session_secret, config['cookie_secret']
get '/' do
@configured = config['client_id'] != 'your-do-client-id'
haml :index
end
get '/terms' do
haml :terms
end
get '/install' do
begin
@installer = Installer.new(params[:url])
rescue Installer::URLParseError
haml :error_parsing_url
rescue Installer::ConfigFetchError
haml :error_getting_config
rescue Installer::ConfigParseError
haml :error_parsing_config
else
haml :install
end
end
post '/install' do
begin
installer = Installer.new(params[:url])
rescue
haml :error_generic
else
installer.region = params[:region]
installer.size = params[:size]
session[:config] = installer.as_json
if installer.auth_token = session[:token]
begin
installer.go!
rescue RestClient::Unauthorized
session[:token] = nil
redirect "https://cloud.digitalocean.com/v1/oauth/authorize?response_type=code&client_id=#{CLIENT_ID}&redirect_uri=#{CALLBACK_URL}&scope=read+write"
else
session[:config] = installer.as_json
redirect '/status'
end
else
redirect "https://cloud.digitalocean.com/v1/oauth/authorize?response_type=code&client_id=#{CLIENT_ID}&redirect_uri=#{CALLBACK_URL}&scope=read+write"
end
end
end
get '/auth/callback' do
result = RestClient.post 'https://cloud.digitalocean.com/v1/oauth/token',
{ client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
grant_type: 'authorization_code',
code: params[:code],
redirect_uri: CALLBACK_URL }
session[:token] = JSON.parse(result)['access_token']
installer = Installer.from_json(session[:config])
installer.auth_token = session[:token]
installer.go!
session[:config] = installer.as_json
redirect '/status'
end
get '/status' do
haml :status
end
get '/status.json' do
installer = Installer.from_json(session[:config])
installer.auth_token = session[:token]
status = {
id: installer.droplet_id,
ip: installer.droplet_ip,
status: installer.droplet_status
}
content_type :json
status.to_json
end