-
Notifications
You must be signed in to change notification settings - Fork 4
/
test_server.rb
73 lines (62 loc) · 1.63 KB
/
test_server.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
require 'sinatra'
if ENV['bind']
set :bind, ENV['bind']
end
disable :logging
helpers do
def restricted_area
headers['WWW-Authenticate'] = 'Basic realm="Restricted Area"'
halt 401, "Not authorized\n"
end
def http_protect!
return if http_authorized?
restricted_area
end
def token_protect!
return if token_authorized?
restricted_area
end
def token_authorized?
request.env.fetch('HTTP_AUTHORIZATION', nil) &&
'rubymotion' == request.env['HTTP_AUTHORIZATION'].match(/Token token="(.*)"/).captures.first
end
def http_authorized?
@auth ||= Rack::Auth::Basic::Request.new(request.env)
@auth.provided? and @auth.basic? and @auth.credentials and @auth.credentials == ['admin', 'letmein']
end
end
before do
puts "#{request.request_method} #{request.path_info} #{request.env['HTTP_VERSION']}"
headers = Hash[*request.env.select {|k,v| k.start_with? 'HTTP_'}
.collect {|k,v| [k.sub(/^HTTP_/, ''), v]}
.collect {|k,v| [k.split('_').collect(&:capitalize).join('-'), v]}
.sort
.flatten]
headers.each do |k,v|
next if k == 'Host'
next if k == 'Version'
puts "#{k}: #{v}"
end
if request.content_length && request.content_length.to_i > 0
puts "Content-Type: #{request.media_type}"
puts "Content-Length: #{request.content_length}"
puts request.body.read
end
puts
end
get '/basic_auth' do
http_protect!
"Welcome"
end
get('/token_auth') do
token_protect!
"Welcome"
end
get '*' do
headers 'content-type' => 'application/json'
body '[{"title":"Example Post"}]'
end
post '*' do
headers 'content-type' => 'application/json'
body '[{"title":"Example Post"}]'
end