Created
May 1, 2011 08:42
-
-
Save sabman/950349 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'devise/strategies/base' | |
module Devise | |
module Strategies | |
# Sign in an user using HTTP authentication. | |
class HttpAuthenticatableWithContentType < Base | |
MESSAGE = "Could not authenticate you." | |
def valid? | |
request.authorization && mapping.to.respond_to?(:authenticate_with_http) | |
end | |
def authenticate! | |
username, password = username_and_password | |
if resource = mapping.to.authenticate_with_http(username, password) | |
success!(resource) | |
else | |
custom!([401, custom_headers, custom_message]) | |
end | |
end | |
private | |
def username_and_password | |
decode_credentials(request).split(/:/, 2) | |
end | |
def decode_credentials(request) | |
ActiveSupport::Base64.decode64(request.authorization.split(' ', 2).last || '') | |
end | |
def custom_headers | |
{ | |
"Content-Type" => request.format.to_s, | |
"WWW-Authenticate" => %(Basic realm="#{Devise.http_authentication_realm.gsub(/"/, "")}") | |
} | |
end | |
def custom_message | |
case request.format.to_s | |
when 'application/xml': [ { :error => MESSAGE }.to_xml ] | |
when 'application/json': [ { :error => MESSAGE }.to_json ] | |
else | |
[ MESSAGE ] | |
end | |
end | |
end | |
end | |
end | |
Warden::Strategies.add(:http_authenticatable_with_content_type, Devise::Strategies::HttpAuthenticatableWithContentType) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment