Skip to content

Instantly share code, notes, and snippets.

@alfius
Created November 26, 2014 16:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alfius/e1f979621bbfe98e10dc to your computer and use it in GitHub Desktop.
Save alfius/e1f979621bbfe98e10dc to your computer and use it in GitHub Desktop.
Setup Sunspot and Websolr with authentication
# put this file in config/initializers
require 'openssl'
class RSolrWithWebsolrAuth
attr_reader :secret
def initialize(secret)
@secret = secret
end
def connect(opts = {})
RSolr::Client.new(AuthenticatedConnection.new(secret), opts)
end
class AuthenticatedConnection < ::RSolr::Connection
attr_reader :secret
def initialize(secret)
@secret = secret
end
def auth_headers
time = Time.now.to_i
nonce = Time.now.to_i.to_s.split(//).sort_by{rand}.join
auth = OpenSSL::HMAC.hexdigest('sha1', secret, "#{time}#{nonce}")
{
'X-Websolr-Time' => time.to_s,
'X-Websolr-Nonce' => nonce,
'X-Websolr-Auth' => auth
}
end
def setup_raw_request(request_context)
request_context[:headers] ||= {}
request_context[:headers].merge!(auth_headers)
super(request_context)
end
end
end
if Rails.env.production? || Rails.env.staging?
Sunspot::Session.connection_class = RSolrWithWebsolrAuth.new(ENV['WEBSOLR_SECRET'])
end
@pramodthammaiah
Copy link

This worked for me. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment