Skip to content

Commit a308925

Browse files
Merge pull request #48 from authts/renames
renames and refactors
2 parents ee67b5c + 5691048 commit a308925

File tree

7 files changed

+50
-41
lines changed

7 files changed

+50
-41
lines changed

api/src/envUtils.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
export const requireEnvVar = (name: string): string => {
2+
const value = process.env[name];
3+
if (!value) {
4+
throw new Error(`Env var ${name} is required`);
5+
}
6+
return value;
7+
};

api/src/index.ts

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import express from 'express';
22
import morgan from 'morgan';
3+
import { requireEnvVar } from './envUtils.js';
34
import { verifyJwtMiddleware } from './jwtUtils.js';
45
import type { AugmentedRequest } from './types.js';
56

@@ -9,19 +10,17 @@ type CustomError = {
910

1011
const app = express();
1112

12-
// biome-ignore lint/style/noNonNullAssertion: We expect this env var to always be populated
13-
const port = Number(process.env.API_PORT!);
13+
const port = Number(requireEnvVar('API_PORT'));
1414

1515
app.use(morgan('tiny'));
1616

1717
app.get('/auth-well-known-config', async (_req, res) => {
1818
try {
19-
// biome-ignore lint/style/noNonNullAssertion: We expect this env var to always be populated
20-
const response = await fetch(process.env.API_AUTH_WELL_KNOWN_CONFIG_URL!, {
19+
const response = await fetch(requireEnvVar('API_AUTH_WELL_KNOWN_CONFIG_URL'), {
2120
headers: { accept: 'application/json' },
2221
});
2322
if (!response.ok) {
24-
return res.status(500).json({ error: `Unexpected response status: ${response.status}` } satisfies CustomError);
23+
throw new Error(`Unexpected response status: ${response.status}`);
2524
}
2625
const body = await response.json();
2726
return res.json(body);
@@ -33,7 +32,7 @@ app.get('/auth-well-known-config', async (_req, res) => {
3332

3433
app.get('/payload', verifyJwtMiddleware, (req, res) => {
3534
const data = (req as AugmentedRequest).payload;
36-
res.json(data);
35+
return res.json(data);
3736
});
3837

3938
const server = app.listen(port, () => {

api/src/jwtUtils.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
import type { NextFunction, Request, Response } from 'express';
22
import { type JWTVerifyGetKey, createRemoteJWKSet, jwtVerify } from 'jose';
3+
import { requireEnvVar } from './envUtils.js';
34
import type { AugmentedRequest } from './types.js';
45

5-
// biome-ignore lint/style/noNonNullAssertion: We expect this env var to always be populated
6-
const jsonWebKeySetUrl = process.env.API_AUTH_JSON_WEB_KEY_SET_URL!;
6+
const jsonWebKeySetUrl = requireEnvVar('API_AUTH_JSON_WEB_KEY_SET_URL');
77

88
// This function is cached so that the json web key set is not looked up on every request
99
let getJsonWebKeySet: JWTVerifyGetKey | null = null;

package-lock.json

Lines changed: 0 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@
22
"version": "2.0.0",
33
"scripts": {
44
"check": "biome check --write .",
5-
"toc": "markdown-toc -i README.md"
5+
"toc": "markdown-toc -i README.md",
6+
"docker-compose-all": "cp .env.sample .env && docker compose build && docker compose up"
67
},
78
"devDependencies": {
89
"@biomejs/biome": "^1.9.4",

react/src/components/ProtectedApp.tsx

Lines changed: 32 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { type FC, type ReactNode, useEffect, useState } from 'react';
33
import { hasAuthParams, useAuth } from 'react-oidc-context';
44
import { Alert } from './Alert.tsx';
55

6-
const queryFn = async () => {
6+
const getAuthHealth = async () => {
77
const response = await fetch('/api/auth-well-known-config');
88
if (!response.ok) {
99
throw new Error('Please confirm your auth server is up');
@@ -18,9 +18,9 @@ interface ProtectedAppProps {
1818
export const ProtectedApp: FC<ProtectedAppProps> = (props) => {
1919
const { children } = props;
2020

21-
const { isPending: metadataIsPending, error: metadataError } = useQuery({
22-
queryKey: ['getMetadata'],
23-
queryFn,
21+
const { isPending: getAuthHealthIsPending, error: getAuthHealthError } = useQuery({
22+
queryKey: ['getAuthHealth'],
23+
queryFn: getAuthHealth,
2424
retry: false,
2525
});
2626

@@ -33,37 +33,40 @@ export const ProtectedApp: FC<ProtectedAppProps> = (props) => {
3333
* See {@link https://github.com/authts/react-oidc-context?tab=readme-ov-file#automatic-sign-in}
3434
*/
3535
useEffect(() => {
36-
if (metadataIsPending || metadataError) {
36+
if (getAuthHealthIsPending || getAuthHealthError) {
3737
return;
3838
}
3939
if (!(hasAuthParams() || auth.isAuthenticated || auth.activeNavigator || auth.isLoading || hasTriedSignin)) {
4040
void auth.signinRedirect();
4141
setHasTriedSignin(true);
4242
}
43-
}, [auth, hasTriedSignin, metadataIsPending, metadataError]);
43+
}, [auth, hasTriedSignin, getAuthHealthIsPending, getAuthHealthError]);
4444

45-
const anyLoading = auth.isLoading || metadataIsPending;
46-
const anyErrorMessage = auth.error?.message || metadataError?.message;
45+
const anyLoading = getAuthHealthIsPending || auth.isLoading;
46+
const anyErrorMessage = getAuthHealthError?.message || auth.error?.message;
4747

48-
return (
49-
<>
50-
{anyErrorMessage ? (
51-
<>
52-
<h1>We've hit a snag</h1>
53-
<Alert variant="error">{anyErrorMessage}</Alert>
54-
</>
55-
) : anyLoading ? (
56-
<>
57-
<h1>Loading...</h1>
58-
</>
59-
) : auth.isAuthenticated ? (
60-
children
61-
) : (
62-
<>
63-
<h1>We've hit a snag</h1>
64-
<Alert variant="error">Unable to sign in</Alert>
65-
</>
66-
)}
67-
</>
68-
);
48+
if (anyLoading) {
49+
return (
50+
<>
51+
<h1>Loading...</h1>
52+
</>
53+
);
54+
}
55+
if (anyErrorMessage) {
56+
return (
57+
<>
58+
<h1>We've hit a snag</h1>
59+
<Alert variant="error">{anyErrorMessage}</Alert>
60+
</>
61+
);
62+
}
63+
if (!auth.isAuthenticated) {
64+
return (
65+
<>
66+
<h1>We've hit a snag</h1>
67+
<Alert variant="error">Unable to sign in</Alert>
68+
</>
69+
);
70+
}
71+
return <>{children}</>;
6972
};

react/src/main.tsx

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { QueryClientProvider } from '@tanstack/react-query';
22
import React from 'react';
3-
import reactDom from 'react-dom/client';
3+
import { createRoot } from 'react-dom/client';
44
import { AuthProvider } from 'react-oidc-context';
55
import { BrowserRouter } from 'react-router-dom';
66
import { App } from './components/App.tsx';
@@ -9,7 +9,7 @@ import { ProtectedApp } from './components/ProtectedApp.tsx';
99
import { onSigninCallback, queryClient, userManager } from './config.ts';
1010

1111
// biome-ignore lint/style/noNonNullAssertion: We expect this element to always exist
12-
reactDom.createRoot(document.getElementById('root')!).render(
12+
createRoot(document.getElementById('root')!).render(
1313
<React.StrictMode>
1414
<BrowserRouter basename="/">
1515
<AuthProvider userManager={userManager} onSigninCallback={onSigninCallback}>

0 commit comments

Comments
 (0)