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
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
"dependencies": {
"@blueprintjs/core": "5.7.1",
"@blueprintjs/select": "5.0.19",
"@braintree/sanitize-url": "^7.1.1",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-hotkeys-hook": "^4.6.1",
Expand Down
5 changes: 3 additions & 2 deletions src/components/Footer/Footer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,13 @@ import { useAuth } from "../../contexts/AuthContext";
import { useStorage } from "../../contexts/StorageContext/StorageContext";

const Footer: React.FC = () => {
const { authState } = useAuth();
const { authState, resetAuth } = useAuth();
const { settings } = useStorage();

const handleLogout = () => {
const signoutUrl = `${settings.signadotUrls.dashboardUrl}/signout`;
const signoutUrl = new URL(`/signout`, settings.signadotUrls.dashboardUrl).toString();
window.open(signoutUrl, '_blank');
resetAuth();
};

return (
Expand Down
10 changes: 5 additions & 5 deletions src/components/Frame/Frame.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ const Home = () => {
<ListRouteEntries
routingEntities={routingEntities}
setUserSelectedRoutingEntity={(e) => setCurrentRoutingKey(e.routingKey)}
orgName={authState?.org.name}
orgName={authState.org?.name}
/>
<div className={styles.selectedEntity}>
{pinnedRoutingEntityData ? (
Expand All @@ -70,18 +70,18 @@ const Home = () => {
};

const Frame = () => {
const { authState, isLoading } = useAuth();
const { authState } = useAuth();
const { goToView } = useRouteView();

useEffect(() => {
if (isLoading) {
if (authState.status === "loading") {
goToView("loading");
} else if (authState) {
} else if (authState.status === "authenticated") {
goToView("home");
} else {
goToView("login");
}
}, [authState, isLoading]);
}, [authState]);

return (
<div className={styles.container}>
Expand Down
4 changes: 2 additions & 2 deletions src/components/Layout/Layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,15 @@ interface Props {

const Layout: React.FC<Props> = ({ children }) => {
const { currentView, goToView } = useRouteView();
const { init, settings, setSettings, isAuthenticated } = useStorage();
const { isStoreLoaded, settings, setSettings, isAuthenticated } = useStorage();
const { authState } = useAuth();

const handleHomeChange = () => {
return isAuthenticated ? "home" : "login";
};

return (
init && (
isStoreLoaded && (
<div className={styles.container}>
<div className={styles.topBar}>
<div className={styles.logoContainer}>
Expand Down
32 changes: 28 additions & 4 deletions src/components/ListRouteEntries/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,39 @@ export const useFetchRoutingEntries = () => {
data: sandboxes,
error: sandboxesError,
isLoading: sandboxesLoading,
} = useQuery<RoutingEntity[], ApiError>("sandboxes", () =>
fetchSandboxes(settings.signadotUrls.apiUrl || "", authState?.org.name || ""),
} = useQuery<RoutingEntity[], ApiError>(
"sandboxes",
() => {
if (authState.status !== "authenticated") {
throw new Error("Not authenticated");
}
if (!settings.signadotUrls.apiUrl) {
throw new Error("API URL not configured");
}
return fetchSandboxes(settings.signadotUrls.apiUrl, authState.org.name);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is much nicer to not have invalid calls made, thanks for the fix.

},
{
enabled: authState.status === "authenticated" && !!settings.signadotUrls.apiUrl
}
);
const {
data: routegroups,
error: routegroupsError,
isLoading: routegroupsLoading,
} = useQuery<RoutingEntity[], ApiError>("routegroups", () =>
fetchRouteGroups(settings.signadotUrls.apiUrl || "", authState?.org.name || ""),
} = useQuery<RoutingEntity[], ApiError>(
"routegroups",
() => {
if (authState.status !== "authenticated") {
throw new Error("Not authenticated");
}
if (!settings.signadotUrls.apiUrl) {
throw new Error("API URL not configured");
}
return fetchRouteGroups(settings.signadotUrls.apiUrl, authState.org.name);
},
{
enabled: authState.status === "authenticated" && !!settings.signadotUrls.apiUrl
}
);
// TODO: Handle error and loading too.

Expand Down
6 changes: 3 additions & 3 deletions src/components/ListRouteEntries/queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { getApiUrl } from "../Settings/api";

export const fetchSandboxes = async (apiUrl: string, orgName?: string): Promise<RoutingEntity[]> => {
return new Promise(async (resolve, reject) => {
fetch(`${apiUrl}/api/v2/orgs/${orgName}/sandboxes`)
fetch(new URL(`/api/v2/orgs/${orgName}/sandboxes`, apiUrl).toString())
.then((response) => {
if (!response.ok) {
throw new Error("Failed to fetch sandboxes");
Expand All @@ -20,7 +20,7 @@ export const fetchSandboxes = async (apiUrl: string, orgName?: string): Promise<

export const fetchRouteGroups = async (apiUrl: string, orgName?: string): Promise<RoutingEntity[]> => {
return new Promise(async (resolve, reject) => {
fetch(`${apiUrl}/api/v2/orgs/${orgName}/routegroups`)
fetch(new URL(`/api/v2/orgs/${orgName}/routegroups`, apiUrl).toString())
.then((response) => {
if (!response.ok) {
throw new Error("Failed to fetch route groups");
Expand All @@ -34,7 +34,7 @@ export const fetchRouteGroups = async (apiUrl: string, orgName?: string): Promis

export const fetchClusters = async (apiUrl: string, orgName: string): Promise<Cluster[]> => {
return new Promise(async (resolve, reject) => {
fetch(`${apiUrl}/api/v2/orgs/${orgName}/clusters`)
fetch(new URL(`/api/v2/orgs/${orgName}/clusters`, apiUrl).toString())
.then((response) => {
if (!response.ok) {
throw new Error("Failed to fetch clusters");
Expand Down
4 changes: 2 additions & 2 deletions src/components/PinnedRouteGroup/PinnedRouteGroup.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@ interface Props {
const getEntityDashboardURL = (dashboardUrl: string, routingEntity: RoutingEntity): string | undefined => {
switch (routingEntity.type) {
case RoutingEntityType.Sandbox:
return dashboardUrl + `/sandbox/name/${routingEntity.name}/overview`;
return new URL(`/sandbox/name/${routingEntity.name}/overview`, dashboardUrl).toString();
case RoutingEntityType.RouteGroup:
return dashboardUrl + `/routegroups/${routingEntity.name}`;
return new URL(`/routegroups/${routingEntity.name}`, dashboardUrl).toString();
}
return undefined;
};
Expand Down
15 changes: 11 additions & 4 deletions src/components/Settings/Settings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ import {
STAGING_SIGNADOT_PREVIEW_URL,
STAGING_SIGNADOT_DASHBOARD_URL,
} from "../../contexts/StorageContext/defaults";

import { useAuth } from "../../contexts/AuthContext";
import { sanitizeUrl } from "@braintree/sanitize-url";
const AUTH_SESSION_COOKIE_NAME = "signadot-auth";

type Environment = "production" | "staging" | "custom";
Expand Down Expand Up @@ -44,6 +45,7 @@ const Settings: React.FC<SettingsProps> = ({ onClose }) => {

const { settings, traceparent, setSettings, setTraceparent } = useStorage();
const [isExtraSettingsOpen, setIsExtraSettingsOpen] = React.useState(false);
const { resetAuth } = useAuth();

useHotkeys("ctrl+shift+u", () => setIsExtraSettingsOpen(!isExtraSettingsOpen), {
enableOnFormTags: true,
Expand Down Expand Up @@ -105,9 +107,14 @@ const Settings: React.FC<SettingsProps> = ({ onClose }) => {
const isReadOnly = selectedEnv === "production" || selectedEnv === "staging";

const handleSave = () => {
const cleanApiUrl = unsavedValues.apiUrl.replace(/\/+$/, "");
const cleanPreviewUrl = unsavedValues.previewUrl.replace(/\/+$/, "");
const cleanDashboardUrl = unsavedValues.dashboardUrl.replace(/\/+$/, "");
const cleanApiUrl = sanitizeUrl(unsavedValues.apiUrl);
const cleanPreviewUrl = sanitizeUrl(unsavedValues.previewUrl);
const cleanDashboardUrl = sanitizeUrl(unsavedValues.dashboardUrl);

// If there is a new apiUrl, we need to reset the auth state
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we can use a more robust mechanism like https://github.com/braintree/sanitize-url rather than just trimming the string. WDYT?

if (cleanApiUrl !== settings.signadotUrls.apiUrl || cleanPreviewUrl !== settings.signadotUrls.previewUrl || cleanDashboardUrl !== settings.signadotUrls.dashboardUrl) {
resetAuth();
}

setSettings({
enabled: settings.enabled,
Expand Down
94 changes: 60 additions & 34 deletions src/contexts/AuthContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,30 +2,31 @@ import React, { createContext, useContext, useEffect, useState } from "react";
import { auth } from "./auth";
import Layout from "../components/Layout/Layout";
import { useStorage } from "./StorageContext/StorageContext";
import { Intent, Spinner, SpinnerSize } from "@blueprintjs/core";

const loadingIconPath = chrome.runtime.getURL("images/loading.gif");

interface Props {
children: React.ReactNode;
}

interface AuthState {
org: {
name: string;
displayName?: string;
};
user: {
firstName?: string;
lastName?: string;
email?: string;
};
interface User {
firstName?: string;
lastName?: string;
email?: string;
}

interface Org {
name: string;
displayName?: string;
}

type AuthState =
| { status: "loading"; user: undefined; org: undefined }
| { status: "unauthenticated"; user: undefined; org: undefined }
| { status: "authenticated"; user: User; org: Org };

// Define the shape of the context
interface AuthContextType {
authState?: AuthState;
isLoading: boolean;
authState: AuthState;
resetAuth: () => void;
}

interface GetOrgsResponse {
Expand All @@ -51,31 +52,54 @@ const AuthContext = createContext<AuthContextType | undefined>(undefined);

// AuthProvider component
export const AuthProvider: React.FC<Props> = ({ children }) => {
const [authState, setAuthState] = useState<AuthState | undefined>(undefined);
const [authenticated, setAuthenticated] = useState<boolean | undefined>(undefined);
const [isLoading, setIsLoading] = useState(true);
const { settings, setIsAuthenticated } = useStorage();
const [authState, setAuthState] = useState<AuthState>({
status: "loading",
user: undefined,
org: undefined
});
const { settings, isStoreLoaded, setIsAuthenticated } = useStorage();
const { apiUrl, previewUrl } = settings.signadotUrls;

const resetAuth = () => {
setAuthState({
status: "unauthenticated",
user: undefined,
org: undefined
});
setIsAuthenticated(false);
};

useEffect(() => {
if (!apiUrl || !previewUrl) return;
if (!apiUrl || !previewUrl || !isStoreLoaded) return;

setAuthState({
status: "loading",
user: undefined,
org: undefined
});

auth(
async (authenticated) => {
if (!authenticated) {
console.log("Not authenticated!");
setAuthenticated(false);
setIsLoading(false);
setAuthState({
status: "unauthenticated",
user: undefined,
org: undefined
});
return;
}

try {
const response = await fetch(`${apiUrl}/api/v1/orgs`);
const response = await fetch(new URL("/api/v1/orgs", apiUrl).toString());

if (response.status === 401 || !response.ok) {
setAuthenticated(false);
setIsAuthenticated(false);
setIsLoading(false);
setAuthState({
status: "unauthenticated",
user: undefined,
org: undefined
});
return;
}

Expand All @@ -87,40 +111,42 @@ export const AuthProvider: React.FC<Props> = ({ children }) => {
}

setAuthState({
status: "authenticated",
org: data.orgs[0],
user: {
firstName: data.user.firstName?.String,
lastName: data.user.lastName?.String,
email: data.user.email
},
}
});

setAuthenticated(true);
setIsAuthenticated(true);
setIsLoading(false);
} catch (error) {
console.error("Error fetching org:", error);
setAuthenticated(false);
setIsAuthenticated(false);
setIsLoading(false);
setAuthState({
status: "unauthenticated",
user: undefined,
org: undefined
});
}
},
{ apiUrl, previewUrl },
);
}, [apiUrl, previewUrl]);
}, [apiUrl, previewUrl, isStoreLoaded]);

useEffect(() => {
if (authState === undefined) {
if (authState.status === "unauthenticated") {
setIsAuthenticated(false);
}

if (authState) {
if (authState.status === "authenticated") {
setIsAuthenticated(true);
}
}, [authState]);

return (
<AuthContext.Provider value={{ authState, isLoading }}>
<AuthContext.Provider value={{ authState, resetAuth }}>
<Layout>{children}</Layout>
</AuthContext.Provider>
);
Expand Down
8 changes: 3 additions & 5 deletions src/contexts/StorageContext/StorageContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,6 @@ export const StorageProvider: React.FC<StorageProviderProps> = ({ children }) =>

const [isStorageLoaded, setIsStorageLoaded] = useState(false);

useEffect(() => {
setIsStorageLoaded(true);
}, []);

// Load initial values from browser storage
useEffect(() => {
const loadInitialValues = async () => {
Expand Down Expand Up @@ -128,6 +124,8 @@ export const StorageProvider: React.FC<StorageProviderProps> = ({ children }) =>

return newState;
});

setIsStorageLoaded(true);
};

loadInitialValues();
Expand Down Expand Up @@ -175,7 +173,7 @@ export const StorageProvider: React.FC<StorageProviderProps> = ({ children }) =>
};

const value = {
init: isStorageLoaded,
isStoreLoaded: isStorageLoaded,
isAuthenticated: state.isAuthenticated,
settings: state.settings,
traceparent: state.traceparent,
Expand Down
Loading