Re-authorize when token is invalid

This commit is contained in:
Râu Cao 2022-12-23 15:14:24 +07:00
parent e62bf67262
commit e1aaa2c434
Signed by: raucao
GPG Key ID: 15E65F399D084BA9
2 changed files with 20 additions and 6 deletions

View File

@ -28,13 +28,13 @@ class WalletController < ApplicationController
private private
def authenticate_with_lndhub def authenticate_with_lndhub(options={})
if session["ln_auth_token"].present? if session[:ln_auth_token].present? && !options[:force_reauth]
@ln_auth_token = session["ln_auth_token"] @ln_auth_token = session[:ln_auth_token]
else else
lndhub = Lndhub.new lndhub = Lndhub.new
auth_token = lndhub.authenticate(current_user) auth_token = lndhub.authenticate(current_user)
session["ln_auth_token"] = auth_token session[:ln_auth_token] = auth_token
@ln_auth_token = auth_token @ln_auth_token = auth_token
end end
rescue rescue
@ -49,14 +49,23 @@ class WalletController < ApplicationController
lndhub = Lndhub.new lndhub = Lndhub.new
data = lndhub.balance @ln_auth_token data = lndhub.balance @ln_auth_token
@balance = data["BTC"]["AvailableBalance"] rescue nil @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 end
def fetch_transactions def fetch_transactions
lndhub = Lndhub.new lndhub = Lndhub.new
txs = lndhub.gettxs @ln_auth_token txs = lndhub.gettxs @ln_auth_token
invoices = lndhub.getuserinvoices(@ln_auth_token).select{|i| i["ispaid"]} invoices = lndhub.getuserinvoices(@ln_auth_token).select{|i| i["ispaid"]}
process_transactions(txs + invoices) process_transactions(txs + invoices)
rescue
authenticate_with_lndhub(force_reauth: true)
return [] if @fetch_transactions_retried
@fetch_transactions_retried = true
fetch_transactions
end end
def process_transactions(txs) def process_transactions(txs)

View File

@ -28,8 +28,13 @@ class Lndhub
"Accept" => "application/json", "Accept" => "application/json",
"Authorization" => "Bearer #{auth_token}" "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 end
def create(payload) def create(payload)