Handle oauth errors with Google Ruby Client? - ruby-on-rails

I'm using Google API Ruby Client (gem 'google-api-client') in a Rails Web app, and I'd like to know how to catch specific errors in the oauth flow. In particular, what should I look for in the rescue statement? Here's the function called by the redirect after the user authorizes:
require 'google/api_client'
def google_auth_finish
begin
client = Google::APIClient.new
client.authorization.client_id = GOOGLE_CLIENT_ID
client.authorization.client_secret = GOOGLE_CLIENT_SECRET
...
rescue ## WHAT GOES HERE TO IDENTIFY THE ERROR?
# Handle the error
logger.info "There was an error."
end
end
Is there a reference somewhere with defined errors? I've searched and can't find it.

I know this was asked years ago, but I literally just encountered this problem and happened upon this question. You were just missing a small part. This worked for me. I am still relatively new, but in my case it prevented the program from breaking and printed out the error message, then the program continued on.
rescue Exception => error
puts "Error #{error}"
end

try theseRaising An Exception

Related

Rails API 422 Unprocessable Entity: No verification key available, heroku

I created a Rails API with a JWT authentication system and deployed it to Heroku. When I request the endpoints locally, all seems to be working fine but when I make requests to the live endpoints (i.e the Heroku deployed app) I get a: 422 Unprocessable Entity server error and the response body looks like this:
{
"message": "No verification key available"
}
The class responsible for encoding and decoding the auth token is defined as follows:
class JsonWebToken
# secret to encode and decode token
HMAC_SECRET = Rails.application.secrets.secret_key_base
def self.encode(payload, exp = 24.hours.from_now)
# set expiry to 24 hours from the creation time.
payload[:exp] = exp.to_i
# sign token with application secret
JWT.encode(payload, HMAC_SECRET)
end
def self.decode(token)
# get payload, first index in decoded Array
body = JWT.decode(token, HMAC_SECRET)[0]
HashWithIndifferentAccess.new body
# rescue from all decode errors
rescue JWT::DecodeError => e
# raise custom error to be handled by custom handler
raise ExceptionHandler::InvalidToken, e.message
end
end
I have an endpoint /signup where I can make a POST request to register a new user and POST /todos which is accessible and available only to registered users. Making a registration request works perfectly fine, but when I try to make the POST request to the /todos endpoint it raises an error.
The association between user and suit is 1:m respectively.
Please if you have any idea on how I can fix this, I'll be very grateful, thanks : ).
I finally figured a way out by altering the Rails.application.secrets.secret_key_base to Rails.application.secret_key_base. For a more detailed review on this please check out this link. Hopefully, this will help someone facing a similar issue.
This was also my problem. After checking out my json_web_token.rb file, I figured out that I had written the following line:
HMAC_SECRET = Rails.application.secrets.secret_key_base
There is an extra secrets reference, which is causing the problem. It should be:
HMAC_SECRET = Rails.application.secret_key_base
But as far as I'm concerned, you managed to figure it out yourself!

How to handle httparty errors rails

I am using some api with httparty gem
I have read this question:
How can I handle errors with HTTParty?
And there are two most upvoted answers how to handle errors
first one using response codes (which does not address connection failures)
response = HTTParty.get('http://twitter.com/statuses/public_timeline.json')
case response.code
when 200
puts "All good!"
when 404
puts "O noes not found!"
when 500...600
puts "ZOMG ERROR #{response.code}"
end
And the second - catching errors.
begin
HTTParty.get('http://google.com')
rescue HTTParty::Error
# donĀ“t do anything / whatever
rescue StandardError
# rescue instances of StandardError,
# i.e. Timeout::Error, SocketError etc
end
So what is the best practice do handle errors?
Do I need to handle connection failures?
Right now I am thinking of combining this two approaches like this:
begin
response = HTTParty.get(url)
case response.code
when 200
# do something
when 404
# show error
end
rescue HTTParty::Error => error
puts error.inspect
rescue => error
puts error.inspect
end
end
Is it a good approach to handle both connection error and response codes?
Or I am being to overcautious?
You definitely want to handle connection errors are they are exceptions outside the normal flow of your code, hence the name exceptions. These exceptions happen when connections timeout, connections are unreachable, etc, and handling them ensures your code is resilient to these types of failures.
As far as response codes, I would highly suggest you handle edge cases, or error response codes, so that your code is aware when there are things such as pages not found or bad requests which don't trigger exceptions.
In any case, it really depends on the code that you're writing and at this point is a matter of opinion but in my opinion and personal coding preference, handling both exceptions and error codes is not being overcautious but rather preventing future failures.

How to handle 300 Multiple Choices Exception for Rails

