-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.rb
More file actions
232 lines (185 loc) · 6.56 KB
/
Copy pathapp.rb
File metadata and controls
232 lines (185 loc) · 6.56 KB
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
# frozen_string_literal: true
require "sinatra"
require "sinatra/reloader" if development?
require "dotenv/load"
require "faraday"
require "json"
require "securerandom"
require "uri"
# ---------------------------------------------------------------------------
# Config
# ---------------------------------------------------------------------------
SUPERCAST_ENV = ENV.fetch("SUPERCAST_ENV", "development")
BASE_URLS = {
"production" => "https://app.supercast.tech",
"development" => "https://app.supercast.test",
}.freeze
BASE_URL = BASE_URLS.fetch(SUPERCAST_ENV) { abort "Unknown SUPERCAST_ENV: #{SUPERCAST_ENV}" }
CLIENT_ID = ENV.fetch("SUPERCAST_CLIENT_ID") { abort "SUPERCAST_CLIENT_ID is not set" }
CLIENT_SECRET = ENV.fetch("SUPERCAST_CLIENT_SECRET") { abort "SUPERCAST_CLIENT_SECRET is not set" }
REDIRECT_URI = ENV.fetch("REDIRECT_URI", "http://localhost:4000/auth/callback")
# ---------------------------------------------------------------------------
# Sinatra settings
# ---------------------------------------------------------------------------
configure do
set :port, ENV.fetch("PORT", 4000).to_i
set :bind, "localhost"
set :views, File.join(__dir__, "views")
enable :sessions
set :session_secret, ENV.fetch("SESSION_SECRET", SecureRandom.hex(32))
end
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
helpers do
def authenticated?
!!session[:access_token]
end
def token_expired?
return false unless session[:token_expires_at]
Time.now.to_i >= session[:token_expires_at]
end
def store_tokens(token_data)
session[:access_token] = token_data["access_token"]
session[:refresh_token] = token_data["refresh_token"]
if (expires_in = token_data["expires_in"])
session[:token_expires_at] = Time.now.to_i + expires_in.to_i - 60
end
end
def refresh_token!
return false unless session[:refresh_token]
response = supercast.post("/oauth/token") do |req|
req.body = URI.encode_www_form(
grant_type: "refresh_token",
refresh_token: session[:refresh_token],
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET
)
end
return false unless response.success?
store_tokens(JSON.parse(response.body))
true
end
def api_call(endpoint, params = {})
if token_expired?
unless refresh_token!
return { error: "Access token expired. Please re-authorize.", status: 401 }
end
end
response = supercast.get("/api/v1#{endpoint}") do |req|
req.headers["Authorization"] = "Bearer #{session[:access_token]}"
req.params = params.reject { |_, v| v.nil? || v.to_s.strip.empty? }
end
{ status: response.status, data: JSON.parse(response.body), ok: response.success? }
rescue => e
{ error: e.message, status: 0 }
end
def flash!(type, message)
session[:flash] = { "type" => type, "message" => message }
end
private
def supercast
@supercast ||= Faraday.new(BASE_URL) do |f|
f.headers["Content-Type"] = "application/x-www-form-urlencoded"
f.headers["Accept"] = "application/json"
f.ssl.verify = false if SUPERCAST_ENV == "development"
end
end
end
# ---------------------------------------------------------------------------
# Routes
# ---------------------------------------------------------------------------
get "/" do
@authenticated = authenticated?
@expired = @authenticated && token_expired?
@subdomain = session[:subdomain] || ""
@env_name = SUPERCAST_ENV
@base_url = BASE_URL
@flash = session.delete(:flash)
erb :index
end
# --- OAuth: start authorization code flow -----------------------------------
get "/auth/authorize" do
state = SecureRandom.hex(16)
session[:oauth_state] = state
query = URI.encode_www_form(
client_id: CLIENT_ID,
response_type: "code",
redirect_uri: REDIRECT_URI,
scope: "public write",
state: state
)
redirect "#{BASE_URL}/oauth/authorize?#{query}"
end
# --- OAuth: handle callback -------------------------------------------------
get "/auth/callback" do
if params[:error]
flash!("error", "Authorization denied: #{params[:error]}")
redirect "/"
end
if params[:state] != session.delete(:oauth_state)
flash!("error", "Invalid state parameter. Please try again.")
redirect "/"
end
response = supercast.post("/oauth/token") do |req|
req.body = URI.encode_www_form(
grant_type: "authorization_code",
code: params[:code],
redirect_uri: REDIRECT_URI,
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET
)
end
token_data = JSON.parse(response.body)
if response.success?
store_tokens(token_data)
flash!("success", "Successfully connected to Supercast.")
else
msg = token_data["error_description"] || token_data["error"] || "Token exchange failed."
flash!("error", msg)
end
redirect "/"
end
# --- Set working subdomain --------------------------------------------------
post "/subdomain" do
session[:subdomain] = params[:subdomain].to_s.strip
redirect "/"
end
# --- Logout -----------------------------------------------------------------
post "/auth/logout" do
session.clear
redirect "/"
end
# --- API: subscribers -------------------------------------------------------
get "/api/subscribers" do
redirect "/" unless authenticated?
page = (params[:page] || 1).to_i
@result = api_call("/subscribers", subdomain: session[:subdomain], page: page, per_page: 20)
@title = "Subscribers"
@endpoint = "/api/v1/subscribers?subdomain=#{session[:subdomain]}"
@page = page
@back_path = "/api/subscribers"
erb :results
end
# --- API: episodes ----------------------------------------------------------
get "/api/episodes" do
redirect "/" unless authenticated?
page = (params[:page] || 1).to_i
@result = api_call("/episodes", subdomain: session[:subdomain], page: page, per_page: 20)
@title = "Episodes"
@endpoint = "/api/v1/episodes?subdomain=#{session[:subdomain]}"
@page = page
@back_path = "/api/episodes"
erb :results
end
# --- API: charges -----------------------------------------------------------
get "/api/charges" do
redirect "/" unless authenticated?
page = (params[:page] || 1).to_i
@result = api_call("/charges", subdomain: session[:subdomain], page: page, per_page: 20)
@title = "Charges"
@endpoint = "/api/v1/charges?subdomain=#{session[:subdomain]}"
@page = page
@back_path = "/api/charges"
erb :results
end