Skip to content

Instantly share code, notes, and snippets.

@nz
Last active February 16, 2018 21:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nz/6243059 to your computer and use it in GitHub Desktop.
Save nz/6243059 to your computer and use it in GitHub Desktop.
Support in Sunspot for Websolr Advanced Auth
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
alias_method_chain :setup_raw_request, :auth_headers
def setup_raw_request_with_auth_headers
raw_request = setup_raw_request_without_auth_headers
raw_request.headers = raw_request.headers.merge(auth_headers)
raw_request
end
end
end
Sunspot::Session.connection_class = RSolrWithWebsolrAuth.new(ENV['WEBSOLR_SECRET'])
@hasghari
Copy link

alias_method_chain should appear after the setup_raw_request_with_auth_headers method, otherwise we get an undefined method exception.

Why not call super here since we're subclassing?

def setup_raw_request
  raw_request = super
  raw_request.headers = raw_request.headers.merge(auth_headers)
  raw_request
end

@alfius
Copy link

alfius commented Nov 26, 2014

Thanks! I had to change the setup_raw_request method a little bit to make it work: https://gist.github.com/alfonsocora/e1f979621bbfe98e10dc

@pramodthammaiah
Copy link

@alfonsocora's gist got it working for me

The gist here gave me a NameError: undefined method

@diazruy
Copy link

diazruy commented Feb 16, 2018

alias_method_chain has been deprecated in RoR5 (and fully removed in 5.1), causing the code as is to error out. @alfonsocora's version does still work on RoR5

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