Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Generate stoken and attach it as a data attribute #132

Merged
merged 1 commit into from
Jul 20, 2015
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
19 changes: 15 additions & 4 deletions lib/recaptcha/client_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -63,20 +63,31 @@ def v1_tags(options)
end

def v2_tags(options)
key = options[:public_key] ||= Recaptcha.configuration.public_key
raise RecaptchaError, "No public key specified." unless key
public_key = options[:public_key] ||= Recaptcha.configuration.public_key
raise RecaptchaError, "No public key specified." unless public_key
private_key = options[:private_key] ||= Recaptcha.configuration.private_key
raise RecaptchaError, "No private key specified." unless private_key
error = options[:error] ||= ((defined? flash) ? flash[:recaptcha_error] : "")
uri = Recaptcha.configuration.api_server_url(options[:ssl])
uri += "?hl=#{options[:hl]}" unless options[:hl].blank?

v2_options = options.slice(:theme, :type, :callback, :expired_callback).map {|k,v| %{data-#{k.to_s.gsub(/_/,'-')}="#{v}"} }.join(" ")

stoken_json = hash_to_json({'session_id' => SecureRandom.uuid, 'ts_ms' => (Time.now.to_f * 1000).to_i})
cipher = OpenSSL::Cipher::AES128.new(:ECB)
private_key_digest = Digest::SHA1.digest(private_key)[0...16]

cipher.encrypt
cipher.key = private_key_digest
encrypted_stoken = cipher.update(stoken_json) << cipher.final
encoded_stoken = Base64.urlsafe_encode64(encrypted_stoken).gsub(/\=+\Z/, '')

html = ""
html << %{<script src="#{uri}" async defer></script>\n}
html << %{<div class="g-recaptcha" data-sitekey="#{key}" #{v2_options}></div>\n}
html << %{<div class="g-recaptcha" data-sitekey="#{public_key}" data-stoken="#{encoded_stoken}" #{v2_options}></div>\n}

unless options[:noscript] == false
fallback_uri = "#{uri.chomp('.js')}/fallback?k=#{key}"
fallback_uri = "#{uri.chomp('.js')}/fallback?k=#{public_key}"
html << %{<noscript>}
html << %{<div style="width: 302px; height: 352px;">}
html << %{ <div style="width: 302px; height: 352px; position: relative;">}
Expand Down