theseus/app/models/hcb/oauth_connection.rb
24c02 11c5f53074 Add HCB payment integration for indicia purchases
- USPS::IndiciumPolicy to check can_use_indicia?
- HCB::IndiciumPurchaseService for disbursement + purchase flow
- Add hcb_payment_account to letter_queues and usps_indicia
- Wire HCB payment into LettersController#buy_indicia
- Wire HCB payment into Letter::InstantQueue
2025-12-18 14:45:50 -05:00

64 lines
1.6 KiB
Ruby

# == Schema Information
#
# Table name: hcb_oauth_connections
#
# id :bigint not null, primary key
# access_token_ciphertext :text
# expires_at :datetime
# refresh_token_ciphertext :text
# created_at :datetime not null
# updated_at :datetime not null
# user_id :bigint not null
#
# Indexes
#
# index_hcb_oauth_connections_on_user_id (user_id)
#
# Foreign Keys
#
# fk_rails_... (user_id => users.id)
#
class HCB::OauthConnection < ApplicationRecord
belongs_to :user
has_many :payment_accounts, dependent: :destroy
has_encrypted :access_token, :refresh_token
validates :user_id, uniqueness: true
def client
@client ||= HCBV4::Client.from_credentials(
client_id: Rails.application.credentials.dig(:hcb, :client_id),
client_secret: Rails.application.credentials.dig(:hcb, :client_secret),
access_token: access_token,
refresh_token: refresh_token,
expires_at: expires_at&.to_i,
base_url: hcb_api_base,
)
end
def organizations
result = client.organizations
persist_refreshed_token!
result
end
def persist_refreshed_token!
token = client.oauth_token
return unless token.respond_to?(:token)
if token.token != access_token || token.refresh_token != refresh_token
update!(
access_token: token.token,
refresh_token: token.refresh_token,
expires_at: token.expires_at ? Time.at(token.expires_at) : nil,
)
end
end
private
def hcb_api_base
Rails.application.credentials.dig(:hcb, :api_base) || "https://hcb.hackclub.com"
end
end