Create a domain-specific ".site.com" cookie with Ruby's selenium-webdriver [duplicate] - ruby

This question already has answers here:
How to set a cookie for another domain
(11 answers)
Closed 9 years ago.
I am trying to create a cookie with domain, not host, or entire website.
I have this code now
driver.manage.add_cookie(:name => 'test', :value => 'testvalue', :path => '/', :secure => false)
I want something like this
name=test
value=testvalue
domain=.site.com
path=/
I am getting such result in a firefox cookie dialog
while I want something like this
You can see Host: is empty in my case and in another case it is replaced with Domain: and this is what I want to achieve, to set a cookie domain to .mydomain.com
I want to achieve this for JavaScript to be able to read domain-specific cookies as it can not read what's outside of current domain scope.

Try following:
require 'selenium-webdriver'
driver = Selenium::WebDriver.for :firefox
driver.get('http://eu.httpbin.org') # <-- required.
driver.manage.add_cookie(name: 'test', value: 'testvalue', path: '/', domain: '.httpbin.org')
driver.get('http://eu.httpbin.org/cookies') # eu.httpbin.org
puts driver.page_source
# => ...
# {
# "cookies": {
# "test": "testvalue"
# }
# }
# ...
driver.get('http://httpbin.org/cookies') # httpbin.org
puts driver.page_source
# => ...
# {
# "cookies": {
# "test": "testvalue"
# }
# }
# ...
NOTE: You have to go to the same domain page (html page) before adding cookie.

You can do as below using JavaScript :
require "selenium-webdriver"
require "awesome_print"
driver = Selenium::WebDriver.for :firefox
driver.navigate.to "http://example.com"
COOKIE_DOMAIN = <<-eotl
var cookieName = arguments[0];
var cookieValue = arguments[1];
var myDate = new Date();
myDate.setMonth(myDate.getMonth() + 12);
document.cookie = cookieName +"=" + encodeURIComponent(cookieValue)
+ ";expires=" + myDate
+ ";domain=.example.com;path=/";
eotl
driver.execute_script(COOKIE_DOMAIN,'test','testvalue')
ap driver.manage.cookie_named('test')
output
{
:name => "test",
:value => "testvalue",
:path => "/",
:domain => ".example.com",
:expires => #<DateTime: 2014-09-09T07:43:12+00:00 ((2456910j,27792s,999999924n),+0s,2299161j)>,
:secure => false
}

Related

ChromeOptions To Not Prompt For Download When Running RemoteDriver

I'm trying to debug why when running remote webdriver tests on a headless linux host download dialogs are presented in chrome. I believe the chrome version is 45.
Couple of Env Details
Selenium 2.53 (gem)
Selenium 2.53 Server Jar
Chrome Driver 2.21
The framework/Tests are written in Ruby utilizing Capybara for driving web tests. Here is a brief snippet of how the remote driver is initialized.
prefernces = {
:download => {
:prompt_for_download => false,
:default_directory => '/home/john.doe/Downloads/'
}
}
caps = Selenium::WebDriver::Remote::Capabilities.chrome()
caps['chromeOptions'] = {'prefs' => prefernces}
http_client = Selenium::WebDriver::Remote::Http::Default.new
http_client.timeout = 240
options = {
browser: :remote,
url: "http://<server_url>:4444/wd/hub",
desired_capabilities: caps,
http_client: http_client
}
# Returns Remote Driver
Capybara::Selenium::Driver.new(app, options)
I have verified via the hub that the chromeOptions are set, but when a file is downloaded, we're presented with a file dialog prompt.
I've burned the candle looking for a solution to this problem. Thanks for the help and consideration!
try removing the / from the end of the default_directory and also setting directory_upgrade: true. Other than that make sure the browser has permission to write to the selected directory (note also the correct spelling of preferences)
preferences = {
:download => {
:default_directory => '/home/john.doe/Downloads',
:directory_upgrade => true,
:prompt_for_download => false,
}
}
caps = Selenium::WebDriver::Remote::Capabilities.chrome(
'chromeOptions' => {'prefs' => preferences}
)
Here is an example to download a file with Capybara / Selenium / Chrome :
require 'capybara'
require 'selenium-webdriver'
Capybara.register_driver :chrome do |app|
Capybara::Selenium::Driver.new(app,
:url => "http://localhost:4444/wd/hub",
:browser => :chrome,
:desired_capabilities => Selenium::WebDriver::Remote::Capabilities.chrome(
'chromeOptions' => {
'prefs' => {
'download.default_directory' => File.expand_path("C:\\Download"),
'download.directory_upgrade' => true,
'download.prompt_for_download' => false,
'plugins.plugins_disabled' => ["Chrome PDF Viewer"]
}
}
)
)
end
session = Capybara::Session.new(:chrome)
session.visit "https://www.mozilla.org/en-US/foundation/documents"
session.click_link "IRS Form 872-C"
sleep 20