I have an exception error for testing an API that I am not quite sure how to handle. Here is the snippet of code at the bottom.
begin
open(release_url(uuid)) do |feed|
response = JSON.parse(feed.read)
return get_target_releases_json(response['targets']) if feed.status.first != 200
return if pss.etag == feed.meta['etag']
response['releases']
end
rescue Exception => e
puts "#---Exception---#"
puts e
end
What is pertinent to understand the problem is the open(url) method.
When I reach this point using byebug I get an exception that is a 300 - Multiple Choices error. I read a little bit about it but I don't understand what I need to do to correct this. The api (which is internal to my company btw) is supposed to return a JSON structure when it hits 300. When I place this api url in my browser, I am able to see the JSON payload but when I try to use it programmatically, it errors out. Where does the problem lie? Is it in the api url or could it be elsewhere? As or right now, I can't do anything with this test url call so I'm a little bit stuck. Does anyone have any ideas to discover what I can do with this?

Yelp Place API returning "Invalid Signature" Error only from Nginx on EC2

Problem: I am getting an "Invalid Signature" error from Yelp API only from production (running on nginx server in AWS) When I run locally on my localhost:3000, there is no signature error, and everything works fine.
I am using the yelp gem in rails. Here's some code in ruby.:
$client = Yelp::Client.new({
consumer_key: $SL_CONSUMER_KEY,
consumer_secret: $SL_CONSUMER_SECRET,
token: $SL_TOKEN,
token_secret: $SL_TOKEN_SECRET
})
begin
$client.search("Los Angeles")
rescue => error
puts error.message
puts error.inspect
end
error.message prints out: "Signature was invalid"
error.inspect prints out: < Yelp::Error::InvalidSignature: Signature was invalid >
Everything works when I run locally on rails' Webrick server but when I run it in production, I get an "Invalid Signature" error.
Has anyone seen this? I've looked at some relevant posts, but this seems different. Thanks!
This will probably not pertain to most people, but the off chance it could help someone, here it is:
My "time" was effed up on my EC2 instance. So for example, in ruby, Time.now was not printing the actual time. (I think it was off by a few minutes or so).
Anyway, Yelp API requires a oauth_timestamp when you send a request. Of course, then, my request was timing out b/c the time was off.
How did I found this error out?
I just pinged the URL on my browser with the oauth, token, oauth_timestamp, etc. (few more) as query params. The browser spits out the error response in JSON, and it was saying that my request was timing out. When you use the ruby Yelp Client and catch the exception in code, it doesn't spit out the error response in terminal, so it's a bit more difficult to locate the exact root of the error.
How I solved it:
I re-calibrated the time in my ec2 instance by following the directions here: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/set-time.html
Problem is solved. Peace.
Invalid signature error in Yelp API occurs due to two reasons .
First , Either of your four keys i.e consumer_key , consumer_secret_key , Token & Token Secret is invalid . Secondly Parameters passed to Yelp API Function are either invalid or any of those are nil .

How do I get my rails app to work around errors?

My rails app is a web scraper using Mechanize / Nokogiri. Due to problems with KBB.com and their cookies I have to clear my cookie jar in my app every time I issue a new get request to their server.
agent.cookie_jar.clear!
However, while my app is scraping data, occasionally it hits a KBB.cpm page with an automatic redirect! This causes an error:
Mechanize::ResponseCodeError: 500 => Net::HTTPInternalServerError for http://www.kbb.com/toyota/prius/2002-toyota-prius/sedan-4d/options/?vehicleid=4843&intent=buy-used -- unhandled response
This causes my rails app to crash because I can't clear the cookie jar before it redirects. Instead, what I would like for my app to do is recognize that it could hit an error and if it does to use a different process. Something like:
if there_is_an_error
# alternative process for redirect
else
# business as usual
end
here's my code:
agent = Mechanize.new
agent.cookie_jar.clear!
page = agent.get(url)
agent.cookie_jar.clear!
page.link_with(:text => "Choose this style").click
agent.cookie_jar.clear!
agent.page.link_with(:text => "Choose price type").click
agent.cookie_jar.clear!
agent.page.links_with(:text => "Get used car price")[2].click
url = agent.page.uri.to_s.sub('retail', 'private-party')
agent.cookie_jar.clear!
agent.get(url)
#kbb_value = agent.page.at('.selected .value').text.delete('$')
You should look at http://www.tutorialspoint.com/ruby/ruby_exceptions.htm on handling exceptions. There is also a stack overflow post about this: Begin, Rescue and Ensure in Ruby? . You could fix your problem by setting a flag in the exception handling block, then checking for that flag later on in your code to find out if an exception occurred, and this should fix your problem.
you can just rescue the Mechanize::ResponseCodeError exception and do your alternative process for redirect inside that block

Resources