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: 2 additions & 0 deletions .env.development
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
VITE_PETSTORE_URL=https://localhost
VITE_OIDC_AUTHORITY=http://keycloak:8080/realms/petstore
VITE_OIDC_CLIENT_ID=petstore-frontend
2 changes: 2 additions & 0 deletions .env.production
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
VITE_PETSTORE_URL=https://petstore.production
VITE_OIDC_AUTHORITY=https://keycloak.production/realms/petstore
VITE_OIDC_CLIENT_ID=petstore-frontend
2 changes: 2 additions & 0 deletions .env.test
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
VITE_PETSTORE_URL=https://petstore.test
VITE_OIDC_AUTHORITY=https://keycloak.test/realms/petstore
VITE_OIDC_CLIENT_ID=petstore-frontend
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
"cross-fetch": "^4.1.0",
"date-fns": "^4.4.0",
"nock": "^14.0.16",
"oidc-client-ts": "^3.5.0",
"qs": "^6.15.3",
"solid-js": "^1.9.14",
"zod": "^4.4.3"
Expand Down
17 changes: 17 additions & 0 deletions pnpm-lock.yaml

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

44 changes: 41 additions & 3 deletions src/app.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
import type { Component } from 'solid-js';
import { createSignal } from 'solid-js';
import { createSignal, Show } from 'solid-js';
import type { RouteSectionProps } from '@solidjs/router';
import { A } from '@solidjs/router';
import { useOidc } from './hook/use-oidc';
import { HttpError as HttpErrorPartial } from './component/partial/http-error';
import { HttpError } from './client/error';
import { H1 } from './component/heading';
import { Button } from './component/button';

const App: Component<RouteSectionProps> = (props: RouteSectionProps) => {
const [getDisplayMenu, setDisplayMenu] = createSignal<boolean>(false);
const oidc = useOidc();

const toggleMenu = () => {
setDisplayMenu(!getDisplayMenu());
Expand All @@ -15,14 +21,24 @@ const App: Component<RouteSectionProps> = (props: RouteSectionProps) => {
<nav class="absolute flow-root h-16 w-full bg-gray-900 px-4 py-3 text-2xl leading-relaxed font-semibold text-gray-100 uppercase">
<button
type="button"
class="float-right block border-2 p-2 md:hidden"
class="float-right ml-4 block border-2 p-2 md:hidden"
data-testid="navigation-toggle"
onClick={toggleMenu}
>
<span class="block h-2 w-6 border-t-2" />
<span class="block h-2 w-6 border-t-2" />
<span class="block h-0 w-6 border-t-2" />
</button>
<Show when={oidc.isAuthenticated}>
<button
type="button"
data-testid="navigation-logout"
class="float-right ml-4 border-2 px-3 py-1 text-base leading-relaxed hover:bg-gray-700"
onClick={oidc.logout}
>
Logout
</button>
</Show>
<A href="/" class="hover:text-gray-500">
Petstore
</A>
Expand All @@ -44,7 +60,29 @@ const App: Component<RouteSectionProps> = (props: RouteSectionProps) => {
</ul>
</nav>
<div class={`w-full px-6 py-8 md:w-2/3 lg:w-3/4 xl:w-4/5 ${getDisplayMenu() ? 'mt-0' : 'mt-16'}`}>
{props.children}
<Show when={oidc.error}>
{(getError) => (
<HttpErrorPartial
httpError={new HttpError({ title: 'Authentication failed', detail: getError().message })}
/>
)}
</Show>
<Show when={!oidc.isLoading}>
<Show
when={oidc.isAuthenticated}
fallback={
<div data-testid="login-required">
<H1>Login</H1>
<p class="mb-4">You need to login to use the petstore.</p>
<Button data-testid="login" colorTheme="blue" onClick={oidc.login}>
Login
</Button>
</div>
}
>
{props.children}
</Show>
</Show>
</div>
</div>
);
Expand Down
44 changes: 43 additions & 1 deletion src/client/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,32 @@ import { throwableToError } from '@chubbyts/chubbyts-throwable-to-error/dist/thr
import qs from 'qs';
import type { z } from 'zod';
import type { HttpError } from './error';
import { BadRequest, InternalServerError, NetworkError, NotFound, UnprocessableEntity } from './error';
import { BadRequest, InternalServerError, NetworkError, NotFound, Unauthorized, UnprocessableEntity } from './error';

export type Fetch = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;

export type GetAccessToken = () => Promise<string | undefined>;

export const createAuthenticatedFetch = (fetch: Fetch, getAccessToken: GetAccessToken): Fetch => {
return async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
const accessToken = await getAccessToken();

if (!accessToken) {
return fetch(input, init);
}

const headers = new Headers(init?.headers);
headers.set('Authorization', `Bearer ${accessToken}`);

return fetch(input, { ...init, headers: Object.fromEntries(headers.entries()) });
};
};

// the api responds without a body, but with a www-authenticate header
const createUnauthorized = (): Unauthorized => {
return new Unauthorized({ title: 'Unauthorized', detail: 'The access token is missing, invalid or expired' });
};

export type ListClient<ModelListRequest, ModelListResponse> = (
modelListRequest: ModelListRequest,
) => Promise<HttpError | ModelListResponse>;
Expand All @@ -30,6 +52,10 @@ export const createListClient = <
},
});