Validate In-App-Purchase Android/Google on Server side

I would like to use the purchase token from the in app purchases in an android app to validate it to the google server on my own server.
With the following code I can validate a token, but I have to authenticate myself with my OAuth credentials every time:
class GooglePlayVerification
require 'google/api_client'
# Refer:
# https://code.google.com/p/google-api-ruby-client/issues/detail?id=72
# and
# http://jonathanotto.com/blog/google_oauth2_api_quick_tutorial.html
# and
# http://milancermak.wordpress.com/2012/08/24/server-side-verification-of-google-play-subsc/
GOOGLE_KEY = 'xxx.apps.googleusercontent.com'
GOOGLE_SECRET = 'xxxx'
APP_NAME = 'xx.xx.xx'
SCOPE = "https://www.googleapis.com/auth/androidpublisher"
def self.token
##token ||= begin
require 'oauth2'
raise "Missing client_id variable" if GOOGLE_KEY.to_s.empty?
raise "Missing client_secret variable" if GOOGLE_SECRET.to_s.empty?
raise "Missing scope variable" if SCOPE.to_s.empty?
redirect_uri = 'https://localhost/oauth2callback'
auth_client_obj = OAuth2::Client.new(GOOGLE_KEY, GOOGLE_SECRET, {:site => 'https://accounts.google.com', :authorize_url => "/o/oauth2/auth", :token_url => "/o/oauth2/token"})
puts "1) Paste this URL into your browser where you are logged in to the relevant Google account\n\n"
puts auth_client_obj.auth_code.authorize_url(:scope => SCOPE, :access_type => "offline", :redirect_uri => redirect_uri, :approval_prompt => 'force')
puts "\n\n\n2) Accept the authorization request from Google in your browser:"
puts "\n\n\n3) Google will redirect you to localhost, but just copy the code parameter out of the URL they redirect you to, paste it here and hit enter:\n"
code = gets.chomp.strip
access_token_obj = auth_client_obj.auth_code.get_token(code, {:redirect_uri => redirect_uri, :token_method => :post})
puts "Result: #{access_token_obj.inspect}\n\n"
puts "Token is: #{access_token_obj.token}"
puts "Refresh token is: #{access_token_obj.refresh_token}"
{
:access_token => access_token_obj.token,
:refresh_token => access_token_obj.refresh_token,
:expires_in => access_token_obj.expires_in,
:expires_at => access_token_obj.expires_at
}
end
end
def self.refresh_token
refresh_client_obj = OAuth2::Client.new(GOOGLE_KEY, GOOGLE_SECRET, {:site => 'https://accounts.google.com', :authorize_url => '/o/oauth2/auth', :token_url => '/o/oauth2/token'})
refresh_access_token_obj = OAuth2::AccessToken.new(refresh_client_obj, token[:access_token], {refresh_token: token[:refresh_token]})
refresh_access_token_obj.refresh!
puts "refresh token: #{refresh_access_token_obj.inspect}"
##token = {
:access_token => refresh_access_token_obj.token,
:refresh_token => refresh_access_token_obj.refresh_token,
:expires_in => refresh_access_token_obj.expires_in,
:expires_at => refresh_access_token_obj.expires_at
}
end
# ie. https://developers.google.com/android-publisher/v1/
# eg.
# #subscription_id com.stocklight.stocklight.standardsubscription
# #purchase_token xxx
def self.verify_subscription(subscription_id, purchase_token)
response = RestClient.get "https://www.googleapis.com/androidpublisher/v1.1/applications/#{APP_NAME}/inapp/#{subscription_id}/purchases/#{purchase_token}?access_token=#{token[:access_token]}"
puts "Respnse \n #{response.inspect}"
puts response.code == 200
puts JSON.parse(response)
return response.code == 200 && JSON.parse(response)['kind'] =='androidpublisher#inappPurchase'
rescue
return false
end
end
Has anyone an idea how to authenticate a server without such things like OAuth on the server? Is there another authentification possibility?
Thanks!
Here is my ruby code:
def self.verify_subscription(subscription_id, transaction_id)
json = JSON.parse(transaction_id)
order = ["orderId", "packageName", "productId", "purchaseTime", "purchaseState", "purchaseToken"]
signature = json["signature"]
data = {}
order.each do |o|
data[o] = json[o]
end
key = OpenSSL::PKey::RSA.new(Base64.decode64(GOOGLE_PUBLIC_KEY))
verified = key.verify(OpenSSL::Digest::SHA1.new, Base64.decode64(signature), data.to_json)
verified
end

