From 94966a9933bc4007ae249857fa0e5af1bd0e38af Mon Sep 17 00:00:00 2001 From: Michael Bumann Date: Thu, 9 Apr 2020 11:51:54 +0200 Subject: [PATCH] Handle authentication errors when appending data This catches exceptions that can happen when an authentication is expired or removed by the user on google's side. --- app/jobs/submission_append_job.rb | 16 ++++++++++++++-- app/models/form.rb | 8 ++++++++ app/models/user.rb | 9 +++++++++ 3 files changed, 31 insertions(+), 2 deletions(-) diff --git a/app/jobs/submission_append_job.rb b/app/jobs/submission_append_job.rb index fe55176..0403000 100644 --- a/app/jobs/submission_append_job.rb +++ b/app/jobs/submission_append_job.rb @@ -1,8 +1,20 @@ class SubmissionAppendJob < ApplicationJob queue_as :default - def perform(submission_id) + rescue_from(Signet::AuthorizationError, Google::Apis::AuthorizationError) do |exception| + submission_id = self.arguments.first + Rails.logger.error("AuthorizationError during SubmissionAppend: submission_id=#{submission_id}") submission = Submission.find(submission_id) - submission.append_to_spreadsheet + submission.form.deactivate!('AuthorizationError') + end + + def perform(*args) + submission_id = args.first + submission = Submission.find(submission_id) + if submission.form.active? + submission.append_to_spreadsheet + else + Rails.logger.error("Inactive form: submission_id=#{submission_id} form_id=#{submission.form_id}") + end end end diff --git a/app/models/form.rb b/app/models/form.rb index 9752094..c70d3bd 100644 --- a/app/models/form.rb +++ b/app/models/form.rb @@ -11,6 +11,14 @@ class Form < ApplicationRecord validates_presence_of :title + def deactivate!(reason = nil) + self.user.deactivate!(reason) + end + + def active? + self.user.active? + end + def google_spreadsheet_url "https://docs.google.com/spreadsheets/d/#{google_spreadsheet_id}/edit" if google_spreadsheet_id.present? end diff --git a/app/models/user.rb b/app/models/user.rb index 83bb70e..2918dc3 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -25,6 +25,15 @@ class User < ApplicationRecord end end + def deactivate!(reason = nil) + # currently we only use deactivate if we get an authentication exception appending data to a spreadsheet + authentications.last&.update(expires_at: Time.current) + end + + def active? + authentications.last.present? && !authentications.last.expired? + end + def google_authorization authentications.last.google_authorization end