Last active
February 16, 2018 21:46
-
-
Save nz/6243059 to your computer and use it in GitHub Desktop.
Support in Sunspot for Websolr Advanced Auth
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 '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']) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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