How to make request by Octokit client - ruby

I'm using token to access github api by Octokit client.
client = Octokit::Client.new(access_token: TOKEN)
It seems that is ok:
client.rate_limit
=> #<struct Octokit::RateLimit
limit=5000,
remaining=4998,
resets_at=2013-11-25 03:38:41 +0200,
resets_in=3533>
So now I want to get some info
repo = client.repo 'rails/rails'
repo.rels[:events]
repo.rels[:events].get.data
But when I'm getting next page
repo.rels[:events].get[:next]
I'm hitting the rate limit in 60 requests per hour.
It seems that next requests are not authorized by token.
How to make all request be authorized by token?

Maybe your token has been expired or your client variable lost scope.
Create a initializers/octokit.rb with authentication:
Octokit.configure do |c|
c.client_id = ENV['GITHUB_ID']
c.client_secret = ENV['GITHUB_SECRET']
end
I chose to do by id and secret.
And make your requests with:
repo = Octokit.repo 'rails/rails'
After create the initializer, you can test in rails c:
> Octokit.rate_limit
=> #<struct Octokit::RateLimit limit=5000, remaining=4927, resets_at=2016-04-22 12:24:52 -0300, resets_in=2102>

Taken from the Octokit documentation:
Note: While Octokit auto pagination will set the page size to the
maximum 100, and seek to not overstep your rate limit, you probably
want to use a custom pattern for traversing large lists.

Related

Generate expiring activator token or a key hash in rails manually

I'm trying to verify a link that will expire in a week. I have an activator_token stored in the database, which will be used to generate the link in this format: http://www.example.com/activator_token. (And not activation tokens generated by Devise or Authlogic.)
Is there a way to make this activator token expire (in a week or so) without comparing with updated_at or some other date. Something like an encoded token, which will return nil when decoded after a week. Can any existing modules in Ruby do this? I don't want to store the generated date in the database or in an external store like Redis and compare it with Time.now. I want it to be very simple, and wanted to know if something like this already exists, before writing the logic again.
What you want to use is: https://github.com/jwt/ruby-jwt .
Here is some boilerplate code so you can try it out yourself.
require 'jwt'
# generate your keys when deploying your app.
# Doing so using a rake task might be a good idea
# How to persist and load the keys is up to you!
rsa_private = OpenSSL::PKey::RSA.generate 2048
rsa_public = rsa_private.public_key
# do this when you are about to send the email
exp = Time.now.to_i + 4 * 3600
payload = {exp: exp, discount: '9.99', email: 'user#example.com'}
# when generating an invite email, this is the token you want to incorporate in
# your link as a parameter
token = JWT.encode payload, rsa_private, 'RS256'
puts token
puts token.length
# this goes into your controller
begin
#token = params[:token]
decoded_token = JWT.decode token, rsa_public, true, { :algorithm => 'RS256' }
puts decoded_token.first
# continue with your business logic
rescue JWT::ExpiredSignature
# Handle expired token
# inform the user his invite link has expired!
puts "Token expired"
end

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

How do you save a persistent session with a cookie in Ruby?

All I'm looking for is something very simple. I want to check if the client has my cookie in their browser. If so then to load the last session ID from the cookie and access the session from the server side. If not I want to create the server side session and store the session id to the cookie.
So my question is two parts. What parts of the session code/variable/ID is relevant to retrieve it in the future? And what's the simple method for achieving a continuous session via cookie/session?
I am not using rails. It's a standard CGI script.
#!/usr/bin/ruby
require 'cgi'
require 'cgi/session'
require 'cgi/session/pstore'
cgi = CGI.new("html4")
# !! TODO !! if cookie has "session_id" then open sess from "session_id"
sess = CGI.Session.new( cgi,
'database_manager' => CGI::Session::PStore, # use PStore
'session_key' => '_rb_sess_id', # custom session key
'session_expires' => Time.now + 30 * 60, # 30 minute timeout
'prefix' => 'pstore_sid_')
if sess.has_key? "friend_list"
#friend_list = sess['friend_list']
sess['access_count'] += 1
else
#friend_list = JSON.parse( IO.read( "fbget.json" ) )
sess['friend_list'] = #friend_list
sess['access_count'] = 1
end
I wanted to save the json list on the server side via a session instance. I figure putting that in a cookie would be a very bad security mistake.
Through my searching online I haven't found any non-rails info on saving session access info via the cookie. Only how to use each individually.

Generating Paypal Signature, 'X-PAYPAL-AUTHORIZATION' in Ruby

