cannot create wall posts with fb_graph - ruby

i am attempting to create a test user, and then write on that user's
wall. here is my code followed by the error i get (i'm using ruby and the gem fb_graph):
app = FbGraph::Application.new(config[:client_id], :secret =>
config[:client_secret])
user1 = app.test_user!(:installed => true, :permissions
=> :publish_stream)
user2 = app.test_user!(:installed => true, :permissions
=> :publish_stream)
me = FbGraph::User.me(ACCESS_TOKEN)
me.feed!(:message => "Testing")
FbGraph::Unauthorized: FbGraph::Unauthorized from /Library/Ruby/Gems/
1.8/gems/fb_graph-1.9.4/lib/fb_graph/node.rb:126:in
'handle_httpclient_error'
from /Library/Ruby/Gems/1.8/gems/fb_graph-1.9.4/lib/fb_graph/node.rb:
115:in 'handle_response'
from /Library/Ruby/Gems/1.8/gems/fb_graph-1.9.4/lib/fb_graph/node.rb:
48:in 'post'
from /Library/Ruby/Gems/1.8/gems/fb_graph-1.9.4/lib/fb_graph/
connections/feed.rb:15:in `feed!'
from (irb):90
publish_stream should give me the proper permissions to write to the
wall, but as you can see, it doesn't.
any suggestions?
thanks for any help.

Are you sure your access token is valid? Facebook needs a valid access token or it will not allow you to use the user's permissions, even if he granted them to you on facebook.

Related

Ruby : SoftLayer API : getPendingEvents fails to show many relational properties

I'm trying to make a softlayer API call using Ruby to see upcoming maintenance and the machines that may be effected by the maintenance. I have a few questions but I'm running into an issue seeing many of the relational properties documented here:
http://sldn.softlayer.com/reference/datatypes/SoftLayer_Notification_Occurrence_Event
Here is my simple program:
require 'rubygems'
require 'softlayer_api'
require 'pp'
client = SoftLayer::Client.new(:username => user, :api_key => api_key, :timeout => 99999999)
account = client['Account'].object_mask("mask[pendingEventCount]").getObject()
pending_event_count = account["pendingEventCount"]
current_time = Time.now.to_i
for i in 0..(pending_event_count/30.0).ceil - 1
list_of_pending_events = client['Account'].result_limit(i*30,30).object_mask("mask[id, startDate, endDate, recoveryTime, subject, summary]").getPendingEvents
for x in 0..list_of_pending_events.length - 1
start_time = DateTime.parse(list_of_pending_events[x]['startDate']).to_time.to_i
if start_time > current_time
pp list_of_pending_events[x]
end
end
end
The above works, but if I try to add a relational property to the mask, such as "impactedResources" it will fail saying that property does not belong to SoftLayer_Notification_Occurrence_Event. Can someone help explain why this, and many other, relational properties are not valid in the above call?
Also, two quick other questions on this topic:
1) Why do some of the results in getPendingEvents have start AND end times in the past? And why do some have a missing end time altogether? Notice I'm checking if the start time is greater than the current time as there seems to be old maintenance data in the results.
2) Am I taking the right approach for getting upcoming maintenance and figuring out machines that will be impacted? (Using getPendingEvents and then the 'impactedResources' property)
I used your code and I added the "impactedResources" to the object mask and it worked fine. You may be getting the issue, because your API user does not have enough permissions, I recomend you try with the master user.
regarding to your other questions:
1.- When I ran your code I got only 3 events whose startDate is greater than the current time, so it worked fine for me. If you still are getting that issue you can try using objectFilters.
require 'rubygems'
require 'softlayer_api'
require 'pp'
client = SoftLayer::Client.new(:username => user, :api_key => apikey, :timeout => 99999999)
object_filter = SoftLayer::ObjectFilter.new
object_filter.set_criteria_for_key_path('pendingEvents.startDate', 'operation' => 'greaterThanDate',
'options' => [{
'name' => 'date',
'value' => ['9/8/2016']
}])
list_of_pending_events = client['Account'].object_filter(object_filter).object_mask("mask[id, startDate, endDate, recoveryTime, subject, summary]").getPendingEvents
pp list_of_pending_events
2.- Yes, that approach wil work.
Regards

Oauth2 token not working for gmail_xoauth gem

I'm currently getting a token via the omniauth-google-oauth2 gem per the following: https://github.com/zquestz/omniauth-google-oauth2
I store the token that comes back from the auth_hash.
I then try to use the token by calling:
require 'gmail_xoauth'
imap = Net::IMAP.new('imap.gmail.com', 993, usessl = true, certs = nil, verify = false)
imap.authenticate('XOAUTH2', 'myemail#gmail.com', Token.last)
Problem is that I get an error:
[8] pry(main)> imap.authenticate('XOAUTH2', 'myemail#gmail.com', Token.last)
Token Load (0.6ms) SELECT "tokens".* FROM "tokens" ORDER BY "tokens"."id" DESC LIMIT 1
Net::IMAP::NoResponseError: Invalid credentials (Failure)
from /Users/username/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/net/imap.rb:1171:in `get_tagged_response'
Ok I took a look at google-api-client and I started to use that a little more. Seems like the best solution at the moment is to do the following:
create an options hash that includes the gmail parameters and the gmail api_method
use the service you initialize with your access_token to create your query in the options hash
Below you can see a rough example that you can use
client = Google::APIClient.new
client.authorization.access_token = token
service = client.discovered_api 'gmail'
options = {parameters: {'userId' => 'email#gmail.com'}, api_method: service.users.messages.list}
client.execute(options)
I mean this is pretty clunky and should be DRY'd up. (Hopefully google creates a better gem around this)
The solution was to update the scope of omniauth for gmail.
Rails.application.config.middleware.use OmniAuth::Builder do
provider :google_oauth2, ENV['GOOGLE_CLIENT_ID'], ENV['GOOGLE_CLIENT_SECRET'],
{
scope: [
'https://mail.google.com/','https://www.googleapis.com/auth/userinfo.email'
]
}
end

What is the proper way to use google's api client in ruby to get Gmail messages?

I've setup a Service Account in my google developer console and I've turned ON the Gmail API. Using the various examples for ruby, I came up with the following script in an attempt to get at my emails:
#!/usr/bin/ruby
require 'google/api_client'
SERVACC = "abcdefg#developer.gserviceaccount.com" # My Service Account's CLIENT ID
GAPMAIL = "myapp#mydomain.com" #gApps account
PKCFILE = "myapp.p12" # Downloaded S.A. cred file
GMSCOPE = "https://www.googleapis.com/auth/gmail.readonly"
TOKEURI = "https://accounts.google.com/o/oauth2/token"
options = {:application_name => 'gmail', :application_version => 'v1'}
Gclient = Google::APIClient.new( options )
Gclient.authorization = Signet::OAuth2::Client.new(
:token_credential_uri => TOKEURI,
:audience => TOKEURI,
:scope => GMSCOPE,
:issuer => SERVACC,
:signing_key => Google::APIClient::PKCS12.load_key(PKCFILE, 'notasecret')
)
Gclient.authorization.fetch_access_token!
result = Gclient.execute!(
:api_method => Gclient.discovered_api('gmail').users.messages.list,
:parameters => {:userId => GAPMAIL}
)
Unfortunately, it bombs with a Backend Error:
~/.rvm/gems/ruby-2.1.4/gems/google-api-client-0.8.2/lib/google/api_client.rb:654:in `block (2 levels) in execute!': Backend Error (Google::APIClient::ServerError)
from /Users/bbialek/.rvm/gems/ruby-2.1.4/gems/retriable-1.4.1/lib/retriable/retry.rb:27:in `perform'
from /Users/bbialek/.rvm/gems/ruby-2.1.4/gems/retriable-1.4.1/lib/retriable.rb:15:in `retriable'
from /Users/bbialek/.rvm/gems/ruby-2.1.4/gems/google-api-client-0.8.2/lib/google/api_client.rb:635:in `block in execute!'
from /Users/bbialek/.rvm/gems/ruby-2.1.4/gems/retriable-1.4.1/lib/retriable/retry.rb:27:in `perform'
from /Users/bbialek/.rvm/gems/ruby-2.1.4/gems/retriable-1.4.1/lib/retriable.rb:15:in `retriable'
from /Users/bbialek/.rvm/gems/ruby-2.1.4/gems/google-api-client-0.8.2/lib/google/api_client.rb:626:in `execute!'
from stack.rb:22:in `<main>'
I actually see the Server errors (5xx) count going up under the API's usage, so I can't be too far of. What am I missing?
Just in case anyone found this while struggling away....
Here is a working implementation. Hope it helps.
You'll need to have registered the app in your google developers console..etc and, importantly, granted the appropriate scopes to the service account in your google apps domain (the scope below is the full access one).
google_api_key = #Your API Key - here it's stored as a string, but you might want to use the file version
google_api_email = #The email id attached to your service account
account = #the email account you want to use
application_name = # a name for your app
application_version = #version for your app
#google_mail_session = Google::APIClient.new(application_name: application_name, application_version: application_version)
key = Google::APIClient::KeyUtils.load_from_pem(
google_api_key,
'notasecret')
asserter = Google::APIClient::JWTAsserter.new(
google_api_email,
['https://mail.google.com/'],
key
)
#google_mail_session.authorization = asserter.authorize(account)
# Leave the account details out for a generic authorization, you'll need to specify the account when you make a call to the API.
#gmail_api = #google_mail_session.discovered_api('gmail', 'v1')
An example call would be
response = #google_mail_session.execute(
:api_method => #gmail_api.users.messages.list,
:parameters => {:userId => 'me'}) # you can use the standard address here if you don't want to authorize to a specific account above
This took me a long, long time to get working where I largely felt like I was shooting in the dark. Why google make it so damn difficult is beyond me....