if (401 === response.status) {
return createUnauthorized();
}

const json = await response.json();

if (200 === response.status) {
Expand Down Expand Up @@ -72,6 +98,10 @@ export const createCreateClient = <ModelRequestSchema extends z.ZodObject, Model
body: JSON.stringify(modelRequestSchema.parse(modelRequest)),
});

if (401 === response.status) {
return createUnauthorized();
}

const json = await response.json();

if (201 === response.status) {
Expand Down Expand Up @@ -113,6 +143,10 @@ export const createReadClient = <ModelResponseSchema extends z.ZodObject>(
},
});

if (401 === response.status) {
return createUnauthorized();
}

const json = await response.json();

if (200 === response.status) {
Expand Down Expand Up @@ -159,6 +193,10 @@ export const createUpdateClient = <ModelRequestSchema extends z.ZodObject, Model
body: JSON.stringify(modelRequestSchema.parse(modelRequest)),
});

if (401 === response.status) {
return createUnauthorized();
}

const json = await response.json();

if (200 === response.status) {
Expand Down Expand Up @@ -204,6 +242,10 @@ export const createDeleteClient = (fetch: Fetch, url: string): DeleteClient => {
return;
}

if (401 === response.status) {
return createUnauthorized();
}

const json = await response.json();

if (404 === response.status) {
Expand Down
2 changes: 2 additions & 0 deletions src/client/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ export class NetworkError extends HttpError {}

export class NotFound extends HttpError {}

export class Unauthorized extends HttpError {}

export class UnprocessableEntity extends BadRequestOrUnprocessableEntity {}

export const createInvalidParametersByName = (
Expand Down
5 changes: 4 additions & 1 deletion src/client/pet.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
import { fetch } from 'cross-fetch';
import { fetch as crossFetch } from 'cross-fetch';
import { petListRequestSchema, petListResponseSchema, petRequestSchema, petResponseSchema } from '../model/pet';
import { getAccessToken } from '../oidc';
import {
createAuthenticatedFetch,
createCreateClient,
createDeleteClient,
createListClient,
createReadClient,
createUpdateClient,
} from './client';

const fetch = createAuthenticatedFetch(crossFetch, getAccessToken);
const url = `${import.meta.env.VITE_PETSTORE_URL}/api/pets`;

export const listPetsClient = createListClient(fetch, url, petListRequestSchema, petListResponseSchema);
Expand Down
131 changes: 131 additions & 0 deletions src/hook/use-oidc.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
import type { ParentComponent } from 'solid-js';
import { createContext, onCleanup, onMount, useContext } from 'solid-js';
import { createStore } from 'solid-js/store';
import type { User, UserManager } from 'oidc-client-ts';
import { throwableToError } from '@chubbyts/chubbyts-throwable-to-error/dist/throwable-to-error';

export type OidcProviderProps = {
userManager: UserManager;
onSigninCallback?: (user: User | undefined) => Promise<void> | void;
};

export type Oidc = {
isLoading: boolean;
isAuthenticated: boolean;
error?: Error;
login: () => Promise<void>;
logout: () => Promise<void>;
};

type OidcState = {
isLoading: boolean;
isAuthenticated: boolean;
error: Error | undefined;
};

const OidcContext = createContext<Oidc>();

// check if returning back from authority server (response_mode: query)
const hasAuthParams = (): boolean => {
const searchParams = new URLSearchParams(window.location.search);

return Boolean((searchParams.get('code') || searchParams.get('error')) && searchParams.get('state'));
};

export const OidcProvider: ParentComponent<OidcProviderProps> = (props) => {
const [state, setState] = createStore<OidcState>({ isLoading: true, isAuthenticated: false, error: undefined });

const signinCallback = async (): Promise<User | undefined> => {
const user = await props.userManager.signinCallback();

if (props.onSigninCallback) {
await props.onSigninCallback(user);
}

return user;
};

const initialize = async (): Promise<void> => {
try {
const signedInUser = hasAuthParams() ? await signinCallback() : undefined;
const user = signedInUser ?? (await props.userManager.getUser());

setState({ isLoading: false, isAuthenticated: user ? !user.expired : false, error: undefined });
} catch (error) {
setState({ isLoading: false, error: throwableToError(error) });
}
};

const navigate = async (callback: () => Promise<void>): Promise<void> => {
setState({ isLoading: true });

try {
await callback();
} catch (error) {
setState({ error: throwableToError(error) });
} finally {
setState({ isLoading: false });
}
};

// event UserLoaded (e.g. initial load, silent renew success)
const handleUserLoaded = (user: User): void => {
setState({ isLoading: false, isAuthenticated: !user.expired, error: undefined });
};

// event UserUnloaded (e.g. userManager.removeUser) / UserSignedOut (e.g. user was signed out in background)
const handleUserUnloaded = (): void => {
setState({ isAuthenticated: false });
};

// event SilentRenewError (silent renew error)
const handleSilentRenewError = (error: Error): void => {
setState({ isLoading: false, error });
};

onMount(() => {
props.userManager.events.addUserLoaded(handleUserLoaded);
props.userManager.events.addUserUnloaded(handleUserUnloaded);
props.userManager.events.addUserSignedOut(handleUserUnloaded);
props.userManager.events.addSilentRenewError(handleSilentRenewError);

void initialize();
});

onCleanup(() => {
props.userManager.events.removeUserLoaded(handleUserLoaded);
props.userManager.events.removeUserUnloaded(handleUserUnloaded);
props.userManager.events.removeUserSignedOut(handleUserUnloaded);
props.userManager.events.removeSilentRenewError(handleSilentRenewError);
});

const oidc: Oidc = {
get isLoading() {
return state.isLoading;
},
get isAuthenticated() {
return state.isAuthenticated;
},
get error() {
return state.error;
},
// return to the current page after the login
login: () =>
navigate(() =>
props.userManager.signinRedirect({ redirect_uri: `${window.location.origin}${window.location.pathname}` }),
),
logout: () => navigate(() => props.userManager.signoutRedirect()),
};

return <OidcContext.Provider value={oidc}>{props.children}</OidcContext.Provider>;
};

export const useOidc = (): Oidc => {
const oidc = useContext(OidcContext);

if (!oidc) {
throw new Error('useOidc must be used within an OidcProvider');
}

return oidc;
};
Loading