-
Notifications
You must be signed in to change notification settings - Fork 6
/
public_app.rb
426 lines (360 loc) · 14.8 KB
/
public_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
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
# Core
require 'open3'
require 'date'
require 'digest/sha2'
require 'securerandom'
require 'date'
# External
require 'bundler'
require 'rack/ssl'
require 'rack/auth/basic'
require 'sinatra/base'
require 'sinatra/cookies'
require 'sinatra/streaming'
require 'octokit'
require 'json'
# Front end
require 'sass'
require 'slim'
require 'sprockets'
require 'compass'
require 'sprockets-sass'
require 'sprockets-helpers'
require_relative 'helpers/repository'
require_relative 'helpers/link'
module AwestructWebEditor
class PublicApp < Sinatra::Base
set :sprockets, Sprockets::Environment.new(root)
set :ssl, lambda { |_| development? }
set :protection, :origin_whitelist => ['https://webeditor.bleepbleep.org.uk']
use Rack::Session::Cookie, :key => 'awestruct-editor-session',
:path => '/',
:secret => (ENV['OPENSHIFT_APP_UUID'] || 'localhost'), # TODO: add something for Contegix
:old_secret => '6b0385be07bcc169a1ee49ddb4b33c9d31cc668504dd2b5b59185253dcf55b42d7f6c766f546f638cd3fe829b9d32a59db61a5938d75ab2f2c15336a2368c9e6'
#use Rack::SSL, :exclude => lambda { |_| development? }
configure do
# Setup logging
enable :logging
log_file = File.new(File.join((ENV['OPENSHIFT_RUBY_LOG_DIR'] || 'log'), 'application.log' ), 'a+')
log_file.sync = true
set :logger, Logger.new(log_file, 'daily')
use Rack::CommonLogger, log_file
# Setup Sprockets
Sprockets::Helpers.configure do |config|
config.environment = sprockets
%w(sass javascripts images fonts).each do |dir|
sprockets.append_path File.join(root, 'assets', dir)
end
#if production?
%w(font stylesheets javascripts images).each do |dir|
sprockets.prepend_path File.join('public', dir)
end
sprockets.index
#end
end
end
configure :development do
require 'sinatra/reloader'
register Sinatra::Reloader
also_reload 'models/**/*.rb'
set :raise_errors, true
enable :dump_errors, :raise_errors
end
# Security
before %r{^/(repo|settings)(/[\w]+)*} do
pass if ((request.path_info =~ %r{^/repo}) && (request.path_info =~ /images/))
check_token
end
before '/token' do
unless session['gh-pass'] and read_settings()['username']
auth ||= Rack::Auth::Basic::Request.new request.env
if auth.provided? && auth.basic? && auth.credentials
session['username'] = auth.credentials[0]
session['gh-pass'] = auth.credentials[1]
begin
get_octokit_client(auth.credentials[0]).user
write_settings(read_settings().merge({'username' => session['username']}))
rescue Octokit::Unauthorized => e
halt 401, e.to_s
end
else
halt 401, 'Unauthorized'
end
end
end
get '/token' do
get_token
end
# From the secure portion
get '/settings' do
settings = read_settings
if settings.is_a? Hash
settings = settings.reject { |k,_| /oauth|client/ =~ k}
end
[200, JSON.dump(settings)]
end
post '/settings' do
settings = read_settings().merge({ 'repo' => params['repo'].sub(%r{^(((git@github.com:)|(https(s)?://github.com/)?))},'/').sub(/\.git$/,'') })
write_settings settings
end
put '/settings' do
settings = read_settings().merge({ 'repo' => params['repo'].sub(%r{^(((git@github.com:)|(https(s)?://github.com/)?))},'/').sub(/\.git$/,'') })
logger.debug "Settings: #{settings}"
get_github_token settings
repo = AwestructWebEditor::Repository.new(:name => settings['repo'].split('/').last,
:token => session[:github_auth], :username => session['username'])
repo.init_empty
repo.add_creds
clone_result = repo.clone_repo
if clone_result.first != 0
[500, clone_result[1]]
else
[200, 'Successfully cloned']
end
end
error do
"An error occurred while processing: #{env['sinatra.error']}. Message: #{env['sinatra.error'].message}"
end
# Views
get '/' do
slim :index
end
get '/partials/*.*' do |basename, _|
slim "partials/#{basename}".to_sym
end
# Application API
# Git related APIs
post '/repo/:repo_name/change_set' do |repo_name|
create_repo(repo_name).create_branch params[:name]
end
post '/repo/:repo_name/commit' do |repo_name|
if create_repo(repo_name).commit(params[:message]).nil?
[500, 'Error committing']
else
[200, 'Success']
end
end
post '/repo/:repo_name/pull_latest' do |repo_name|
repo = create_repo(repo_name)
repo.rebase(params.include? :overwrite)
end
# Repo APIs
post '/repo/:repo_name/push' do |repo_name|
repo = create_repo(repo_name)
repo.push
repo.pull_request params[:title], params[:message]
end
get '/repo' do
repo_base = ENV['RACK_ENV'] =~ /test/ ? "tmp/repos/#{session('username')}" : "repos/#{session('username')}"
return_structure = {}
Dir[repo_base + '/*'].each do |f|
if File.directory? f
basename = File.basename f
return_structure[basename] = { 'links' => [AwestructWebEditor::Link.new({ :url => url("/repo/#{basename}"),
:text => f,
:method => 'GET' })] }
end
end
[200, JSON.dump(return_structure)]
end
# File related APIs
get '/repo/:repo_name' do |repo_name|
additional_allows = params[:allow] || ''
files = create_repo(repo_name).all_files([Regexp.compile(additional_allows)])
return_links = {}
files.each do |f|
links = []
unless f[:directory]
links = links_for_file(f, repo_name)
end
if f[:path_to_root] =~ /\./
return_links[f[:location]] = { :links => links, :directory => f[:directory], :children => {},
:path => File.join(f[:path_to_root], f[:location]) }
else
directory_paths = f[:path_to_root].split(File::SEPARATOR)
final_location = return_links[directory_paths[0]]
directory_paths.delete(directory_paths[0])
directory_paths.each { |path| final_location = final_location[:children][path] } unless directory_paths.nil?
final_location[:children][f[:location]] = { :links => links, :directory => f[:directory], :children => {},
:path => File.join(f[:path_to_root], f[:location]) }
end
end
[200, JSON.dump(return_links)]
end
get '/repo/:repo_name/images' do |repo_name|
repo = create_repo(repo_name)
files = repo.all_files([], 'images')
json_return = {}
files.each do |f|
unless f[:directory]
json_return[f[:location]] = { :content => repo.file_content(File.join('images', f[:location]))}
end
end
[200, JSON.dump(json_return)]
end
get '/repo/:repo_name/branches' do |repo_name|
repo = create_repo(repo_name)
[200, JSON.dump(repo.branches)]
end
post '/repo/:repo_name/branches/:branch_name' do |repo_name, branch_name|
repo = create_repo(repo_name).switch_branch branch_name
end
get '/repo/:repo_name/*' do |repo_name, path|
repo = create_repo(repo_name)
json_return = { :content => repo.file_content(path), :links => links_for_file(repo.file_info(path), repo_name) }
[200, JSON.dump(json_return)]
end
post '/repo/:repo_name/*' do |repo_name, path|
save_or_create(repo_name, path)
end
put '/repo/:repo_name/*' do |repo_name, path|
save_or_create(repo_name, path)
end
delete '/repo/:repo_name/*' do |repo_name, path|
result = create_repo(repo_name).remove_file path
result ? [200] : [500]
end
# Preview APIs
get '/preview/:repo_name' do |repo_name|
retrieve_rendered_file(create_repo(repo_name), '_site/index.html')
end
get '/preview/:repo_name/*' do |repo_name, path|
retrieve_rendered_file(create_repo(repo_name), path)
end
helpers do
include Sprockets::Helpers
include Sinatra::Cookies
include Sinatra::Streaming
def check_token
unless env['HTTP_TOKEN'] == (Digest::SHA512.new << "#{session[:csrf]}#{env['HTTP_TIME']}").to_s
error 401, 'You are not allowed to do this.'
end
end
def get_token
time = DateTime.now.iso8601
if session[:csrf].nil?
session[:csrf] = (Digest::SHA512.new << SecureRandom.uuid << SecureRandom.random_bytes).to_s
end
response.headers['base_token'] = session[:csrf]
(Digest::SHA512.new << "#{session[:csrf]}#{time}").to_s
end
def settings_storage_file
if ENV['OPENSHIFT_DATA_DIR']
base_repo_dir = File.join(ENV['OPENSHIFT_DATA_DIR'], 'repos', session['username'])
elsif ENV['RACK_ENV'] =~ /test/
base_repo_dir = "tmp/repos/#{session['username']}"
else
base_repo_dir = "repos/#{session['username']}"
end
FileUtils.mkdir_p(File.join base_repo_dir) unless File.exists? base_repo_dir
File.join(base_repo_dir, 'github-settings')
end
def read_settings
if File.exists?(settings_storage_file)
File.open(settings_storage_file, 'r') do |f|
get_github_token JSON.load(f)
end
else
{}
end
end
def write_settings(settings)
File.open(settings_storage_file, 'w+') do |f|
f.write JSON.dump(settings)
end
end
def get_github_token(settings)
unless session[:github_auth] && settings['token_id']
client = get_octokit_client(session['username'])
logger.debug "github_client: #{client}"
# if token_id (get token, save in session)
result = {}
if settings['token_id']
result = client.authorization settings['token_id']
logger.debug "result from authorization: #{result}"
else
result = client.create_authorization :note => 'Awestruct Web Editor', :scopes => ['repo']
logger.debug "result from create_authorization: #{result}"
settings['token_id'] = result['id']
end
if result.empty?
error 500, 'Error authenticating with GitHub'
end
session[:github_auth] = result['token']
settings.delete('password')
end
write_settings settings
settings
end
def create_repo(repo_name)
AwestructWebEditor::Repository.new({ :name => repo_name, :token => session[:github_auth], :username => session['username'] })
end
def links_for_file(f, repo_name)
links = []
links << AwestructWebEditor::Link.new({ :url => url("/repo/#{repo_name}/#{f[:path_to_root]}/#{f[:location]}"), :text => f[:location], :method => 'GET' })
links << AwestructWebEditor::Link.new({ :url => url("/repo/#{repo_name}/#{f[:path_to_root]}/#{f[:location]}"), :text => f[:location], :method => 'PUT' })
links << AwestructWebEditor::Link.new({ :url => url("/repo/#{repo_name}/#{f[:path_to_root]}/#{f[:location]}"), :text => f[:location], :method => 'POST' })
links << AwestructWebEditor::Link.new({ :url => url("/repo/#{repo_name}/#{f[:path_to_root]}/#{f[:location]}"), :text => f[:location], :method => 'DELETE' })
links << AwestructWebEditor::Link.new({ :url => url("/repo/#{repo_name}/#{f[:path_to_root]}/#{f[:location]}/preview"), :text => "Preview #{f[:location]}", :method => 'GET' })
end
def save_or_create(repo_name, path)
stream do |out|
request.body.rewind # in case someone already read it
repo = create_repo repo_name
out.write repo.save_file(path, params[:content]) + "\n"
out.flush
out.write retrieve_rendered_file(repo, path, false) unless ENV['RACK_ENV'] =~ /test/
out.flush
end
end
def retrieve_rendered_file(repo, path, return_content = true)
mapping_file = File.join(repo.base_repository_path, '_tmp', 'mapping.json')
unless File.exists? mapping_file
logger.info 'executing external script to render file'
Bundler.with_clean_env do
Open3.popen3("ruby exec_awestruct.rb --repo #{repo.name} --url '#{request.scheme}://#{request.host}:#{request.port}' --profile development --username '#{session['username']}'") do |_, stdout, stderr, _|
errors = stderr.readlines.join
logger.error "Error during rendering: #{errors}" unless errors.empty?
return [500, "Error: #{final_path.to_s} not rendered"] unless errors.empty?
end
end
end
# Open mapping file
# find path
# check mtime
# (re)-generate if source file is newer than generated file
# Grab the generated file, return it and the content/type
mapping_json = JSON.parse(File.readlines(mapping_file).first)
final_path = path
if File.extname(final_path).empty?
final_path = File.join final_path, 'index.html'
end
if return_content
generated_mtime = mapping_json[mapping_json['/' + final_path]['relative_source_path']]['output_mtime']
source_mtime = mapping_json['/' + final_path]['source_mtime']
else
generated_mtime = mapping_json['/' + final_path]['output_mtime']
source_mtime = repo.file_info(File.basename(final_path), File.dirname(final_path))[:mtime]
end
if source_mtime > generated_mtime
Bundler.with_clean_env do
Open3.popen3("ruby exec_awestruct.rb --repo #{repo.name} --url '#{request.scheme}://#{request.host}:#{request.port}' --profile development --username '#{session['username']}'") do |_, _, stderr, _|
errors = stderr.readlines.join
logger.error "Error during rendering: #{errors}" unless errors.empty?
return [500, "Error: #{final_path.to_s} not rendered"] unless errors.empty?
end
end
mapping_json = JSON.parse(File.readlines(mapping_file).first) # reload the file to include new info
end
if return_content
[200, {'Content-type' => mapping_json['/' + final_path]['content-type']}, File.open(File.join(repo.base_repository_path, final_path), 'r') { |f| f.readlines }]
else
url("preview/#{repo.name}/_site#{mapping_json['/' + final_path]['output_path']}")
end
end
def get_octokit_client(username)
Octokit::Client.new(:login => username, :password => session['gh-pass'])
end
end
end
end