Authorization to google drive api using Ruby

I want to make a simple application (like a Service account -in google api console) which send a file to an google drive.
I have got code like this:
require 'rubygems'
require 'google/api_client'
require 'launchy'
#extra
gem 'oauth2'
gem 'omniauth'
client = Google::APIClient.new({:application_name => "testdevelop",:application_version => "1.0"})
drive = client.discovered_api('drive', 'v2')
####################################################################################
# Initialize OAuth 2.0 client
# client.authorization.client_id = '111062272758.apps.googleusercontent.com'
# client.authorization.client_secret = 's8j3VQwCvlyz2Hcpr06xrVfr'
# client.authorization.redirect_uri = 'urn:ietf:wg:oauth:2.0:oob'
# client.authorization.scope = 'https://www.googleapis.com/auth/drive'
# uri = client.authorization.authorization_uri
# Launchy.open(uri)
# $stdout.write "Enter authorization code: "
# client.authorization.code = gets.chomp
# client.authorization.fetch_access_token!
####################################################################################
key = Google::APIClient::KeyUtils.load_from_pkcs12('12355eaee706eb725ff5dd890b5c2bc39d536a53-privatekey.p12', 'notasecret')
client.authorization = Signet::OAuth2::Client.new(
:token_credential_uri => 'https://accounts.google.com/o/oauth2/token',
:audience => 'https://accounts.google.com/o/oauth2/token',
:scope => 'https://www.googleapis.com/auth/prediction',
:issuer => '312062272758-bg7s7ts9f3m11hjetboodre6hfg4qp8q#developer.gserviceaccount.com',
:signing_key => key)
client.authorization.fetch_access_token!
#####################################################################################
# Make an API call
# Insert a file
file = drive.files.insert.request_schema.new({
'title' => 'My document',
'description' => 'A test document',
'mimeType' => 'text/plain'
})
media = Google::APIClient::UploadIO.new('document.txt', 'text/plain')
result = client.execute(
:api_method => drive.files.insert,
:body_object => file,
:media => media,
:parameters => {
'uploadType' => 'multipart',
'alt' => 'json'})
# Pretty print the API result
jj result.data.to_hash
When I run it i got an error
`rescue in rbuf_fill': Timeout::Error (Faraday::Error::TimeoutError)
When I uncomment commented code and comment code between line of ############## It is possible to send a file into gDrive but I must enter the authorization code from web browser.
I want to do it automaticly thats i decided to use gDrive like a Service account
I have tried to increase connection time out by adding lines:
conn = Faraday.default_connection
conn.options[:timeout] = 500
and ofcourse with connection: conn after parametrs in request but i have got another error
`sysread_nonblock': end of file reached
(Faraday::Error::ConnectionFailed)
the (ssl)-certificate is missing.
how to fix: https://gist.github.com/fnichol/867550

