The personal finance app for everyone (by everyone)
Ruby
class EnableBankingItemsController < ApplicationController
include EnableBankingItems::MapsHelper
include SafeProviderRedirect
before_action :set_enable_banking_item, only: [ :update, :destroy, :sync, :select_bank, :authorize, :reauthorize, :setup_accounts, :complete_account_setup, :new_connection ]
before_action :require_admin!, only: [ :new, :create, :link_accounts, :select_existing_account, :link_existing_account, :update, :destroy, :sync, :select_bank, :authorize, :callback, :reauthorize, :setup_accounts, :complete_account_setup, :new_connection ]
skip_before_action :verify_authenticity_token, only: [ :callback ]
OAUTH_STATE_SESSION_KEY = :enable_banking_oauth_states
MAX_PENDING_OAUTH_STATES = 5
# Authorization URLs from Enable Banking are followed only on these hosts
# (or their subdomains), over HTTPS. See SafeProviderRedirect.
TRUSTED_ENABLE_BANKING_HOSTS = %w[
enablebanking.com
api.enablebanking.com
auth.enablebanking.com
].freeze
def new
@enable_banking_item = Current.family.enable_banking_items.build
end
def create
@enable_banking_item = Current.family.enable_banking_items.build(enable_banking_item_params)
@enable_banking_item.name ||= "Enable Banking Connection"
if @enable_banking_item.save
redirect_to settings_providers_path, notice: t(".success"), status: :see_other
else
render_provider_panel("enable_banking", alert: @enable_banking_item.errors.full_messages.join(", "))
end
end
def update
if @enable_banking_item.update(enable_banking_item_params)
render_provider_panel("enable_banking", notice: t(".success"), enable_banking_items: Current.family.enable_banking_items.ordered)
else
render_provider_panel("enable_banking", alert: @enable_banking_item.errors.full_messages.join(", "))
end
end
def destroy
# Ensure we detach provider links before scheduling deletion
begin
@enable_banking_item.unlink_all!(dry_run: false)
rescue => e
Rails.logger.warn("Enable Banking unlink during destroy failed: #{e.class} - #{e.message}")
end
@enable_banking_item.revoke_session
@enable_banking_item.destroy_later
redirect_to settings_providers_path, notice: t(".success", default: "Scheduled Enable Banking connection for deletion.")
end
def sync
unless @enable_banking_item.syncing?
@enable_banking_item.sync_later
end
if provider_panel_form?
return render_provider_panel("enable_banking", notice: t("settings.providers.sync_provider_in_progress"),
enable_banking_items: Current.family.enable_banking_items.ordered)
end
respond_to do |format|
format.html { redirect_back_or_to accounts_path }
format.json { head :ok }
end
end
# Show bank selection page
def select_bank
unless @enable_banking_item.credentials_configured?
redirect_to settings_providers_path, alert: t(".credentials_required", default: "Please configure your Enable Banking credentials first.")
return
end
@new_connection = params[:new_connection] == "true"
@country_code = requested_country_code
begin
provider = @enable_banking_item.enable_banking_provider
response = provider.get_aspsps(country: @country_code)
raw_aspsps = response[:aspsps] || response["aspsps"] || []
# Sort: non-beta alphabetically, then beta alphabetically
@aspsps = raw_aspsps.map(&:with_indifferent_access).sort_by { |a| [ a[:beta] ? 1 : 0, a[:name].to_s.downcase ] }
rescue Provider::EnableBanking::EnableBankingError => e
Rails.logger.error "Enable Banking API error in select_bank: #{e.message}"
@error_message = e.message
@aspsps = []
end
render layout: false
end
# Initiate authorization for a selected bank
def authorize
aspsp_name = params[:aspsp_name]
country_code = requested_country_code
psu_type = params[:psu_type].presence || "personal"
unless aspsp_name.present?
redirect_to settings_providers_path, alert: t(".bank_required", default: "Please select a bank.")
return
end
begin
pending_connection = pending_connection_for(aspsp_name, country_code) if params[:new_connection] == "true"
target_item = if params[:new_connection] == "true"
pending_connection || Current.family.enable_banking_items.create!(
name: "Enable Banking Connection",
aspsp_name: aspsp_name,
country_code: country_code,
application_id: @enable_banking_item.application_id,
client_certificate: @enable_banking_item.client_certificate
)
else
@enable_banking_item
end
# Capture PSU IP for use in background sync PSU headers
target_item.update(last_psu_ip: request.remote_ip) if request.remote_ip.present?
language = I18n.locale.to_s.split("-").first
# begin_authorization! re-fetches ASPSP metadata and auto-selects the best
# auth method (REDIRECT > DECOUPLED > EMBEDDED). Decoupled/MFA banks proceed
# through Enable Banking's hosted SCA page rather than being blocked.
redirect_url = with_oauth_state_for(target_item, supersede: pending_connection.present?) do |state|
target_item.begin_authorization!(
aspsp_name: aspsp_name,
redirect_url: enable_banking_callback_url,
state: state,
psu_type: psu_type,
language: language
)
end
safe_redirect_to_provider(
redirect_url,
trusted_hosts: TRUSTED_ENABLE_BANKING_HOSTS,
fallback_path: settings_providers_path,
fallback_alert: t(".invalid_redirect", default: "Invalid authorization URL received. Please try again.")
)
rescue Provider::EnableBanking::EnableBankingError => e
if e.message.include?("REDIRECT_URI_NOT_ALLOWED")
Rails.logger.error "Enable Banking redirect URI not allowed: #{e.message}"
redirect_to settings_providers_path, alert: t(".redirect_uri_not_allowed",
default: "Redirect not allowed. Configure `%{callback_url}` in your Enable Banking application settings.",
callback_url: enable_banking_callback_url)
else
Rails.logger.error "Enable Banking authorization error: #{e.message}"
redirect_to settings_providers_path, alert: t(".authorization_failed",
default: "Failed to start authorization: %{message}", message: e.message)
end
rescue => e
Rails.logger.error "Unexpected error in authorize: #{e.class}: #{e.message}"
redirect_to settings_providers_path, alert: t(".unexpected_error", default: "An unexpected error occurred. Please try again.")
end
end
# Handle OAuth callback from Enable Banking
def callback
code = params[:code]
state = params[:state]
error = params[:error]
error_description = params[:error_description]
if error.present?
Rails.logger.error "Enable Banking callback error: #{error} - #{error_description}"
redirect_to settings_providers_path, alert: t(".authorization_error", default: "Authorization failed: %{error}", error: error_description || error)
return
end
unless code.present? && state.present?
redirect_to settings_providers_path, alert: t(".invalid_callback", default: "Invalid callback parameters.")
return
end
# The state must match the one issued to this browser session, so a
# callback link crafted by someone else cannot attach their bank
# authorization code to this family's connection.
enable_banking_item = consume_oauth_state(state)
unless enable_banking_item.present?
redirect_to settings_providers_path, alert: t(".item_not_found", default: "Connection not found.")
return
end
# Refresh PSU IP on callback (user's browser is present here)
enable_banking_item.update(last_psu_ip: request.remote_ip) if request.remote_ip.present?
begin
enable_banking_item.complete_authorization(code: code)
# Trigger sync to process accounts
enable_banking_item.sync_later
redirect_to accounts_path, notice: t(".success", default: "Successfully connected to your bank. Your accounts are being synced.")
rescue Provider::EnableBanking::EnableBankingError => e
Rails.logger.error "Enable Banking session creation error: #{e.message}"
redirect_to settings_providers_path, alert: t(".session_failed", default: "Failed to complete authorization: %{message}", message: e.message)
rescue => e
Rails.logger.error "Unexpected error in callback: #{e.class}: #{e.message}"
redirect_to settings_providers_path, alert: t(".unexpected_error", default: "An unexpected error occurred. Please try again.")
end
end
# Show bank selection for a new connection using credentials from an existing item
# Does NOT create a new item - that happens in authorize when user selects a bank
def new_connection
# Redirect to select_bank with a flag indicating this is for a new connection
redirect_to select_bank_enable_banking_item_path(@enable_banking_item, new_connection: true, country_code: requested_country_code), data: { turbo_frame: "modal" }
end
# Re-authorize an expired session
def reauthorize
begin
language = I18n.locale.to_s.split("-").first
# Route through the shared path so reauthorization re-selects the same auth
# method (decoupled banks included) instead of falling back to a default.
redirect_url = with_oauth_state_for(@enable_banking_item, supersede: false) do |state|
@enable_banking_item.begin_authorization!(
redirect_url: enable_banking_callback_url,
state: state,
language: language
)
end
safe_redirect_to_provider(
redirect_url,
trusted_hosts: TRUSTED_ENABLE_BANKING_HOSTS,
fallback_path: settings_providers_path,
fallback_alert: t(".invalid_redirect", default: "Invalid authorization URL received. Please try again.")
)
rescue Provider::EnableBanking::EnableBankingError => e
Rails.logger.error "Enable Banking reauthorization error: #{e.message}"
redirect_to settings_providers_path, alert: t(".reauthorization_failed",
default: "Failed to re-authorize: %{message}", message: e.message)
end
end
# Link accounts from Enable Banking to internal accounts
def link_accounts
selected_uids = params[:account_uids] || []
accountable_type = params[:accountable_type] || "Depository"
if selected_uids.empty?
redirect_to accounts_path, alert: t(".no_accounts_selected", default: "No accounts selected.")
return
end
enable_banking_item = Current.family.enable_banking_items.where.not(session_id: nil).first
unless enable_banking_item.present?
redirect_to settings_providers_path, alert: t(".no_session", default: "No active Enable Banking connection. Please connect a bank first.")
return
end
created_accounts = []
already_linked_accounts = []
# Wrap in transaction so partial failures don't leave orphaned accounts without provider links
begin
ActiveRecord::Base.transaction do
selected_uids.each do |uid|
enable_banking_account = enable_banking_item.enable_banking_accounts.find_by(uid: uid)
next unless enable_banking_account
# Check if already linked
if enable_banking_account.account_provider.present?
already_linked_accounts << enable_banking_account.name
next
end
# Create the internal Account (uses save! internally, will raise on failure)
# Skip initial sync - provider sync will handle balance creation with correct currency
account = Account.create_and_sync(
{
family: Current.family,
name: enable_banking_account.name,
balance: enable_banking_account.current_balance || 0,
currency: enable_banking_account.currency || "EUR",
accountable_type: accountable_type,
accountable_attributes: {}
},
skip_initial_sync: true
)
# Link account to enable_banking_account via account_providers
# Uses create! so any failure will rollback the entire transaction
AccountProvider.create!(
account: account,
provider: enable_banking_account
)
created_accounts << account
end
end
rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotSaved => e
Rails.logger.error "Enable Banking link_accounts failed: #{e.class} - #{e.message}"
redirect_to accounts_path, alert: t(".link_failed", default: "Failed to link accounts: %{error}", error: e.message)
return
end
# Trigger sync if accounts were created
enable_banking_item.sync_later if created_accounts.any?
if created_accounts.any?
redirect_to accounts_path, notice: t(".success", default: "%{count} account(s) linked successfully.", count: created_accounts.count)
elsif already_linked_accounts.any?
redirect_to accounts_path, alert: t(".already_linked", default: "Selected accounts are already linked.")
else
redirect_to accounts_path, alert: t(".link_failed", default: "Failed to link accounts.")
end
end
# Show setup accounts modal
def setup_accounts
@enable_banking_accounts = @enable_banking_item.enable_banking_accounts.needs_setup
account_type_keys = {
"depository" => "Depository",
"credit_card" => "CreditCard",
"investment" => "Investment",
"loan" => "Loan",
"other_asset" => "OtherAsset"
}
@account_type_options = [ [ t(".account_types.skip"), "skip" ] ] +
account_type_keys.map { |key, type| [ t(".account_types.#{key}"), type ] }
@subtype_options = {
"Depository" => {
label: t(".subtype_labels.depository"),
options: Depository.subtype_options_for_select
},
"CreditCard" => {
label: "",
options: [],
message: t(".subtype_messages.credit_card")
},
"Investment" => {
label: t(".subtype_labels.investment"),
options: Investment.subtype_options_for_select
},
"Loan" => {
label: t(".subtype_labels.loan"),
options: Loan.subtype_options_for_select
},
"OtherAsset" => {
label: nil,
options: [],
message: t(".subtype_messages.other_asset")
}
}
render layout: false
end
# Complete account setup from modal
def complete_account_setup
account_types = params[:account_types] || {}
account_subtypes = params[:account_subtypes] || {}
# The modal's date field is optional: a blank one means no lower bound, so
# the first fetch imports as much history as the bank provides.
if params.key?(:sync_start_date)
@enable_banking_item.update!(sync_start_date: params[:sync_start_date].presence)
end
created_count = 0
skipped_count = 0
account_types.each do |enable_banking_account_id, selected_type|
enable_banking_account = @enable_banking_item.enable_banking_accounts.find(enable_banking_account_id)
if selected_type == "skip" || selected_type.blank?
# Persist the skip so the account stops resurfacing as "needs setup" and the
# importer stops fetching it.
enable_banking_account.ignore!
skipped_count += 1
next
end
selected_subtype = account_subtypes[enable_banking_account_id]
# Default subtype for CreditCard since it only has one option
selected_subtype = "credit_card" if selected_type == "CreditCard" && selected_subtype.blank?
# Create account with user-selected type and subtype
account = Account.create_from_enable_banking_account(
enable_banking_account,
selected_type,
selected_subtype
)
# Link account via AccountProvider
AccountProvider.create!(
account: account,
provider: enable_banking_account
)
created_count += 1
end
# Clear pending status and mark as complete
@enable_banking_item.update!(pending_account_setup: false)
# Trigger a sync to process the imported data if accounts were created
@enable_banking_item.sync_later if created_count > 0
if created_count > 0
flash[:notice] = t(".success", default: "%{count} account(s) created successfully!", count: created_count)
elsif skipped_count > 0
flash[:notice] = t(".all_skipped")
else
flash[:notice] = t(".no_accounts", default: "No accounts to set up.")
end
redirect_to accounts_path, status: :see_other
end
def select_existing_account
@account = Current.family.accounts.find(params[:account_id])
# Filter out Enable Banking accounts that are already linked to any account
# (either via account_provider or legacy account association)
@available_enable_banking_accounts = Current.family.enable_banking_items
.includes(:enable_banking_accounts)
.flat_map(&:enable_banking_accounts)
.reject { |sfa| sfa.account_provider.present? || sfa.account.present? }
.sort_by { |sfa| sfa.updated_at || sfa.created_at }
.reverse
# Always render a modal: either choices or a helpful empty-state
render :select_existing_account, layout: false
end
def link_existing_account
@account = Current.family.accounts.find(params[:account_id])
enable_banking_account = EnableBankingAccount.find(params[:enable_banking_account_id])
# Guard: only manual accounts can be linked (no existing provider links or legacy IDs)
if @account.account_providers.any? || @account.plaid_account_id.present? || @account.simplefin_account_id.present?
flash[:alert] = t("enable_banking_items.link_existing_account.errors.only_manual")
if turbo_frame_request?
return render turbo_stream: Array(flash_notification_stream_items)
else
return redirect_to account_path(@account), alert: flash[:alert]
end
end
# Verify the Enable Banking account belongs to this family's Enable Banking items
unless enable_banking_account.enable_banking_item.present? &&
Current.family.enable_banking_items.include?(enable_banking_account.enable_banking_item)
flash[:alert] = t("enable_banking_items.link_existing_account.errors.invalid_enable_banking_account")
if turbo_frame_request?
render turbo_stream: Array(flash_notification_stream_items)
else
redirect_to account_path(@account), alert: flash[:alert]
end
return
end
# Relink behavior: detach any legacy link and point provider link at the chosen account
orphaned_account = nil
Account.transaction do
enable_banking_account.lock!
# Upsert the AccountProvider mapping deterministically
ap = AccountProvider.find_or_initialize_by(provider: enable_banking_account)
previous_account = ap.account
ap.account_id = @account.id
ap.save!
# If the provider was previously linked to a different account in this family,
# and that account is now orphaned, quietly disable it so it disappears from the
# visible manual list. This mirrors the unified flow expectation that the provider
# follows the chosen account.
if previous_account && previous_account.id != @account.id && previous_account.family_id == @account.family_id
begin
# Disabled accounts still appear (greyed-out) in the manual list after a full refresh.
# Use the app's standard deletion path (async) so the duplicate disappears and the
# "pending_deletion" state remains truthful in the UI.
orphaned_account = previous_account if previous_account.may_mark_for_deletion?
rescue => e
Rails.logger.warn("Failed to cleanup orphaned account #{previous_account.id}: #{e.class} - #{e.message}")
end
end
end
# Queue the orphan for deletion only after the relink commits. destroy_later
# pushes DestroyJob only once every open transaction commits, so called in
# the block above, an enqueue error would leave it from the commit, past
# the rescue inside it.
begin
orphaned_account&.destroy_later
rescue => e
Rails.logger.warn("Failed to cleanup orphaned account #{orphaned_account.id}: #{e.class} - #{e.message}")
end
if turbo_frame_request?
# Reload the item to ensure associations are fresh
enable_banking_account.reload
item = enable_banking_account.enable_banking_item
item.reload
# Recompute data needed by Accounts#index partials
@manual_accounts = Account.uncached {
Current.family.accounts
.visible_manual_for(Current.user)
.order(:name)
.to_a
}
@enable_banking_items = Current.family.enable_banking_items.ordered.includes(:syncs)
build_enable_banking_maps_for(@enable_banking_items)
flash[:notice] = t("enable_banking_items.link_existing_account.success")
@account.reload
manual_accounts_stream = if @manual_accounts.any?
turbo_stream.update(
"manual-accounts",
partial: "accounts/index/manual_accounts",
locals: { accounts: @manual_accounts }
)
else
turbo_stream.replace("manual-accounts", view_context.tag.div(id: "manual-accounts"))
end
render turbo_stream: [
# Optimistic removal of the specific account row if it exists in the DOM
turbo_stream.remove(ActionView::RecordIdentifier.dom_id(@account)),
manual_accounts_stream,
# Admin-only action (require_admin!), so the card lists every account.
turbo_stream.replace(
ActionView::RecordIdentifier.dom_id(item),
partial: "enable_banking_items/enable_banking_item",
locals: { enable_banking_item: item, visible_accounts: item.accounts }
),
turbo_stream.replace("modal", view_context.turbo_frame_tag("modal"))
] + Array(flash_notification_stream_items)
else
redirect_to accounts_path(cache_bust: SecureRandom.hex(6)), notice: t("enable_banking_items.link_existing_account.success"), status: :see_other
end
end
private
# The connection is created before the bank's page opens, so a later click
# on the same bank, a back-and-retry or a failed start would leave an empty
# connection behind. An earlier attempt at this bank with the same
# credentials that never came back from it (no session, no accounts) is
# reused instead. Other banks keep their own connection. Only attempts
# started in this browser session qualify: two browsers of one family
# sharing a pending connection could both complete on it.
def pending_connection_for(aspsp_name, country_code)
Current.family.enable_banking_items.active
.where(id: pending_oauth_states.values)
.where(
aspsp_name: aspsp_name,
session_id: nil,
application_id: @enable_banking_item.application_id,
country_code: country_code,
client_certificate: @enable_banking_item.client_certificate
)
.where.missing(:enable_banking_accounts)
.ordered
.first
end
# Pending states map state => item id, so parallel flows (two tabs) each
# keep their own entry. Only the newest few are kept.
#
# Yields a new state to the block that starts the flow, and records it only
# once the flow got a trusted provider URL. A reused pending connection
# (supersede) then keeps only that newest flow: two logins finishing on one
# connection would leave the first one's accounts attached to the second
# one's session. Its older states go before the cap applies, so they never
# push out another login still open. A start that fails, or returns an
# untrusted URL, leaves the map as it was, so the login still open can
# complete; only a connection with no state yet gets this one, so a retry
# finds it for reuse.
def with_oauth_state_for(item, supersede:)
state = SecureRandom.urlsafe_base64(32)
pending = pending_oauth_states
started = false
redirect_url = yield(state)
started = trusted_provider_url?(redirect_url, TRUSTED_ENABLE_BANKING_HOSTS)
redirect_url
ensure
if started || !pending.value?(item.id)
pending = pending.reject { |_, item_id| item_id == item.id } if started && supersede
write_pending_oauth_states(pending.merge(state => item.id))
end
end
def write_pending_oauth_states(pending)
session[OAUTH_STATE_SESSION_KEY] = pending.to_a.last(MAX_PENDING_OAUTH_STATES).to_h
end
# An entry is removed only when it matches, so a stray callback with a
# made-up state cannot cancel a real flow in progress.
def consume_oauth_state(state)
pending = pending_oauth_states
matched = pending.keys.find { |candidate| ActiveSupport::SecurityUtils.secure_compare(candidate, state.to_s) }
return unless matched
item_id = pending.delete(matched)
session[OAUTH_STATE_SESSION_KEY] = pending
Current.family.enable_banking_items.find_by(id: item_id)
end
def pending_oauth_states
pending = session[OAUTH_STATE_SESSION_KEY]
pending.is_a?(Hash) ? pending.to_h : {}
end
# A new connection can live in a different country than the item whose
# credentials it copies, so the caller may choose one. Unknown values fall
# back to the item's own country.
# Only a new connection can use another country. Existing-item flows keep the
# item's own country, since they authorize against that item.
def requested_country_code
return @enable_banking_item.country_code unless action_name == "new_connection" || params[:new_connection] == "true"
code = params[:country_code].to_s.strip.upcase
EnableBankingItem::COUNTRY_CODES.include?(code) ? code : @enable_banking_item.country_code
end
def set_enable_banking_item
@enable_banking_item = Current.family.enable_banking_items.find(params[:id])
end
def enable_banking_item_params
permitted = params.require(:enable_banking_item).permit(
:name,
:sync_start_date,
:country_code,
:application_id,
:client_certificate
)
# The panel never pre-fills the stored credentials, so a blank one on
# update means "keep the current value".
if @enable_banking_item&.persisted?
%i[application_id client_certificate].each do |credential|
permitted.delete(credential) if permitted[credential].blank?
end
end
permitted
end
def enable_banking_callback_url
helpers.enable_banking_callback_url
end
end