Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/components/collections/href.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export default function CollectionsHref({ href }: { href: string }) {
queryFn: async ({ pageParam }) => {
if (pageParam) {
const headers: Record<string, string> = {};
const token = getAccessToken();
const token = getAccessToken(pageParam);
if (token) headers["Authorization"] = `Bearer ${token}`;
return await fetch(pageParam, { headers }).then((response) => {
if (response.ok) return response.json();
Expand Down
97 changes: 96 additions & 1 deletion src/components/ui/settings.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,22 @@
import type { IconButtonProps } from "@chakra-ui/react";
import {
Box,
CloseButton,
Dialog,
Field,
Flex,
HStack,
IconButton,
Input,
Portal,
Separator,
Switch,
Text,
} from "@chakra-ui/react";
import * as React from "react";
import { LuSettings } from "react-icons/lu";
import { LuPlus, LuSettings, LuTrash2 } from "react-icons/lu";
import { useStore } from "../../store";
import { authConfig } from "./auth";

interface SettingsButtonProps extends Omit<IconButtonProps, "aria-label"> {}

Expand Down Expand Up @@ -79,6 +85,12 @@ export const SettingsButton = React.forwardRef<
</Text>
</Field.HelperText>
</Field.Root>
{!authConfig && (
<>
<Separator my={4} />
<TokensSection />
</>
)}
</Dialog.Body>
<Dialog.CloseTrigger asChild>
<CloseButton size="sm" />
Expand All @@ -89,3 +101,86 @@ export const SettingsButton = React.forwardRef<
</Dialog.Root>
);
});

function TokensSection() {
const tokens = useStore((store) => store.tokens);
const setToken = useStore((store) => store.setToken);
const removeToken = useStore((store) => store.removeToken);
const href = useStore((store) => store.href);

const defaultBaseUri = React.useMemo(() => {
if (!href) return "";
try {
return new URL(href).origin;
} catch {
return "";
}
}, [href]);

const [baseUri, setBaseUri] = React.useState("");
const [tokenValue, setTokenValue] = React.useState("");

const handleAdd = () => {
const uri = baseUri.trim() || defaultBaseUri;
const val = tokenValue.trim();
if (!uri || !val) return;
setToken(uri, val);
setBaseUri("");
setTokenValue("");
};

const entries = Object.entries(tokens);

return (
<Box>
<Text fontWeight="medium" mb={2}>
Access tokens
</Text>
<Text fontSize="sm" color="fg.muted" mb={3}>
Provide Bearer tokens for authenticated STAC APIs.
</Text>
{entries.length > 0 && (
<Box mb={3}>
{entries.map(([uri]) => (
<Flex key={uri} align="center" justify="space-between" py={1}>
<Text fontSize="sm" truncate>
{uri}
</Text>
<IconButton
aria-label={`Remove token for ${uri}`}
size="xs"
variant="ghost"
onClick={() => removeToken(uri)}
>
<LuTrash2 />
</IconButton>
</Flex>
))}
</Box>
)}
<HStack>
<Input
placeholder={defaultBaseUri || "https://api.example.com"}
size="sm"
value={baseUri}
onChange={(e) => setBaseUri(e.target.value)}
/>
<Input
placeholder="Token"
size="sm"
type="password"
value={tokenValue}
onChange={(e) => setTokenValue(e.target.value)}
/>
<IconButton
aria-label="Add token"
size="sm"
variant="outline"
onClick={handleAdd}
>
<LuPlus />
</IconButton>
</HStack>
</Box>
);
}
4 changes: 4 additions & 0 deletions src/store/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
createStacGeoparquetState,
type StacGeoparquetState,
} from "./stac-geoparquet";
import { createTokensSlice, type TokensState } from "./tokens";
import {
createUploadedFileSlice,
type UploadedFileState,
Expand All @@ -40,6 +41,7 @@ export interface State
MapState,
SettingsState,
StacGeoparquetState,
TokensState,
WebMapLinksState {
fillColor: [number, number, number, number];
lineColor: [number, number, number, number];
Expand All @@ -64,6 +66,7 @@ export const useStore = create<State>()(
...createDatetimeSlice(...a),
...createMapSlice(...a),
...createSettingsSlice(...a),
...createTokensSlice(...a),
...createWebMapLinksSlice(...a),
fillColor: [207, 63, 2, 50] as [number, number, number, number],
lineColor: [207, 63, 2, 100] as [number, number, number, number],
Expand All @@ -74,6 +77,7 @@ export const useStore = create<State>()(
partialize: (state) => ({
restrictToThreeBandCogs: state.restrictToThreeBandCogs,
hivePartitioning: state.hivePartitioning,
tokens: state.tokens,
}),
}
)
Expand Down
22 changes: 22 additions & 0 deletions src/store/tokens.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import type { StateCreator } from "zustand";
import type { State } from ".";

export interface TokensState {
tokens: Record<string, string>;
setToken: (baseUri: string, token: string) => void;
removeToken: (baseUri: string) => void;
}

export const createTokensSlice: StateCreator<State, [], [], TokensState> = (
set,
get
) => ({
tokens: {},
setToken: (baseUri, token) =>
set({ tokens: { ...get().tokens, [baseUri]: token } }),
removeToken: (baseUri) => {
const tokens = { ...get().tokens };
delete tokens[baseUri];
set({ tokens });
},
});
31 changes: 23 additions & 8 deletions src/utils/auth.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,31 @@
import { User } from "oidc-client-ts";
import { useStore } from "../store";

export function getAccessToken(): string | null {
export function getAccessToken(href?: string | URL): string | null {
const authority = import.meta.env.VITE_AUTH_AUTHORITY;
const clientId = import.meta.env.VITE_AUTH_CLIENT_ID;
if (!authority || !clientId) return null;

const oidcStorage = sessionStorage.getItem(
`oidc.user:${authority}:${clientId}`
);
if (oidcStorage) {
const user = User.fromStorageString(oidcStorage);
return user?.access_token ?? null;
if (authority && clientId) {
const oidcStorage = sessionStorage.getItem(
`oidc.user:${authority}:${clientId}`
);
if (oidcStorage) {
const user = User.fromStorageString(oidcStorage);
return user?.access_token ?? null;
}
return null;
}

if (href) {
try {
const url = new URL(href.toString());
const baseUri = url.origin;
const tokens = useStore.getState().tokens;
return tokens[baseUri] ?? null;
} catch {
return null;
}
}

return null;
}
2 changes: 1 addition & 1 deletion src/utils/stac.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ export async function fetchStac({
body?: string;
}): Promise<StacValue> {
const headers: Record<string, string> = { Accept: "application/json" };
const token = getAccessToken();
const token = getAccessToken(href);
if (token) headers["Authorization"] = `Bearer ${token}`;

return await fetch(href, {
Expand Down