From 0f030b6d1ff1d3b6b73a9bd4b995516627c8cb41 Mon Sep 17 00:00:00 2001 From: Adam Wiggins Date: Fri, 14 Aug 2009 14:51:58 -0700 Subject: [PATCH] request.secure? to check for ssl encrypted connection Signed-off-by: Simon Rozet --- lib/sinatra/base.rb | 4 ++++ test/request_test.rb | 15 +++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/lib/sinatra/base.rb b/lib/sinatra/base.rb index 329a4ef1..104e1cc5 100644 --- a/lib/sinatra/base.rb +++ b/lib/sinatra/base.rb @@ -26,6 +26,10 @@ module Sinatra rescue EOFError, Errno::ESPIPE self.GET end + + def secure? + (@env['HTTP_X_FORWARDED_PROTO'] || @env['rack.url_scheme']) == 'https' + end end # The response object. See Rack::Response and Rack::ResponseHelpers for diff --git a/test/request_test.rb b/test/request_test.rb index 44dac6cb..f213646c 100644 --- a/test/request_test.rb +++ b/test/request_test.rb @@ -15,4 +15,19 @@ class RequestTest < Test::Unit::TestCase ) assert_equal 'bar', request.params['foo'] end + + it 'is secure when the url scheme is https' do + request = Sinatra::Request.new('rack.url_scheme' => 'https') + assert request.secure? + end + + it 'is not secure when the url scheme is http' do + request = Sinatra::Request.new('rack.url_scheme' => 'http') + assert !request.secure? + end + + it 'respects X-Forwarded-Proto header for proxied SSL' do + request = Sinatra::Request.new('HTTP_X_FORWARDED_PROTO' => 'https') + assert request.secure? + end end