Skip to content
Merged

oidc #16

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 @@ -25,6 +25,7 @@
"@tanstack/react-query": "^5.101.4",
"cross-fetch": "^4.1.0",
"date-fns": "^4.4.0",
"oidc-client-ts": "^3.5.0",
"qs": "^6.15.3",
"react": "^19.2.8",
"react-dom": "^19.2.8",
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.

33 changes: 31 additions & 2 deletions src/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,15 @@
import { useState } from 'react';
import { NavLink } from 'react-router-dom';
import Routes from './routes';
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: FC = () => {
const [displayMenu, setDisplayMenu] = useState<boolean>(false);
const oidc = useOidc();

const toggleMenu = () => {
setDisplayMenu(!displayMenu);
Expand All @@ -15,14 +21,24 @@
<nav className="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"
className="float-right block border-2 p-2 md:hidden"
className="float-right ml-4 block border-2 p-2 md:hidden"
data-testid="navigation-toggle"
onClick={toggleMenu}
>
<span className="block h-2 w-6 border-t-2" />
<span className="block h-2 w-6 border-t-2" />
<span className="block h-0 w-6 border-t-2" />
</button>
{oidc.isAuthenticated ? (
<button
type="button"
data-testid="navigation-logout"
className="float-right ml-4 border-2 px-3 py-1 text-base leading-relaxed hover:bg-gray-700"
onClick={oidc.logout}
>
Logout
</button>
) : null}
<NavLink className="hover:text-gray-500" to="/">
Petstore
</NavLink>
Expand All @@ -49,7 +65,20 @@
</ul>
</nav>
<div className={`w-full px-6 py-8 md:w-2/3 lg:w-3/4 xl:w-4/5 ${displayMenu ? 'mt-0' : 'mt-16'}`}>
<Routes />
{oidc.error ? (
<HttpErrorPartial httpError={new HttpError({ title: 'Authentication failed', detail: oidc.error.message })} />
) : null}
{oidc.isLoading ? null : oidc.isAuthenticated ? (
<Routes />
) : (
<div data-testid="login-required">
<H1>Login</H1>
<p className="mb-4">You need to login to use the petstore.</p>
<Button data-testid="login" colorTheme="blue" onClick={oidc.login}>
Login
</Button>
</div>
)}

Check warning on line 81 in src/app.tsx

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Extract this nested ternary operation into an independent statement.

See more on https://sonarcloud.io/project/issues?id=chubbyts_react-petstore&issues=AaAWOtLvOyEnlKeULX6a&open=AaAWOtLvOyEnlKeULX6a&pullRequest=16
</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
Loading