From e1aaa2c43403cc0b1a4d3f04a5f27aa7cb740032 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A2u=20Cao?= Date: Fri, 23 Dec 2022 15:14:24 +0700 Subject: [PATCH] Re-authorize when token is invalid --- app/controllers/wallet_controller.rb | 19 ++++++++++++++----- app/services/lndhub.rb | 7 ++++++- 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/app/controllers/wallet_controller.rb b/app/controllers/wallet_controller.rb index 4990894..535eed1 100644 --- a/app/controllers/wallet_controller.rb +++ b/app/controllers/wallet_controller.rb @@ -28,13 +28,13 @@ class WalletController < ApplicationController private - def authenticate_with_lndhub - if session["ln_auth_token"].present? - @ln_auth_token = session["ln_auth_token"] + def authenticate_with_lndhub(options={}) + if session[:ln_auth_token].present? && !options[:force_reauth] + @ln_auth_token = session[:ln_auth_token] else lndhub = Lndhub.new auth_token = lndhub.authenticate(current_user) - session["ln_auth_token"] = auth_token + session[:ln_auth_token] = auth_token @ln_auth_token = auth_token end rescue @@ -49,14 +49,23 @@ class WalletController < ApplicationController lndhub = Lndhub.new data = lndhub.balance @ln_auth_token @balance = data["BTC"]["AvailableBalance"] rescue nil + rescue + authenticate_with_lndhub(force_reauth: true) + return nil if @fetch_balance_retried + @fetch_balance_retried = true + fetch_balance end def fetch_transactions lndhub = Lndhub.new txs = lndhub.gettxs @ln_auth_token invoices = lndhub.getuserinvoices(@ln_auth_token).select{|i| i["ispaid"]} - process_transactions(txs + invoices) + rescue + authenticate_with_lndhub(force_reauth: true) + return [] if @fetch_transactions_retried + @fetch_transactions_retried = true + fetch_transactions end def process_transactions(txs) diff --git a/app/services/lndhub.rb b/app/services/lndhub.rb index 68f10be..c9547d3 100644 --- a/app/services/lndhub.rb +++ b/app/services/lndhub.rb @@ -28,8 +28,13 @@ class Lndhub "Accept" => "application/json", "Authorization" => "Bearer #{auth_token}" }) + data = JSON.parse(res.body) - JSON.parse(res.body) + if data.is_a?(Hash) && data["error"] && data["message"] == "bad auth" + raise "BAD_AUTH" + else + data + end end def create(payload)