Skip to content

Instantly share code, notes, and snippets.

@dodeja
Created January 27, 2012 23:44
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dodeja/1691624 to your computer and use it in GitHub Desktop.
Save dodeja/1691624 to your computer and use it in GitHub Desktop.
Warden HTTP Basic Auth Strategy for Padrino
# I am using this for an API. So auth key is passed as user name.
Warden::Strategies.add(:basic) do
def auth
@auth ||= Rack::Auth::Basic::Request.new(env)
end
def store?
false
end
def authenticate!
return custom!(unauthorized) unless auth.provided?
return custom!(unauthorized) unless auth.basic?
client = ClientApplication.authenticate(auth.credentials.first)
return client.nil? ? custom!(unauthorized :invalid_key) : success!(client)
end
def unauthorized(type = nil)
type ||= :bad_request
key = auth.provided? ? auth.credentials.first : ''
error_messages = {
bad_request: "You did not provide an API key. ",
invalid_key: "Invalid API Key provided: #{key}"
}
error_response = {
error: {
message: error_messages[type],
type: "invalid_request_error"
}
}
Rack::Response.new([JSON.pretty_generate(error_response)], 401, 'Content-Type' => 'application/json', 'WWW-Authenticate' => %(Basic realm="API") )
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment