Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add configurable backend URL #1050

Merged
merged 2 commits into from
Jun 2, 2023
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 src/config/Config.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
export const BACKEND_URL = process.env.REACT_APP_BACKEND_URL ?? 'http://localhost:5000';
export const DEMO_MODE = process.env.REACT_APP_TARGET === 'demo';
export const ALT_AUTH = process.env.REACT_APP_ALT_AUTH === 'plg';
type ConfigDeployment = 'dev' | 'prod' | undefined;
export const DEPLOYMENT: ConfigDeployment = process.env.REACT_APP_DEPLOYMENT as ConfigDeployment;
133 changes: 85 additions & 48 deletions src/services/AuthService.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { ReactNode, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { ReactNode, useCallback, useEffect, useMemo, useState } from 'react';
import { createGenericContext } from './GenericContext';
import ky, { HTTPError } from 'ky';
import { KyInstance } from 'ky/distribution/types/ky';
import { BACKEND_URL, DEMO_MODE } from '../config/Config';
import { BACKEND_URL, DEMO_MODE, DEPLOYMENT } from '../config/Config';
import { snakeToCamelCase } from '../types/TypeTransformUtil';
import { RequestAuthLogin, RequestAuthLogout, RequestAuthRefresh } from '../types/RequestTypes';
import useIntervalAsync from '../util/hooks/useIntervalAsync';
Expand All @@ -14,6 +14,12 @@ import {
YaptideResponse
} from '../types/ResponseTypes';

declare global {
interface Window {
BACKEND_URL?: string;
}
}

export interface AuthProps {
children: ReactNode;
}
Expand Down Expand Up @@ -60,57 +66,87 @@ const Auth = ({ children }: AuthProps) => {
const [isServerReachable, setIsServerReachable] = useState<boolean | null>(null);
const { enqueueSnackbar } = useSnackbar();

const [backendUrl, setBackendUrl] = useState<string>(BACKEND_URL);

useEffect(() => {
setReachInterval(isServerReachable ? 180000 : 30000);
}, [isServerReachable]);

const kyRef = useRef<KyInstance>(
ky.create({
credentials: 'include',
prefixUrl: BACKEND_URL,
//overwrite default json parser to convert snake_case to camelCase
parseJson: (text: string) => snakeToCamelCase(JSON.parse(text), true),
hooks: {
afterResponse: [
async (_request, _options, response) => {
switch (response?.status) {
case 401:
enqueueSnackbar('Please log in.', { variant: 'warning' });
setUser(null);
break;
case 403:
enqueueSnackbar('Please log in again.', { variant: 'warning' });
setUser(null);
break;
const kyRef = useMemo(
() =>
ky.create({
credentials: 'include',
prefixUrl: backendUrl,
//overwrite default json parser to convert snake_case to camelCase
parseJson: (text: string) => snakeToCamelCase(JSON.parse(text), true),
hooks: {
afterResponse: [
async (_request, _options, response) => {
switch (response?.status) {
case 401:
enqueueSnackbar('Please log in.', { variant: 'warning' });
setUser(null);
break;
case 403:
enqueueSnackbar('Please log in again.', { variant: 'warning' });
setUser(null);
break;
}
if (response?.status > 300) {
const message = await response.json().then(r => r.message);
if (message !== 'No token provided')
enqueueSnackbar(await response.json().then(r => r.message), {
variant: 'error'
});
console.error(
response.status,
await response.json().then(r => r.message)
);
}
}
if (response?.status > 300) {
const message = await response.json().then(r => r.message);
if (message !== 'No token provided')
enqueueSnackbar(await response.json().then(r => r.message), {
variant: 'error'
});
console.error(
response.status,
await response.json().then(r => r.message)
);
}
}
]
}
})
]
}
}),
[backendUrl, enqueueSnackbar]
);

const kyIntervalRef = useMemo(
() =>
kyRef.extend({
retry: 0
}),
[kyRef]
);
const kyIntervalRef = useRef<KyInstance>(
kyRef.current.extend({
retry: 0
})

const setBackendUrlCallback = useCallback(
(url: string) => {
setBackendUrl(url);
},
[setBackendUrl]
);

// Enable backend url change in dev mode
if (DEPLOYMENT === 'dev') {
// eslint-disable-next-line react-hooks/rules-of-hooks
useEffect(() => {
Object.defineProperty(window, 'BACKEND_URL', {
set: function (url: string) {
setBackendUrlCallback(url);
},
get: function () {
return backendUrl;
},
configurable: true
});
}, [backendUrl, setBackendUrlCallback]);
}

useEffect(() => {
if (DEMO_MODE) enqueueSnackbar('Demo mode enabled.', { variant: 'info' });
}, [enqueueSnackbar]);

const reachServer = useCallback(() => {
return kyIntervalRef.current
return kyIntervalRef
.get(``)
.json<YaptideResponse>()
.then(r => !!r.message)
Expand All @@ -124,7 +160,7 @@ const Auth = ({ children }: AuthProps) => {
})
)
.catch(() => setIsServerReachable(false));
}, [enqueueSnackbar]);
}, [enqueueSnackbar, kyIntervalRef]);

useIntervalAsync(reachServer, reachInterval);
useEffect(() => {
Expand All @@ -133,12 +169,12 @@ const Auth = ({ children }: AuthProps) => {

const refresh = useCallback(() => {
if (DEMO_MODE || !isServerReachable) return Promise.resolve(setRefreshInterval(undefined));
return kyIntervalRef.current
return kyIntervalRef
.get(`auth/refresh`)
.json<ResponseAuthRefresh>()
.then(({ accessExp }) => setRefreshInterval(getRefreshDelay(accessExp)))
.catch((_: HTTPError) => {});
}, [isServerReachable]);
}, [isServerReachable, kyIntervalRef]);

useEffect(() => {
if (user !== null && refreshInterval === undefined && isServerReachable)
Expand All @@ -148,7 +184,7 @@ const Auth = ({ children }: AuthProps) => {

const login = useCallback(
(...[username, password]: RequestAuthLogin) => {
kyRef.current
kyRef
.post(`auth/login`, {
json: { username, password }
})
Expand All @@ -160,17 +196,18 @@ const Auth = ({ children }: AuthProps) => {
})
.catch((_: HTTPError) => {});
},
[enqueueSnackbar]
[enqueueSnackbar, kyRef]
);

const logout = useCallback(() => {
kyRef.current
kyRef
.delete(`auth/logout`)
.json<YaptideResponse>()
.then(_response => setUser(null))
.catch((_: HTTPError) => {});
}, []);
const authKy = useMemo(() => kyRef.current, []);
}, [kyRef]);

const authKy = useMemo(() => kyRef, [kyRef]);
const isAuthorized = useMemo(() => user !== null || DEMO_MODE, [user]);

useEffect(() => {
Expand Down