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
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@diamondlightsource/sci-react-ui",
"version": "0.3.1-alpha.1",
"version": "0.3.1-alpha.3",
"files": [
"dist/"
],
Expand All @@ -27,6 +27,7 @@
"storybook:publish": "gh-pages -b storybook/publish -d storybook-static"
},
"dependencies": {
"keycloak-js": "^26.2.1",
"react-icons": "^5.3.0",
"utif": "^3.1.0"
},
Expand Down
8 changes: 8 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion src/components/navigation/Footer.stories.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Meta, StoryObj } from "@storybook/react/*";
import { Meta, StoryObj } from "@storybook/react";
import { Footer, FooterLink, FooterLinks } from "./Footer";
import { MockLink } from "../../utils/MockLink";

Expand Down
96 changes: 96 additions & 0 deletions src/components/systems/auth/AuthProvider.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import { screen } from "@testing-library/react";

import { renderWithProviders } from "../../../__test-utils__/helpers";

import { AuthProvider } from "./AuthProvider";
import { useAuth, useToken } from "./auth";

describe("AuthProvider useAuth", () => {
const TestProvider = () => {
const auth = useAuth();
if (!auth.authenticated) return <>{"Not Authenticated"}</>;
return <></>;
};
it("should be able to use useAuth", async () => {
renderWithProviders(
<AuthProvider
keycloakConfig={{
url: "_",
realm: "_",
clientId: "_",
}}
keycloakInitOptions={{
onLoad: undefined,
}}
>
<TestProvider />
</AuthProvider>,
);
expect(await screen.findByText("Not Authenticated")).toBeInTheDocument();
});

it("should be able to use useAuth with settings", async () => {
renderWithProviders(
<AuthProvider
keycloakConfig={{
url: "_",
realm: "_",
clientId: "_",
}}
keycloakInitOptions={{
onLoad: undefined,
}}
onTokenChange={() => {}}
minimumSecondsLeftInToken={15}
>
<TestProvider />
</AuthProvider>,
);
expect(await screen.findByText("Not Authenticated")).toBeInTheDocument();
});
});

describe("AuthProvider useToken", () => {
const TestProvider = () => {
const token = useToken();
return <div data-testid="token">{token}</div>;
};

it("should be able to use useToken", async () => {
renderWithProviders(
<AuthProvider
keycloakConfig={{
url: "_",
realm: "_",
clientId: "_",
}}
keycloakInitOptions={{
onLoad: undefined,
}}
>
<TestProvider />
</AuthProvider>,
);
expect(await screen.findByTestId("token")).toBeInTheDocument();
});

it("should be able to use useAuth with settings", async () => {
renderWithProviders(
<AuthProvider
keycloakConfig={{
url: "_",
realm: "_",
clientId: "_",
}}
keycloakInitOptions={{
onLoad: undefined,
}}
onTokenChange={() => {}}
minimumSecondsLeftInToken={15}
>
<TestProvider />
</AuthProvider>,
);
expect(await screen.findByTestId("token")).toBeInTheDocument();
});
});
87 changes: 87 additions & 0 deletions src/components/systems/auth/AuthProvider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import { PropsWithChildren, useEffect, useState } from "react";
import Keycloak, {
KeycloakServerConfig,
KeycloakError,
KeycloakInitOptions,
} from "keycloak-js";
import {
AuthContext,
AuthTokenContext,
Auth,
init,
onAuthLogout,
onAuthSuccess,
onAuthRefreshSuccess,
onError,
updateAuth,
} from "./auth";

export interface AuthProviderSettings {
/* call function when token is set, renewed or cleared */
onTokenChange?: (token: string) => void;
/* Renew token before it expires by this amount, default 10s */
minimumSecondsLeftInToken?: number;
}

export interface AuthProviderProps
extends AuthProviderSettings,
PropsWithChildren {
/* Main Keycloak.js config file. */
keycloakConfig: KeycloakServerConfig;
/* Keycloak.js initiate options. */
keycloakInitOptions?: KeycloakInitOptions;
}

export const AuthProvider = ({
children,
keycloakConfig,
keycloakInitOptions,
...settings
}: AuthProviderProps) => {
const [auth, setAuth] = useState<Auth>(updateAuth(null));
const [token, setAuthToken] = useState<string | null>(null);

const keycloak = new Keycloak({ ...keycloakConfig });

const tokenChanged = (): void => {
const token =
keycloak.authenticated && keycloak.token ? keycloak.token : "";
setAuthToken(token);
if (settings.onTokenChange) settings.onTokenChange(token);
};

keycloak.onAuthRefreshSuccess = () => {
onAuthRefreshSuccess(keycloak, settings);
tokenChanged();
};
keycloak.onAuthSuccess = () => {
setAuth(onAuthSuccess(keycloak, settings));
tokenChanged();
};
keycloak.onAuthLogout = () => {
setAuth(onAuthLogout(keycloak, settings));
tokenChanged();
};

keycloak.onAuthError = (error: KeycloakError) => {
const authChanged = onError(keycloak, "Auth error: " + error);
if (authChanged) setAuth(authChanged);
};

useEffect(() => {
if (!keycloak.didInitialize) {
init(keycloak, keycloakInitOptions).then((auth) => {
if (auth) setAuth(auth);
tokenChanged();
});
}
}, []);

return (
<AuthContext.Provider value={auth}>
<AuthTokenContext.Provider value={token}>
{children}
</AuthTokenContext.Provider>
</AuthContext.Provider>
);
};
Loading