Class: InstagramConnect::Account

Inherits:
ApplicationRecord show all
Defined in:
app/models/instagram_connect/account.rb

Overview

A connected Instagram professional account. Holds the (encrypted) access token and the identity the Graph client sends as. One row per connected account — the gem supports connecting several.

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.enable_token_encryption!Object

Called from the engine initializer (and specs) when token encryption is enabled. Kept as an explicit toggle so a host without Active Record Encryption configured can opt out via config.encrypt_tokens = false.



22
23
24
25
# File 'app/models/instagram_connect/account.rb', line 22

def self.enable_token_encryption!
  encrypts :access_token
  encrypts :page_access_token
end

Instance Method Details

#api_tokenObject

Every Instagram messaging call and the webhook subscription are Page-token operations. Falling back to the user token keeps a freshly connected account working until the readiness pass swaps in the Page one.



30
31
32
# File 'app/models/instagram_connect/account.rb', line 30

def api_token
  page_access_token.presence || access_token
end

#clientObject

The only place a Client should be built. Constructing one directly picks up the global auth path, which is wrong for any host with accounts on both paths — and wrong silently, which is worse.



37
38
39
40
41
42
43
# File 'app/models/instagram_connect/account.rb', line 37

def client
  InstagramConnect::Client.new(
    access_token: api_token,
    ig_user_id: ig_user_id,
    config: InstagramConnect.configuration.for_auth_path(auth_path)
  )
end

#refresh_access_token!Object

Refresh via the account's auth strategy and persist the rotated token. Refreshes via the strategy this row was connected with, not the globally configured one.



56
57
58
59
60
# File 'app/models/instagram_connect/account.rb', line 56

def refresh_access_token!
  strategy = InstagramConnect::Auth.for(InstagramConnect.configuration.for_auth_path(auth_path))
  data = strategy.refresh_token(access_token: access_token)
  update!(access_token: data[:access_token], token_expires_at: data[:expires_at])
end

#subscribed_field_listObject



45
46
47
# File 'app/models/instagram_connect/account.rb', line 45

def subscribed_field_list
  subscribed_fields.to_s.split(",").map(&:strip).reject(&:empty?)
end

#token_expired?Boolean

Returns:

  • (Boolean)


49
50
51
# File 'app/models/instagram_connect/account.rb', line 49

def token_expired?
  token_expires_at.present? && token_expires_at <= Time.current
end