Skip to content

Commit

Permalink
Fix teampoltergeist#263 add basic_authorize method
Browse files Browse the repository at this point in the history
  • Loading branch information
route committed Oct 9, 2013
1 parent 0707343 commit 8afd1cf
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 0 deletions.
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ and the following optional features:
* `page.scroll_to`
* cookie handling
* drag-and-drop
* basic http authentication

There are some additional features:

Expand Down Expand Up @@ -234,6 +235,17 @@ page.within_window fb_popup do
end
```

### Basic HTTP authentication ###

This method can be used for basic authentication:

``` ruby
page.driver.basic_authorize('username', 'password')
```

It actually appends `Authorize` header to bunch of your headers, so since you've
set it don't try to use `headers=` which will overwrite it.


## Customization ##

Expand Down
7 changes: 7 additions & 0 deletions lib/capybara/poltergeist/driver.rb
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,13 @@ def cookies_enabled=(flag)
browser.cookies_enabled = flag
end

# Since PhantomJS doesn't send `Authorize` header with POST
# request at all, it's better to set header manually.
def basic_authorize(user, password)
credentials = ["#{user}:#{password}"].pack('m*')
add_header('Authorization', "Basic #{credentials}")
end

def debug
if @options[:inspector]
inspector.open
Expand Down
18 changes: 18 additions & 0 deletions spec/integration/driver_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -620,5 +620,23 @@ def create_screenshot(file, *args)
expect(@driver.browser.window_handles).to eq(["popup"])
expect(@driver.window_handles).to eq(["popup"])
end

context 'basic http authentication' do
it 'does not set header' do
@session.visit '/poltergeist/basic_auth'

expect(@session.status_code).to eq(401)
expect(@session).not_to have_content('Welcome, authenticated client')
end

it 'sets header' do
@driver.basic_authorize('login', 'pass')

@session.visit '/poltergeist/basic_auth'

expect(@session.status_code).to eq(200)
expect(@session).to have_content('Welcome, authenticated client')
end
end
end
end
10 changes: 10 additions & 0 deletions spec/support/test_app.rb
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,16 @@ class TestApp
"slow page"
end

get '/poltergeist/basic_auth' do
auth = Rack::Auth::Basic::Request.new(request.env)
if auth.provided? and auth.basic? and auth.credentials and auth.credentials == ['login', 'pass']
'Welcome, authenticated client'
else
headers['WWW-Authenticate'] = 'Basic realm="Restricted Area"'
halt 401, "Not authorized\n"
end
end

get '/poltergeist/:view' do |view|
render_view view
end
Expand Down

0 comments on commit 8afd1cf

Please sign in to comment.