Skip to content

Instantly share code, notes, and snippets.

@freegenie
Created February 9, 2015 11:54
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 freegenie/eebd004c67ac5d6afb45 to your computer and use it in GitHub Desktop.
Save freegenie/eebd004c67ac5d6afb45 to your computer and use it in GitHub Desktop.
desk.com multipass authentication
module DeskMultipass
URL_TEMPLATE = "https://%s.desk.com/customer/authentication/multipass/callback?multipass=%s&signature=%s"
def self.signed_url(user, redirect_to=nil)
raise "DESK_API_KEY is not set" if ENV['DESK_API_KEY'].blank?
raise "DESK_SUBDOMAIN is not set" if ENV['DESK_SUBDOMAIN'].blank?
# Create the encryption key using a 16 byte SHA1 digest of your api key and subdomain
key = Digest::SHA1.digest(ENV['DESK_API_KEY'] + ENV['DESK_SUBDOMAIN'])[0...16]
# Generate a random 16 byte IV
iv = OpenSSL::Random.random_bytes(16)
data_for_json = {
:uid => user.id,
:expires => (Time.now + 120).iso8601, # Expire two minutes from now
:customer_name => user.email,
:customer_email => user.email
}
# redirect if any path given
unless redirect_to.nil?
data_for_json.update(to: redirect_to)
end
# Build the JSON string
json = JSON.generate data_for_json
# Encrypt JSON string using AES128-CBC
cipher = OpenSSL::Cipher::Cipher.new("aes-128-cbc")
cipher.encrypt # specifies the cipher's mode (encryption vs decryption)
cipher.key = key
cipher.iv = iv
encrypted = cipher.update(json) + cipher.final
# Prepend encrypted data with the IV
prepended = iv + encrypted
# Base64 encode the prepended encrypted data
multipass = Base64.encode64(prepended)
# Build an HMAC-SHA1 signature using the encoded multipass and your api key
signature = Base64.encode64(OpenSSL::HMAC.digest('sha1', ENV['DESK_API_KEY'], multipass))
# URL escape the final multipass and signature parameters
encoded_multipass = CGI.escape(multipass)
encoded_signature = CGI.escape(signature)
URL_TEMPLATE % [ ENV['DESK_SUBDOMAIN'], encoded_multipass, encoded_signature ]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment