Created
November 26, 2014 16:45
-
-
Save alfius/e1f979621bbfe98e10dc to your computer and use it in GitHub Desktop.
Setup Sunspot and Websolr with authentication
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
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This worked for me. Thanks!