How to use Twitter gem in Rails? - ruby

I am planning to use the Twitter gem in my app, but I am stuck trying to figure out what an OAUTH token is, and where can get it. Twitter's documentation has been no help to me so far.
Twitter.configure do |config|
config.consumer_key = YOUR_CONSUMER_KEY
config.consumer_secret = YOUR_CONSUMER_SECRET
config.oauth_token = YOUR_OAUTH_TOKEN
config.oauth_token_secret = YOUR_OAUTH_TOKEN_SECRET
end
Twitter.user
Can anyone gently explain to me what I need to do in order to set this up correctly to use in my app?

You should only need the consumer key and consumer secret. The oauth token and oauth secret are for the non-browser version of the app (I can't remember the actual word) which allows you to have a permanent link to twitter from an account to tweet without authorizing each time.

Go to http://developer.twitter.com/
Register an app (make one up)..
All the authentication information you need will be provided.

Related

Expected top level property 'installed' or 'web' to be present. google-apis-ruby quickstart

I have been attempting to get device information using the google/apis/admin_directory_v1 api.
I found a ruby quickstart that happens to use this exact api in the example. However when I follow the instructions and try to run the script that is listed in the link I get the error ...
"Expected top level property 'installed' or 'web' to be present."
A link to the quickstart is below.
EDITED SORRY I WAS OVER TIRED LOL
https://developers.google.com/admin-sdk/directory/v1/quickstart/ruby
I have been trying to return results from the API all day and it has pushed me to write this post. Please don't attack me I am merely trying to help someone else in the future with this because the documentation is very cavernous for something as simple as api requests?
Anyway I have no idea what the error means or how to proceed. I have fixed enough errors with this situation for one night and now I am just hoping to meet someone else who has traveled this road.
Edited: Sorry to post the wrong link I was too tired. I was never using anything related to the sheets link I must have had the tab open for researched and just pasted the wrong link.
Edited Again: I have gotten a bit further but still no success... Well actually I take that back I am geting a confirmed bearer token back I am just unsure how to use it properly with this api client... The test I am currently working with is below...
require "google/apis/admin_directory_v1"
require "googleauth"
require "googleauth/stores/file_token_store"
require "fileutils"
APPLICATION_NAME = "Directory API Ruby Quickstart".freeze
CREDENTIALS_PATH = "credentials.json".freeze
CUSTOMER_ID = "xxxxxxx".freeze
SCOPE = Google::Apis::AdminDirectoryV1::AUTH_ADMIN_DIRECTORY_USER_READONLY
def authorize
authorizer = Google::Auth::ServiceAccountCredentials.make_creds(
json_key_io: File.open('credentials.json'),
scope: SCOPE)
authorizer.fetch_access_token!
end
# puts authorize
# Initialize the API
service = Google::Apis::AdminDirectoryV1::DirectoryService.new
service.client_options.application_name = APPLICATION_NAME
service.authorization = Google::Auth.get_application_default(SCOPE)
response = service.list_mobile_devices(customer_id: CUSTOMER_ID)
puts response.to_json
This is returning the error below
/var/lib/gems/2.7.0/gems/google-apis-core-0.4.2/lib/google/apis/core/http_command.rb:229:in `check_status': PERMISSION_DENIED: Request had insufficient authentication scopes. (Google::Apis::ClientError)
I would assume that this should be possible with a service account and that I am still making a simple mistake....
The issue you are having is that the Ruby quickstart for Google sheets was designed for use with an installed application.
You are directed to create installed credentials. Here is a video as well How to create Google Oauth2 installed application credentials.json.
Authorization credentials for a desktop application. To learn how to create credentials for a desktop application, refer to Create credentials.
This error message is telling you that you did not create that type of credentials. Did you try to create service account credentials maybe? That wont work with this code.

extracting tweets without oauth

I have tried various ruby codes to extract tweets, i came to know that in order to get tweets i have to create a twitter application and use Oauth for getting consumer key. My question here is can i not access the public tweets without using Oauth since i am working on a project where i have to analyze tweets.
The ruby code that i tried is as follows
require 'tweetstream'
require 'rubygems'
TweetStream.configure do |config|
config.username = 'twitterusername'
config.password = 'twitterpassword'
config.auth_method = :basic
end
#client = TweetStream::Client.new
#client.sample do |status|
puts "#{status.text}"
end
I get Failed to reconnect to twitter error.
There is no access to the twitter api with out Oauth. You will need to create a twitter application in order to request this information from the API.
You can start reading here: Authentication & Authorization

how to authorizate use google-api-ruby-client

i am using google api for ruby, but not know how to start, just give me an ABC example someone, thanks very much?
If you are creating a Service Account application to access Google Analytics.
Register it with Google through https://code.google.com/apis/console.
On API Access tab, click Create client ID, choose Service Account. Store the key file Google will generate, and remember the password for that key.
Here is some code to get you started
require 'rubygems'
require 'google/api_client'
api_client = Google::APIClient.new
path_to_key_file ="/path/to/key/file-privatekey.p12"
passphrase = "google_generated_password"
key = Google::APIClient::PKCS12.load_key(path_to_key_file, passphrase)
Once a key is available, initialize the asserter with your client ID (email in APIs console)
and authorization scopes.
asserter = Google::APIClient::JWTAsserter.new(
'super_long_client_id_from_api_console#developer.gserviceaccount.com',
'https://www.googleapis.com/auth/analytics.readonly',
key)
# To request an access token, call authorize:
api_client.authorization = asserter.authorize()
puts api_client.authorization.access_token
http://code.google.com/p/google-api-ruby-client/wiki/ServiceAccounts
I've answered something similar in a couple of other posts I found that were like this one... so incase its relevant, for ruby, using the google-api-client (for any of the google apis), there's a few ins and outs with authentication when using an api key as opposed to OAuth...
I've outlined this process (using an api key server side) at the code abode.
You have to explicitly set the authorzation param to nil when constructing the client, otherwise the gem tries to use OAuth to authenticate, so if calling from a server using an api key only, you will always get a 401 Unauthorized.
the code abode - google-api-client for ruby

Is it possible to get Gmail oauth or xauth tokens with OmniAuth?

I want to get oauth or xauth tokens from GMail to use with gmail-oauth. I'm thinking of using OmniAuth but it seems not to support GMail yet, which means that with stock OmniAuth is impossible. Is that correct? Am I missing something?
Omniauth has support for both OAuth and OAuth2, which will both allow you to authenticate a google account.
Here are all of the strategies you can use via omniauth:
https://github.com/intridea/omniauth/wiki/List-of-Strategies
Here are the two google OAuth gems:
omniauth-google (OAuth1)
omniauth-google-oauth2 (OAuth2)
As per the documentation of the first gem:
Add the middleware to a Rails app in config/initializers/omniauth.rb:
Rails.application.config.middleware.use OmniAuth::Builder do
provider :google, CONSUMER_KEY, CONSUMER_SECRET
# plus any other strategies you would like to support
end
This is done in addition to setting up the main omniauth gem.
I had trouble, like you, using existing gems with OAuth2 and Gmail since Google's OAuth1 protocol is now deprecated and many gems have not yet updated to use their OAuth2 protocol. I was finally able to get it to work using Net::IMAP directly.
Here is a working example of fetching email from Google using the OAuth2 protocol. This example uses the mail, gmail_xoauth, omniauth, and omniauth-google-oauth2 gems.
You will also need to register your app in Google's API console in order to get your API tokens.
# in an initializer:
ENV['GOOGLE_KEY'] = 'yourkey'
ENV['GOOGLE_SECRET'] = 'yoursecret'
Rails.application.config.middleware.use OmniAuth::Builder do
provider :google_oauth2, ENV['GOOGLE_KEY'], ENV['GOOGLE_SECRET'], {
scope: 'https://mail.google.com/,https://www.googleapis.com/auth/userinfo.email'
}
end
# ...after handling login with OmniAuth...
# in your script
email = auth_hash[:info][:email]
access_token = auth_hash[:credentials][:token]
imap = Net::IMAP.new('imap.gmail.com', 993, usessl = true, certs = nil, verify = false)
imap.authenticate('XOAUTH2', email, access_token)
imap.select('INBOX')
imap.search(['ALL']).each do |message_id|
msg = imap.fetch(message_id,'RFC822')[0].attr['RFC822']
mail = Mail.read_from_string msg
puts mail.subject
puts mail.text_part.body.to_s
puts mail.html_part.body.to_s
end

What's the simplest sample program for twitter4r which is likely to work?

I'm trying the following sample code, and failing (the uid and password I'm using are valid). Is there something I'm missing, or a simpler example I can try?
testing.rb:
require('rubygems')
gem('twitter4r','>=0.2.0')
require('twitter')
client = Twitter::Client.new(:login => 'uid', :password => 'password')
ARGV.each do |a|
#message = "#{a}"
end
status = client.status(:post, #message)
prompt> ruby testing.rb "test"
/Library/Ruby/Gems/1.8/gems/twitter4r-0.6.0/lib/twitter/client/base.rb:120:in
`raise_rest_error': Unauthorized
(Twitter::UnauthorizedError) from
/Library/Ruby/Gems/1.8/gems/twitter4r-0.6.0/lib/twitter/client/base.rb:125:in
`handle_rest_response' from
/Library/Ruby/Gems/1.8/gems/twitter4r-0.6.0/lib/twitter/client/base.rb:23:in `rest_oauth_connect' from
/Library/Ruby/Gems/1.8/gems/twitter4r-0.6.0/lib/twitter/client/status.rb:42:in `status' from testing.rb:11
#blueberryfields you will need to use the OAuth API that Twitter4R v0.5.0+ supports. This is due to Twitter.com mandating OAuth authentication as of August 2010. Supplying the login and password of your username is no longer supported either via Twitter4R, twitter.com or any other Twitter API client.
There is a fantastic tutorial on using OAuth with Twitter4R at this blog:
http://blog.monnet-usa.com/?p=342
HTH,
#SusanPotter -- Author of Twitter4R
PS Also check out #t4ruby for updates to Twitter4R
Twitter doesn't allow basic Auth (username+password) logins through their API anymore.
You should look for a method that supports OAuth-based login.
You'll need to fetch OAuth keys for your application, which can be done from the following links. The first link allows you to enroll a new application, the second one allows you to see what applications you've registered.
New Twitter Application # dev.twitter.com
Twitter Applications (Existing) # dev.twitter.com
A more in-depth guide is available at the following link. You will want to read this as OAuth requires at least two steps to authenticate before you can use the twitter API.
Authenticating Requests with OAuth

Resources