Integrating Google+ into Rails app (execute not working) - ruby

I am trying to display data from Google+ by adapting this to rails https://github.com/google/google-api-ruby-client I created a rails app, made a few tweaks to get oauth working with the client_secret.json, but when the request executes, nothing displays.
welcome_controller:
class WelcomeController < ApplicationController
def index
require 'google/api_client'
require 'google/api_client/client_secrets'
require 'google/api_client/auth/installed_app'
$credentials = Google::APIClient::ClientSecrets.load
# Initialize the client.
$authorization = Signet::OAuth2::Client.new(
:authorization_uri => $credentials.authorization_uri,
:token_credential_uri => $credentials.token_credential_uri,
:client_id => $credentials.client_id,
:client_secret => $credentials.client_secret,
:redirect_uri => $credentials.redirect_uris.first,
:scope => 'https://www.googleapis.com/auth/plus.login')
#client = Google::APIClient.new(
:application_name => 'X',
:application_version => 'X'
)
# Initialize Google+ API. Note this will make a request to the
# discovery service every time, so be sure to use serialization
# in your production code. Check the samples for more details.
#plus = #client.discovered_api( "plus", "v1" )
# Make an API call.
#google_plus_info = #client.execute(
:api_method => #plus.activities.list,
:parameters => {'collection' => 'public', 'userId' => 'my_num_here'}
)
#puts #google_plus_info.data #tried this
render plain: "test: #{#google_plus_info.data}" #tried this too, just returns the call name
end
end
Anyone know why I'm getting it in this case, according to the API (i thought) this was a public call? NOTE: I changed this post in response to suggestions to show my current state of work.

Try replacing $authorization.execute with plus.execute
Take a look at https://github.com/google/google-api-ruby-client-samples/tree/master/googleplus
Here's a snippet from my working code:
#client = Google::APIClient.new(
:application_name => 'X',
:application_version => 'X'
)
#client.authorization.update_token!(:access_token => 'X', :refresh_token => 'X')
#plus = #client.discovered_api( "plus", "v1" )
#google_plus_info = #client.execute(
:api_method => #plus.people.get,
:parameters => {'collection' => 'public', 'userId' => 'me'}
)

Related

Oauth2 error with MapMyFitness API

