handle invalid token more gracefully
authorTom Clegg <tom@clinicalfuture.com>
Fri, 25 Jan 2013 00:40:11 +0000 (16:40 -0800)
committerTom Clegg <tom@clinicalfuture.com>
Fri, 25 Jan 2013 00:40:11 +0000 (16:40 -0800)
app/controllers/application_controller.rb
app/models/orvos_api_client.rb

index b3a98293dab2e66f8fd9822745af26e493470a96..e3f006b57692f3a40314c35b56427d2edc50751d 100644 (file)
@@ -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)
index 42fdcdc5ceab3117966893dafa98b047ddc108c6..b5e1ca2b50cd94b28a09e7092d5e21f25ccc30b8 100644 (file)
@@ -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