From 517a23948528f863dda5def6218d169091412ae6 Mon Sep 17 00:00:00 2001 From: Ricky Barrette Date: Sat, 30 Dec 2023 12:39:51 -0500 Subject: [PATCH] Started reworking Oauth token sorage --- app/controllers/qbo_controller.rb | 15 ++--- app/models/concerns/quickbooks_oauth.rb | 80 ++++++++++++++++++++++++ app/models/qbo.rb | 81 ++++++------------------- db/migrate/037_update_qbo_token.rb | 18 ++++++ 4 files changed, 122 insertions(+), 72 deletions(-) create mode 100644 app/models/concerns/quickbooks_oauth.rb create mode 100644 db/migrate/037_update_qbo_token.rb diff --git a/app/controllers/qbo_controller.rb b/app/controllers/qbo_controller.rb index 3d7c4cd..f6c8be1 100644 --- a/app/controllers/qbo_controller.rb +++ b/app/controllers/qbo_controller.rb @@ -1,6 +1,6 @@ #The MIT License (MIT) # -#Copyright (c) 2022 rick barrette +#Copyright (c) 2023 rick barrette # #Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: # @@ -26,7 +26,7 @@ class QboController < ApplicationController # Called when the user requests that Redmine to connect to QBO # def authenticate - oauth2_client = Qbo.get_client + oauth2_client = Qbo.construct_oauth2_client callback = Setting.host_name + "/qbo/oauth_callback/" grant_url = oauth2_client.auth_code.authorize_url(redirect_uri: callback, response_type: "code", state: SecureRandom.hex(12), scope: "com.intuit.quickbooks.accounting") redirect_to grant_url @@ -37,7 +37,7 @@ class QboController < ApplicationController # def oauth_callback if params[:state].present? - oauth2_client = Qbo.get_client + oauth2_client = Qbo.construct_oauth2_client # use the state value to retrieve from your backend any information you need to identify the customer in your system redirect_uri = Setting.host_name + "/qbo/oauth_callback/" if resp = oauth2_client.auth_code.get_token(params[:code], redirect_uri: redirect_uri) @@ -47,12 +47,7 @@ class QboController < ApplicationController # Save the authentication information qbo = Qbo.new - qbo.company_id = params[:realmId] - - # Generate Access Token & Serialize it into the database - access_token = OAuth2::AccessToken.new(oauth2_client, resp.token, refresh_token: resp.refresh_token) - qbo.token = access_token.to_hash - qbo.expire = 1.hour.from_now.utc + qbo.update(access_token: resp.token, refresh_token: resp.refresh_token, realm_id: params[:realmId]) if qbo.save! redirect_to qbo_sync_path, :flash => { :notice => "Successfully connected to Quickbooks" } @@ -154,6 +149,6 @@ class QboController < ApplicationController ActiveRecord::Base.connection.close end - redirect_to :home, :flash => { :notice => "Successfully synced to Quickbooks" } + redirect_to :home, :flash => { :notice => "Syncing Quickbooks" } end end diff --git a/app/models/concerns/quickbooks_oauth.rb b/app/models/concerns/quickbooks_oauth.rb new file mode 100644 index 0000000..9e03a82 --- /dev/null +++ b/app/models/concerns/quickbooks_oauth.rb @@ -0,0 +1,80 @@ +#The MIT License (MIT) +# +#Copyright (c) 2023 rick barrette +# +#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +# +#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +# +#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +module QuickbooksOauth + extend ActiveSupport::Concern + + OAUTH_CONSUMER_KEY = Setting.plugin_redmine_qbo['settingsOAuthConsumerKey'] + OAUTH_CONSUMER_SECRET = Setting.plugin_redmine_qbo['settingsOAuthConsumerSecret'] + + #== Instance Methods + + def perform_authenticated_request(&block) + attempts = 0 + begin + yield oauth_access_token + rescue OAuth2::Error, Quickbooks::AuthorizationFailure => ex + Rails.logger.info("QuickbooksOauth.perform: #{ex.message}") + + # to prevent an infinite loop here keep a counter and bail out after N times... + attempts += 1 + + raise "QuickbooksOauth:ExceededAuthAttempts" if attempts >= 3 + + # check if its an invalid_grant first, but assume it is for now + refresh_token! + + retry + end + end + + def refresh_token! + t = oauth_access_token + refreshed = t.refresh! + + if refreshed.params['x_refresh_token_expires_in'].to_i > 0 + oauth2_refresh_token_expires_at = Time.now + refreshed.params['x_refresh_token_expires_in'].to_i.seconds + else + oauth2_refresh_token_expires_at = 100.days.from_now + end + + update!( + oauth2_access_token: refreshed.token, + oauth2_access_token_expires_at: Time.at(refreshed.expires_at), + oauth2_refresh_token: refreshed.refresh_token, + oauth2_refresh_token_expires_at: oauth2_refresh_token_expires_at + ) + end + + def oauth_client + self.class.construct_oauth2_client + end + + def oauth_access_token + OAuth2::AccessToken.new(oauth_client, oauth2_access_token, refresh_token: oauth2_refresh_token) + end + + def consumer + oauth_access_token + end + + module ClassMethods + + def construct_oauth2_client + options = { + site: "https://appcenter.intuit.com/connect/oauth2", + authorize_url: "https://appcenter.intuit.com/connect/oauth2", + token_url: "https://oauth.platform.intuit.com/oauth2/v1/tokens/bearer" + } + OAuth2::Client.new(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET, options) + end + + end +end diff --git a/app/models/qbo.rb b/app/models/qbo.rb index 337639e..7cd9b97 100644 --- a/app/models/qbo.rb +++ b/app/models/qbo.rb @@ -10,31 +10,8 @@ class Qbo < ActiveRecord::Base unloadable - validates_presence_of :token, :company_id, :expire - serialize :token - - OAUTH_CONSUMER_KEY = Setting.plugin_redmine_qbo['settingsOAuthConsumerKey'] - OAUTH_CONSUMER_SECRET = Setting.plugin_redmine_qbo['settingsOAuthConsumerSecret'] - - # - # Getter for quickbooks OAuth2 client - # - def self.get_client - oauth_params = { - site: "https://appcenter.intuit.com/connect/oauth2", - authorize_url: "https://appcenter.intuit.com/connect/oauth2", - token_url: "https://oauth.platform.intuit.com/oauth2/v1/tokens/bearer" - } - return OAuth2::Client.new(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET, oauth_params) - end - - # - # Getter for oauth consumer - # - def self.get_oauth_consumer - # Quickbooks Config Info - return $qb_oauth_consumer - end + + include QuickbooksOauth # # Get a quickbooks base service object for type @@ -42,47 +19,27 @@ class Qbo < ActiveRecord::Base # def self.get_base(type) # lets getnourbold access token from the database - oauth2_client = get_client + oauth2_client = construct_oauth2_client qbo = self.first - access_token = OAuth2::AccessToken.from_hash(oauth2_client, qbo.token) - # check to see if we need to refresh the acesstoken - if qbo.expire.to_time.utc.past? - puts "Updating access token" - new_access_token_object = access_token.refresh! - qbo.token = new_access_token_object.to_hash - qbo.expire = 1.hour.from_now.utc - qbo.save! - access_token = new_access_token_object - else - puts "Using current token" - end - - # build the reqiested service - case type - when :item - return Quickbooks::Service::Item.new(:company_id => qbo.company_id, :access_token => access_token) - when :time_activity - return Quickbooks::Service::TimeActivity.new(:company_id => qbo.company_id, :access_token => access_token) - when :customer - return Quickbooks::Service::Customer.new(:company_id => qbo.company_id, :access_token => access_token) - when :invoice - return Quickbooks::Service::Invoice.new(:company_id => qbo.company_id, :access_token => access_token) - when :estimate - return Quickbooks::Service::Estimate.new(:company_id => qbo.company_id, :access_token => access_token) - when :account - return Quickbooks::Service::Account.new(:company_id => qbo.company_id, :access_token => access_token) - when :employee - return Quickbooks::Service::Employee.new(:company_id => qbo.company_id, :access_token => access_token) - else - return access_token + qbo.perform_authenticated_request do |access_token| + # build the reqiested service + case type + when :time_activity + return Quickbooks::Service::TimeActivity.new(:company_id => qbo.company_id, :access_token => access_token) + when :customer + return Quickbooks::Service::Customer.new(:company_id => qbo.company_id, :access_token => access_token) + when :invoice + return Quickbooks::Service::Invoice.new(:company_id => qbo.company_id, :access_token => access_token) + when :estimate + return Quickbooks::Service::Estimate.new(:company_id => qbo.company_id, :access_token => access_token) + when :employee + return Quickbooks::Service::Employee.new(:company_id => qbo.company_id, :access_token => access_token) + else + return access_token + end end - end - - # Get the QBO account - def self.get_account - first end # Updates last sync time stamp diff --git a/db/migrate/037_update_qbo_token.rb b/db/migrate/037_update_qbo_token.rb new file mode 100644 index 0000000..71a3109 --- /dev/null +++ b/db/migrate/037_update_qbo_token.rb @@ -0,0 +1,18 @@ +#The MIT License (MIT) +# +#Copyright (c) 2023 rick barrette +# +#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +# +#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +# +#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +class UpdateQboToken < ActiveRecord::Migration[5.1] + def change + add_column :qbos, :oauth2_access_token, :text + add_column :qbos, :oauth2_access_token_expires_at, :datetime + add_column :qbos, :oauth2_refresh_token, :text + add_column :qbos, :oauth2_refresh_token_expires_at, :datetime + end +end