I'm trying to use the MapMyFitness API (www.mapmyapi.com) with Ruby on Rails 3.2 and the oauth2 gem. First, my app generates the auth_url in "get_auth_url". The browser then navigates to it and a callback is returned to "mapmyfitness_callback" once authenticated. The "mapmyfitness_callback" also gets the list of "workouts" and those are displayed in the browser.
The problem is when the user selects a workout to download. To retrieve the selected workout, I call "get_workout". However, I'm having difficulties getting the appropriate token for the request.
The line below crashes:
workout_data = access_token.get('/v7.0/workout/' + workout_id, :params => { 'field_set' => 'time_series' }, :headers => {'Api-Key' => ENV['MMF_API_KEY'], 'Authorization' => auth_token}).body
with: OAuth2::Error (:
{"oauth1_error":"Malformed authorization header","oauth1_error_code":"OAUTH1:UNKNOWN"}):
app/controllers/telemetry_controller.rb:60:in `get_workout'
The entire controller code:
require 'oauth2'
class TelemetryController < ApplicationController
def get_auth_url
auth_url = mmf_client.auth_code.authorize_url(:redirect_uri => 'http://localhost:3000/telemetry/mapmyfitness_callback')
respond_to do |format|
format.json{ render :json => {:auth_url => auth_url}.to_json }
end
end
def mapmyfitness_callback
# Get user
#code = params[:code]
token = mmf_client.auth_code.get_token(#code, :redirect_uri => 'http://localhost:3000/telemetry/mapmyfitness_callback', :headers => {'Api-Key' => ENV['MMF_API_KEY']})
mmf_user = JSON.parse(token.get('/v7.0/user/self', :headers => {'Api-Key' => ENV['MMF_API_KEY'], 'Authorization' => #code}).body)
mmf_user_id = mmf_user['id']
#auth_token = token.token
# Get workouts
mmf_workouts = JSON.parse(token.get('/v7.0/workout', :params => { 'user' => mmf_user_id }, :headers => {'Api-Key' => ENV['MMF_API_KEY'], 'Authorization' => #code}).body)
#workout_list = Array.new
mmf_workouts['_embedded']['workouts'].each do |workout|
workout_data = {:name => workout['name'],
:id => workout['_links']['self'][0]['id']}
#workout_list.push(workout_data)
end
render :layout => false
end
def get_workout
code = params[:code]
auth_token = params[:auth_token]
access_token = OAuth2::AccessToken.new(mmf_client, auth_token, {
:mode => :query,
:param_name => "oauth2_access_token",
})
puts access_token.to_yaml
# Get workout
workout_id = params[:workout_id]
workout_data = access_token.get('/v7.0/workout/' + workout_id, :params => { 'field_set' => 'time_series' }, :headers => {'Api-Key' => ENV['MMF_API_KEY'], 'Authorization' => auth_token}).body
respond_to do |format|
format.json{ render :json => {:mmf_workout_data => workout_data}.to_json }
end
end
private
def mmf_client
client = OAuth2::Client.new(
ENV['MMF_API_KEY'],
ENV['MMF_SECRET_KEY'],
:authorize_url => "https://www.mapmyfitness.com/v7.0/oauth2/authorize/",
:token_url => "https://oauth2-api.mapmyapi.com/v7.0/oauth2/access_token/",
:site => "https://oauth2-api.mapmyapi.com"
)
end
end
I figured it out. get_workout needs to be like this:
def get_workout
auth_token = params[:auth_token]
token = OAuth2::AccessToken.new(mmf_client, auth_token)
# Get workout
workout_id = params[:workout_id]
workout_data = token.get('/v7.0/workout/' + workout_id, :params => { 'field_set' => 'time_series' }, :headers => {'Api-Key' => ENV['MMF_API_KEY'], 'Authorization' => auth_token}).body
respond_to do |format|
format.json{ render :json => {:mmf_workout_data => workout_data}.to_json }
end
end
The problem with your call to AccessToken.new is the "param_name".
from the docs (http://www.rubydoc.info/github/intridea/oauth2/ebe4be038ec14b349682/OAuth2/AccessToken)
:param_name (String) — default: 'bearer_token' — the parameter name to use for transmission of the Access Token value in :body or :query transmission mode
The default value is "bearer_token", as it should be, but, here, you were changing it to "oauth2_access_token".

Binding to LDAP service

I'm using Ruby and trying to bind an LDAP server. The Ruby documentation seems to be very vague here and it's not obvious what I need to do after the following:
>> require 'uri'
=> true
>> newuri = URI::LDAP.build({:host => '10.1.1.1', :dc => 'cjndemo' , :dc => 'com', :user =>'admin', :password => 'Passw0rd'})
=> #<URI::LDAP:0x007fea9d0cef60 URL:ldap://10.1.1.1?>
What do I need to do to bind then query my LDAP service?
URI::LDAP is only for parsing and generating LDAP URIs. If you want to query the LDAP server you need to use a different tool like net-ldap or ruby-ldap.
An example of binding with simple authentication using net-ldap:
require 'net/ldap'
ldap = Net::LDAP.new(:host => '10.1.1.1',
:auth => {
:method => :simple,
:username => 'cn=admin,dc=cjndemo,dc=com',
:password => 'Passw0rd'
})
if ldap.bind
base = 'dc=cjndemo,dc=com'
filter = Net::LDAP::Filter.eq('objectclass', '*')
ldap.search(:base => base, :filter => filter) do |object|
puts "dn: #{object.dn}"
end
else
# authentication error
end

How do I correctly call Magento SOAP API with Ruby Savon for Category Product Links?

I am trying to call the catalog_product_link.list API method using Savon. However, I keep receiving the error Error cannot find parameter.
Here is what I am using, though I have tried several variations of the call and still cannot get it to go through correctly:
client = Savon.client(wsdl: 'http://localhost/index.php/api/soap/?wsdl')
response = client.call(:login){message(username: 'user', apiKey: 'key')}
session = response.body[:login_response][:login_return]
#These all do not work
client.call(:call){message(:session => session, :method => 'catalog_product_link.list', :type => 'up_sell', :productId => '166')}
client.call(:call){message(:session => session, :method => 'catalog_product_link.list', :type => 'up_sell', :product => '166')}
client.call(:call){message(:sessionId => session, :resourcePath => 'catalog_product_link.list', :args => {:type => 'up_sell', :product => '166'})}
client.call(:call){message(:sessionId => session, :resourcePath => 'catalog_product_link.list', :args => {:type => 'up_sell', :productId => '166'})}
client.call(:call){message(:sessionId => session, :resourcePath => 'catalog_product_link.list', :arguments => {:type => 'up_sell', :product => '166'})}
Is there a different way to format to get this to work?
UPDATE: If I try removing the type parameter, it gives the error Given invalid link type, so it appears it does not like something about multiple parameters.
response = client.call(:call){message(:session => session, :method => 'catalog_product_link.list', :product => '166')}
I was able to get this to work using Builder:
class ServiceRequest
def initialize(session, type, product)
#session = session
#type = type
#product = product
end
def to_s
builder = Builder::XmlMarkup.new()
builder.instruct!(:xml, encoding: "UTF-8")
builder.tag!(
"env:Envelope",
"xmlns:env" => "http://schemas.xmlsoap.org/soap/envelope/",
"xmlns:ns1" => "urn:Magento",
"xmlns:ns2" => "http://xml.apache.org/xml-soap",
"xmlns:xsd" => "http://www.w3.org/2001/XMLSchema",
"xmlns:xsi" => "http://www.w3.org/2001/XMLSchema-instance"
) do |envelope|
envelope.tag!("env:Body") do |body|
body.tag!("ns1:call") do |call|
builder.sessionId(#session, "xsi:type" => "xsd:string")
builder.resourcePath("catalog_product_link.list", "xsi:type" => "xsd:string")
builder.args("xsi:type" => "ns2:Map") do |args|
args.item do |item|
item.key("type", "xsi:type" => "xsd:string")
item.value(#type, "xsi:type" => "xsd:string")
end
args.item do |item|
item.key("product", "xsi:type" => "xsd:string")
item.value(#product, "xsi:type" => "xsd:string")
end
end
end
end
end
builder.target!
end
end
client.call(:call, xml: ServiceRequest.new(session, 'up_sell', '166').to_s)
Thanks to #rubiii for the direction.

Using Typhoeus to POST an array to a URL

I'm using Typhoeus to post a hash to my API url. It's actually an array containing a set of hashes. Here's effectively what I'm doing:
companies = Array.new
company = { 'name' => 'Company 1' , 'company_url' => 'http://company.com' }
companies.push(company)
company2 = {'name' => 'Company 2' , 'company_url' => 'http://company2.com' }
companies.push(company2)
request = Typhoeus::Request.post("http://myapi.com/1.0/startups/create_batch",
:username => 'user',
:password => 'password',
:auth_method => :basic,
:params => {'companies' => companies} )
print "Create_batch response "+request.body
Once I run the script I get the output which states "Create_batch response Disallowed Key Characters.". I'm not sure what it's referencing at this point. I've looked over the text output of what print companies shows up but I don't see any strange code.
Anybody have any insights on what I should do?

Does the twilio-ruby gem take parameters other than 'from', 'to', and 'url' when making calls?

Looking at https://github.com/twilio/twilio-ruby/blob/master/lib/twilio-ruby/rest/calls.rb, it appears that only 'from', 'to', and 'url' are used. How do I pass a value for 'IfMachine'? For example, the following doesn't seem to work.
# set ACCOUNT_SID and AUTH_TOKEN
twilioClient = Twilio::REST::Client.new(ACCOUNT_SID, AUTH_TOKEN)
twilioAccount = twilioClient.account
twilioAccount.calls.create({
:from => 'from_number',
:to => 'to_number',
:url => '/url',
'IfMachine' => 'Hangup'
})
# IfMachine parameter is not passed in the above request
Setting 'IfMachine' => 'hangup' works for me. I think the Twilio API is case-sensitive with respect to parameter values. So 'hangup' would work but 'Hangup' probably won't.
Here's my twilio-ruby session showing that the parameters are passed correctly:
irb(main):002:0> c.account.calls.create :from => '2158377932', :to => '4159334335', :url => 'http://demo.twilio.com/welcome/voice', 'IfMachine' => 'continue'
warning: peer certificate won't be verified in this SSL session
=> <Twilio::REST::Call #uri=/2010-04-01/Accounts/AC8faaf6f7efb9dfd60bc0ff3aa7fa00be/Calls/CA0165c3b35c934ed5a2b7a87f343544ff>
irb(main):003:0> c.last_request
=> #<Net::HTTP::Post POST>
irb(main):004:0> req = c.last_request
=> #<Net::HTTP::Post POST>
irb(main):005:0> req.body
=> "IfMachine=continue&To=4159334335&Url=http%3a%2f%2fdemo.twilio.com%2fwelcome%2fvoice&From=2158377932"
I believe if you set it as a symbol instead it should work:
# set ACCOUNT_SID and AUTH_TOKEN
twilioClient = Twilio::REST::Client.new(ACCOUNT_SID, AUTH_TOKEN)
twilioAccount = twilioClient.account
twilioAccount.calls.create({
:from => 'from_number,
:to => 'to_number',
:url => '/url',
:if_machine => 'Hangup'
})

Resources