-
Notifications
You must be signed in to change notification settings - Fork 25
/
app.rb
68 lines (59 loc) · 2.03 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
require 'guillotine'
require 'redis'
module Katana
class App < Guillotine::App
# use redis adapter with redistogo
uri = URI.parse(ENV["REDISTOGO_URL"] || ENV["REDISGREEN_URL"] || ENV["REDIS_URL"])
REDIS = Redis.new(:host => uri.host, :port => uri.port, :password => uri.password)
adapter = Guillotine::Adapters::RedisAdapter.new REDIS
set :service => Guillotine::Service.new(adapter, :strip_query => false,
:strip_anchor => false)
# authenticate everything except GETs
before do
unless request.request_method == "GET"
protected!
end
end
get '/' do
if ENV['ROOT_REDIRECTS_TO_URL']
redirect ENV['ROOT_REDIRECTS_TO_URL']
else
"Shorten all the URLs"
end
end
if ENV['TWEETBOT_API']
# experimental (unauthenticated) API endpoint for tweetbot
get '/api/create/?' do
status, head, body = settings.service.create(params[:url], params[:code])
if loc = head['Location']
"#{File.join("http://", request.host, loc)}"
else
500
end
end
end
# helper methods
helpers do
# Private: helper method to protect URLs with Rack Basic Auth
#
# Throws 401 if authorization fails
def protected!
return unless ENV["HTTP_USER"]
unless authorized?
response['WWW-Authenticate'] = %(Basic realm="Restricted Area")
throw(:halt, [401, "Not authorized\n"])
end
end
# Private: helper method to check if authorization parameters match the
# set environment variables
#
# Returns true or false
def authorized?
@auth ||= Rack::Auth::Basic::Request.new(request.env)
user = ENV["HTTP_USER"]
pass = ENV["HTTP_PASS"]
@auth.provided? && @auth.basic? && @auth.credentials && @auth.credentials == [user, pass]
end
end
end
end