Connect Rails 3 to Salesforce/Any other App via OAuth

Has anybody connected to Salesforce through Rails 3 App via oauth? Could you please post code for doing same. I am trying to same but I get some error below is my code
def oauth_client
consumer_key = '....'
consumer_secret = '....'
oauth_options = {
:site => 'https://login.salesforce.com',
:scheme => :body,
:request_token_path => '/_nc_external/system/security/oauth/RequestTokenHandler',
:authorize_path => '/setup/secur/RemoteAccessAuthorizationPage.apexp',
:access_token_path => '/_nc_external/system/security/oauth/AccessTokenHandler',
}
OAuth::Consumer.new consumer_key, consumer_secret, oauth_options
end
def oauth_redirect_uri
uri = URI.parse(request.url)
uri.path = '/sfdc/oauth_callback'
uri.query = nil
# uri = "http://localhost:3000/sfdc/oauth_callback"
uri.to_s
end
def oauth_connect
consumer_key = '...' # from SalesForce
consumer = oauth_client
request_t = consumer.get_request_token
redirect_to request_t.authorize_url(
:redirect_uri => oauth_redirect_uri,
:oauth_consumer_key => consumer_key
)
end
def oauth_callback
access = request_t.get_access_token :oauth_verifier => params[:oauth_verifier]
p access
render :text => access.token
end
Error undefined method get_access_token for #<ActionDispatch::Request:0x12b79f370>. the request variable is nil here. How do I get it back?
The rforce gem has quite a bit of an example that I pasted below. However you might just want to use rforce instead of rolling your own.
def init_server(url)
#url = URI.parse(url)
if (#oauth)
consumer = OAuth::Consumer.new \
#oauth[:consumer_key],
#oauth[:consumer_secret],
{
:site => url,
:proxy => #proxy
}
consumer.http.set_debug_output $stderr if show_debug
#server = OAuth::AccessToken.new \
consumer,
#oauth[:access_token],
#oauth[:access_secret]
class << #server
alias_method :post2, :post
end
else
#server = Net::HTTP.Proxy(#proxy).new(#url.host, #url.port)
#server.use_ssl = #url.scheme == 'https'
#server.verify_mode = OpenSSL::SSL::VERIFY_NONE
# run ruby with -d or env variable SHOWSOAP=true to see SOAP wiredumps.
#server.set_debug_output $stderr if show_debug
end
end

trying to POST with ruby mechanize

I've captured the login HTTP headers using firefox plugin LiveHTTPheaders.
I've found the following url and variables.
POST /login
email=myemail%40gmail.com&password=something&remember=1&loginSubmit=Login
And here's the code I am running:
require 'rubygems'
require 'mechanize'
browser = Mechanize.new
browser.post('http://www.mysite.com/login',
[
["email","myemail%40gmail.com"],
["password","something"],
["remember","1"],
["loginSubmit","Login"],
["url"=>""]
]
) do |page|
puts page.body
end
However, this gives me nothing ! is something wrong with my post parameters ?
post() doesn't take a block. Try this:
page = browser.post('http://www.mysite.com/login', {
"email" => "myemail%40gmail.com",
"password" => "something",
"remember" => "1",
"loginSubmit" => "Login",
"url" => ""
})
edit: changed for accuracy

Resources