How to display linkedin profile information in Rails

I'm working on an app that will have a linkedin sign in button. Once the user signs in using their linkedin in username and password. I want to display their information on the home page.
Currently I'm using 'omniauth', 'omniauth-linkedin-oauth2' to authenticate the user.
The person working on this before me completed the authentication process but I can't understand how to display the users info. The authentication was implemented by following RailsCast #235 & #236 Omniauth Part 1 and 2.
This is the omniauth.rb file.
Rails.application.config.middleware.use OmniAuth::Builder do
provider :linkedin, 'LINKEDIN_KEY', 'LINKEDIN_SECRET', :scope => 'r_fullprofile r_emailaddress r_network', :fields => ['id', 'email-address', 'first-name', 'last-name']
end
I want to display all the fields from the omniauth.rb file.
I understand its a really silly issue but I'm really new to Ruby on Rails so I'd greatly appreciate it if someone can guide me through the process.
Based on the Authentications Controller in Part 2
You can get the fields from the omniauth hash:
omniauth = request.env["omniauth.auth"]
first_name = omniauth[:info][:first_name]
last_name = omniauth[:info][:last_name]
summary = omniauth[:extra][:raw_info][:summary]
headline = omniauth[:extra][:raw_info][:headline]
image = omniauth[:info][:image]
email = omniauth[:info][:email]
token = omniauth[:credentials][:token]
secret = omniauth[:credentials][:secret]
profile_url = omniauth[:info][:urls][:public_profile]
Those are the basic info you need from the authentication hash, if you need more data, you can use the following gem (using the user's token):
gem 'linkedin-oauth2', '~> 0.1.1'

Using Ruby + OAuth to access Yelp API

I just getting started with OAuth, and I tried to make a small client to connect to some webservices... I tried twitter and it worked like a charm, however, I also tried to access Yelp V2 API (following their Python example) but I always get back as an answers:
HTTP 400 Bad Request
Missing parameter: oauth_consumer_key
Here's my code:
require 'rubygems'
require 'oauth'
CONSUMER_KEY = "MY_CONSUMER_KEY"
SECRET = "MY_CONSUMER_SECRET"
TOKEN = "MY_TOKEN"
TOKEN_SECRET = "MY_TOKEN_SECRET"
consumer = OAuth::Consumer.new( CONSUMER_KEY,SECRET, {:site => "http://api.yelp.com", :signature_method => "HMAC-SHA1", :scheme => :header})
access_token = OAuth::AccessToken.new( consumer, TOKEN,TOKEN_SECRET)
p access_token.get("/v2/search?location=new+york").body
Regardless to say, that code works with twitter API without any problem (I actually followed twitter's example code)
Cheers and thanks in advance,
Ze
Use :query_string instead of :header and everything will work (at least for me).
Same code, using Signet:
require 'signet/oauth_1/client'
client = Signet::OAuth1::Client.new(
:consumer_key => 'MY_CONSUMER_KEY',
:consumer_secret => 'MY_CONSUMER_SECRET',
:access_token_key => 'MY_TOKEN_KEY',
:access_token_secret => 'MY_TOKEN_SECRET'
)
response = client.fetch_protected_resource(
:uri => 'http://api.yelp.com/v2/search?location=new+york'
)
# The Rack response format is used here
status, headers, body = response
p body
As per the Yelp documentation, the OAuth parameters do not have to be passed in the query string. The fact that the accepted answer resolved the issue indicates to me that there's probably a bug in the oauth gem causing this.

Resources