Is there any library in Ruby that generates the Signature, 'X-PAYPAL-AUTHORIZATION' header that is required to make calls on behalf of the account holder who has authorized us through the paypal Permissions API.
I am done with the permissions flow and get the required access token, tokenSecret. I feel I am generating the signature incorrectly as all my calls with the the generated 'X-PAYPAL-AUTHORIZATION' fail. They give the following errors:
For NVP call I get:
You do not have permissions to make this API call
And for the GetBasicPersonalData call I get:
Authentication failed. API credentials are incorrect.
Has anyone gone through this in Ruby? What is best way to generate signature. Paypal has just provided some SDK in Paypal, Java, but not the algorithm to generate signature.
Thanks,
Nilesh
Take a look at the PayPal Permissions gem.
https://github.com/moshbit/paypal_permissions
Specifically lib/paypal_permissions/x_pp_authorization.rb
require 'cgi'
require 'openssl'
require 'base64'
class Hash
def to_paypal_permissions_query
collect do |key, value|
"#{key}=#{value}"
end.sort * '&'
end
end
module ActiveMerchant #:nodoc:
module Billing #:nodoc:
module XPPAuthorization
public
def x_pp_authorization_header url, api_user_id, api_password, access_token, access_token_verifier
timestamp = Time.now.to_i.to_s
signature = x_pp_authorization_signature url, api_user_id, api_password, timestamp, access_token, access_token_verifier
{ 'X-PAYPAL-AUTHORIZATION' => "token=#{access_token},signature=#{signature},timestamp=#{timestamp}" }
end
public
def x_pp_authorization_signature url, api_user_id, api_password, timestamp, access_token, access_token_verifier
# no query params, but if there were, this is where they'd go
query_params = {}
key = [
paypal_encode(api_password),
paypal_encode(access_token_verifier),
].join("&")
params = query_params.dup.merge({
"oauth_consumer_key" => api_user_id,
"oauth_version" => "1.0",
"oauth_signature_method" => "HMAC-SHA1",
"oauth_token" => access_token,
"oauth_timestamp" => timestamp,
})
sorted_query_string = params.to_paypal_permissions_query
base = [
"POST",
paypal_encode(url),
paypal_encode(sorted_query_string)
].join("&")
base = base.gsub /%([0-9A-F])([0-9A-F])/ do
"%#{$1.downcase}#{$2.downcase}" # hack to match PayPal Java SDK bit for bit
end
digest = OpenSSL::HMAC.digest('sha1', key, base)
Base64.encode64(digest).chomp
end
# The PayPalURLEncoder java class percent encodes everything other than 'a-zA-Z0-9 _'.
# Then it converts ' ' to '+'.
# Ruby's CGI.encode takes care of the ' ' and '*' to satisfy PayPal
# (but beware, URI.encode percent encodes spaces, and does nothing with '*').
# Finally, CGI.encode does not encode '.-', which we need to do here.
def paypal_encode str
s = str.dup
CGI.escape(s).gsub('.', '%2E').gsub('-', '%2D')
end
end
end
end
Sample parameters:
url = 'https://svcs.sandbox.paypal.com/Permissions/GetBasicPersonalData'
api_user_id = 'caller_1234567890_biz_api1.yourdomain.com'
api_password = '1234567890'
access_token = 'YJGjMOmTUqVPlKOd1234567890-jdQV3eWCOLuCQOyDK1234567890'
access_token_verifier = 'PgUjnwsMhuuUuZlPU1234567890'
The X-PAYPAL-AUTHORIZATION header [is] generated with URL "https://svcs.paypal.com/Permissions/GetBasicPersonalData". (see page 23, and chapter 7, at the link)
NVP stating "You do not have permissions to make this API call" means your API credentials are correct, just that your account does not have permission for the particular API you are trying to call. Something between the two calls you are submitting is not using the same API credentials.
For NVP call I get:
What NVP call?
TransactionSearch (see comments below)
Also, if you haven't already done so, you will want to use the sandbox APP-ID for testing in the sandbox, and you will need to apply for an app-id with Developer Technical Services (DTS) at PayPal to get an App-ID for live.
EDIT:
To use the TransactionSearch API, all you should be submitting is below. You do not need to specify any extra headers.
USER=xxxxxxxxxxxxxxxxxx
PWD=xxxxxxxxxxxxxxxxxx
SIGNATURE=xxxxxxxxxxxxxxxxxx
METHOD=TransactionSearch
VERSION=86.0
STARTDATE=2009-10-11T00:00:00Z
TRANSACTIONID=1234567890
//And for submitting API calls on bob's behalf, if his PayPal email was bob#bob.com:
SUBJECT=bob#bob.com

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