From 3b5645c0c76808d4635ef017e3e344cf20ab2278 Mon Sep 17 00:00:00 2001 From: Tom Clegg Date: Thu, 24 Jan 2013 16:40:11 -0800 Subject: [PATCH] handle invalid token more gracefully --- app/controllers/application_controller.rb | 16 ++++++++++++---- app/models/orvos_api_client.rb | 10 ++++++++-- 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index b3a98293da..e3f006b576 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -72,7 +72,9 @@ class ApplicationController < ActionController::Base def thread_with_api_token begin + try_redirect_to_login = true if params[:api_token] + try_redirect_to_login = false Thread.current[:orvos_api_token] = params[:api_token] # Before copying the token into session[], do a simple API # call to verify its authenticity. @@ -93,11 +95,17 @@ class ApplicationController < ActionController::Base end elsif session[:orvos_api_token] # In this case, the token must have already verified at some - # point, although it might have been revoked since. TODO: - # graceful failure if the token is revoked. + # point, but it might have been revoked since. We'll try + # using it, and catch the exception if it doesn't work. + try_redirect_to_login = false Thread.current[:orvos_api_token] = session[:orvos_api_token] - yield - else + begin + yield + rescue OrvosApiClient::NotLoggedInException + try_redirect_to_login = true + end + end + if try_redirect_to_login respond_to do |f| f.html { redirect_to $orvos_api_client.orvos_login_url(return_to: request.url) diff --git a/app/models/orvos_api_client.rb b/app/models/orvos_api_client.rb index 42fdcdc5ce..b5e1ca2b50 100644 --- a/app/models/orvos_api_client.rb +++ b/app/models/orvos_api_client.rb @@ -1,4 +1,6 @@ class OrvosApiClient + class NotLoggedInException < Exception + end def api(resources_kind, action, data=nil) orvos_api_token = Thread.current[:orvos_api_token] orvos_api_token = '' if orvos_api_token.nil? @@ -25,7 +27,7 @@ class OrvosApiClient url = "#{self.orvos_v1_base}/#{resources_kind}#{action}" IO.popen([ENV, 'curl', - '-sk', + '-s', *dataargs, url], 'r') do |io| @@ -33,7 +35,11 @@ class OrvosApiClient end resp = JSON.parse json, :symbolize_names => true if resp[:errors] - raise "API errors:\n#{resp[:errors].join "\n"}\n" + if resp[:errors][0] == 'Not logged in' + raise NotLoggedInException.new + else + raise "API errors:\n\n#{resp[:errors].join "\n\n"}\n" + end end resp end -- 2.30.2