Skip to content

Commit

Permalink
better handle invalid tokens
Browse files Browse the repository at this point in the history
  • Loading branch information
benthecarman committed Dec 19, 2024
1 parent c80f2dd commit 2a59994
Show file tree
Hide file tree
Showing 6 changed files with 57 additions and 44 deletions.
22 changes: 20 additions & 2 deletions src/api/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,27 @@ export const api = {
setToken(null);
localStorage.removeItem("token");
window.location.href = "/";
return;
}

return response.json();
return response;
},
post: async (url: string, body: any) => {
const response = await fetch(`${FAUCET_API_URL}/${url}`, {
method: "POST",
body: JSON.stringify(body),
headers: {
Authorization: `Bearer ${token()}`,
"Content-Type": "application/json",
},
});

if (response.status === 401) {
// Handle unauthorized
setToken(null);
localStorage.removeItem("token");
window.location.href = "/";
}

return response;
},
};
13 changes: 5 additions & 8 deletions src/components/Faucet.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Match, Switch, createSignal } from "solid-js";
import { createRouteAction, useSearchParams } from "solid-start";
import { token } from "~/stores/auth";
import {setToken, token} from "~/stores/auth";
import {api} from "~/api/client";

const FAUCET_API_URL = import.meta.env.VITE_FAUCET_API;

Expand Down Expand Up @@ -64,13 +65,9 @@ export function Faucet() {
// Strip surrounding quotation marks if they exist
toAddress = toAddress.replace(/^"|"$/g, '').trim();

const res = await fetch(`${FAUCET_API_URL}/api/onchain`, {
method: "POST",
body: JSON.stringify({ sats: howMuchSats, address: toAddress }),
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token()}`,
},
const res = await api.post("api/onchain", {
sats: howMuchSats,
address: toAddress,
});

if (!res.ok) {
Expand Down
12 changes: 3 additions & 9 deletions src/components/LnChannel.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { createSignal, Match, Switch } from "solid-js";
import { createRouteAction } from "solid-start";
import { token } from "~/stores/auth";
import {setToken, token} from "~/stores/auth";
import {api} from "~/api/client";

const FAUCET_API_URL = import.meta.env.VITE_FAUCET_API;

Expand Down Expand Up @@ -90,18 +91,11 @@ export function LnChannel() {
}
const pushAmount = Math.round(capacity / 100) * pushPercentage;

const res = await fetch(`${FAUCET_API_URL}/api/channel`, {
method: "POST",
body: JSON.stringify({
const res = await api.post("api/channel", {
push_amount: pushAmount,
capacity,
pubkey,
host,
}),
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${token()}`,
},
});

if (!res.ok) {
Expand Down
12 changes: 4 additions & 8 deletions src/components/LnFaucet.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { token } from "~/stores/auth";
import {setToken, token} from "~/stores/auth";
import { Match, Switch } from "solid-js";
import { createRouteAction } from "solid-start";
import {api} from "~/api/client";

const FAUCET_API_URL = import.meta.env.VITE_FAUCET_API;

Expand Down Expand Up @@ -67,13 +68,8 @@ export function LnFaucet() {
}

// const result = await payInvoice(bolt11);
const res = await fetch(`${FAUCET_API_URL}/api/lightning`, {
method: "POST",
body: JSON.stringify({ bolt11 }),
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${token()}`,
},
const res = await api.post("api/lightning", {
bolt11
});

if (!res.ok) {
Expand Down
21 changes: 8 additions & 13 deletions src/components/NWC.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { Match, Switch, createSignal } from "solid-js";
import { createRouteAction } from "solid-start";
import { token } from "~/stores/auth";

import NDK, { NDKEvent, NDKPrivateKeySigner } from "@nostr-dev-kit/ndk";
import {api} from "~/api/client";

const FAUCET_API_URL = import.meta.env.VITE_FAUCET_API;

Expand Down Expand Up @@ -94,7 +94,7 @@ async function publishMultiInvoiceRequest(invoices: string[], nwc: NWCInfo) {
event.content = JSON.stringify({
method: "multi_pay_invoice",
params: {
invoices: invoicesParam,
invoices: invoicesParam,
},
});
event.tags = [["p", nwc.npubHex]];
Expand All @@ -107,13 +107,8 @@ async function publishMultiInvoiceRequest(invoices: string[], nwc: NWCInfo) {


async function fetchBolt11(): Promise<{ bolt11: string }> {
const res = await fetch(`${FAUCET_API_URL}/api/bolt11`, {
method: "POST",
body: JSON.stringify({ amount_sats: 21 }),
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${token()}`,
},
const res = await api.post("api/bolt11", {
amount_sats: 21
});

if (!res.ok) {
Expand Down Expand Up @@ -148,7 +143,7 @@ function Zapper(props: { nwc: NWCInfo }) {
const bolt11 = (await fetchBolt11()).bolt11;
invoices.push(bolt11);
}
await publishMultiInvoiceRequest(invoices, props.nwc);
await publishMultiInvoiceRequest(invoices, props.nwc);
} catch (e) {
console.error(e);
}
Expand Down Expand Up @@ -195,8 +190,8 @@ function Zapper(props: { nwc: NWCInfo }) {
let keysendParams = [];
for (let i = 0; i < 3; i++) {
let keysendParam = {
id: String(Math.floor(Math.random() * 10000000)),
pubkey: "02465ed5be53d04fde66c9418ff14a5f2267723810176c9212b722e542dc1afb1b",
id: String(Math.floor(Math.random() * 10000000)),
pubkey: "02465ed5be53d04fde66c9418ff14a5f2267723810176c9212b722e542dc1afb1b",
amount: 42 * 1000
}
keysendParams.push(keysendParam)
Expand All @@ -219,7 +214,7 @@ function Zapper(props: { nwc: NWCInfo }) {

setLoading(false);
}

return (
<div class="rounded-xl p-4 flex flex-col items-center gap-2 bg-[rgba(0,0,0,0.5)] drop-shadow-blue-glow">
<Switch>
Expand Down
21 changes: 17 additions & 4 deletions src/routes/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,32 @@ import { NWC } from "~/components/NWC";
import {Match, onMount, Show, Switch} from "solid-js";
import {setToken, token} from "~/stores/auth";
import {AuthButton} from "~/components/AuthButton";
import {api} from "~/api/client";

onMount(() => {
// Handle auth callback
const params = new URLSearchParams(window.location.search);
const token = params.get("token");
const tk = params.get("token");

if (token) {
if (tk) {
// Store token in localStorage and state
localStorage.setItem("token", token);
setToken(token);
localStorage.setItem("token", tk);
setToken(tk);

// Clean up URL
window.history.replaceState({}, document.title, window.location.pathname);
} else if (token()) {
// check if token is still valid
api.get("auth/check").then(async res => {
let json = await res.json();
if (json.status === "OK") {
console.log("token still valid");
} else {
// Logout
localStorage.removeItem("token");
setToken(null);
}
});
}
});

Expand Down

0 comments on commit 2a59994

Please sign in to comment.