mirror of
https://github.com/apricote/Listory.git
synced 2026-01-13 21:21:02 +00:00
feat(frontend): setup
This commit is contained in:
parent
db62d5d908
commit
f14eda16ac
33 changed files with 15076 additions and 22 deletions
26
frontend/src/App.js
Normal file
26
frontend/src/App.js
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
import React from "react";
|
||||
import { Route, Router, Switch } from "react-router-dom";
|
||||
import NavBar from "./components/NavBar";
|
||||
import PrivateRoute from "./components/PrivateRoute";
|
||||
import Profile from "./views/Profile";
|
||||
import ExternalApi from "./views/ExternalApi";
|
||||
import history from "./utils/history";
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<div className="App">
|
||||
<Router history={history}>
|
||||
<header>
|
||||
<NavBar />
|
||||
</header>
|
||||
<Switch>
|
||||
<Route path="/" exact />
|
||||
<PrivateRoute path="/profile" component={Profile} />
|
||||
<PrivateRoute path="/external-api" component={ExternalApi} />
|
||||
</Switch>
|
||||
</Router>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default App;
|
||||
5
frontend/src/auth_config.json
Normal file
5
frontend/src/auth_config.json
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
{
|
||||
"domain": "listory.eu.auth0.com",
|
||||
"clientId": "pYSTOYOsmenpCYj6TsRNQ8dprlqoQTt3",
|
||||
"audience": "https://listory.apricote.de/api/v1"
|
||||
}
|
||||
27
frontend/src/components/NavBar.js
Normal file
27
frontend/src/components/NavBar.js
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
import React from "react";
|
||||
import { useAuth0 } from "../react-auth0-spa";
|
||||
import { Link } from "react-router-dom";
|
||||
|
||||
const NavBar = () => {
|
||||
const { isAuthenticated, loginWithRedirect, logout } = useAuth0();
|
||||
|
||||
return (
|
||||
<div>
|
||||
{!isAuthenticated && (
|
||||
<button onClick={() => loginWithRedirect({})}>Log in</button>
|
||||
)}
|
||||
|
||||
{isAuthenticated && <button onClick={() => logout()}>Log out</button>}
|
||||
|
||||
{isAuthenticated && (
|
||||
<span>
|
||||
<Link to="/">Home</Link>
|
||||
<Link to="/profile">Profile</Link>
|
||||
<Link to="/external-api">External API</Link>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default NavBar;
|
||||
26
frontend/src/components/PrivateRoute.js
Normal file
26
frontend/src/components/PrivateRoute.js
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
import React, { useEffect } from "react";
|
||||
import { Route } from "react-router-dom";
|
||||
import { useAuth0 } from "../react-auth0-spa";
|
||||
|
||||
const PrivateRoute = ({ component: Component, path, ...rest }) => {
|
||||
const { loading, isAuthenticated, loginWithRedirect } = useAuth0();
|
||||
|
||||
useEffect(() => {
|
||||
if (loading || isAuthenticated) {
|
||||
return;
|
||||
}
|
||||
const fn = async () => {
|
||||
await loginWithRedirect({
|
||||
appState: { targetUrl: path }
|
||||
});
|
||||
};
|
||||
fn();
|
||||
}, [loading, isAuthenticated, loginWithRedirect, path]);
|
||||
|
||||
const render = props =>
|
||||
isAuthenticated === true ? <Component {...props} /> : null;
|
||||
|
||||
return <Route path={path} render={render} {...rest} />;
|
||||
};
|
||||
|
||||
export default PrivateRoute;
|
||||
32
frontend/src/index.js
Normal file
32
frontend/src/index.js
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
import React from "react";
|
||||
import ReactDOM from "react-dom";
|
||||
import App from "./App";
|
||||
import * as serviceWorker from "./serviceWorker";
|
||||
import { Auth0Provider } from "./react-auth0-spa";
|
||||
import config from "./auth_config.json";
|
||||
import history from "./utils/history";
|
||||
|
||||
// A function that routes the user to the right place
|
||||
// after login
|
||||
const onRedirectCallback = appState => {
|
||||
history.push(
|
||||
appState && appState.targetUrl
|
||||
? appState.targetUrl
|
||||
: window.location.pathname
|
||||
);
|
||||
};
|
||||
|
||||
ReactDOM.render(
|
||||
<Auth0Provider
|
||||
domain={config.domain}
|
||||
client_id={config.clientId}
|
||||
redirect_uri={window.location.origin}
|
||||
audience={config.audience}
|
||||
onRedirectCallback={onRedirectCallback}
|
||||
>
|
||||
<App />
|
||||
</Auth0Provider>,
|
||||
document.getElementById("root")
|
||||
);
|
||||
|
||||
serviceWorker.unregister();
|
||||
89
frontend/src/react-auth0-spa.js
vendored
Normal file
89
frontend/src/react-auth0-spa.js
vendored
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
import React, { useState, useEffect, useContext } from "react";
|
||||
import createAuth0Client from "@auth0/auth0-spa-js";
|
||||
|
||||
const DEFAULT_REDIRECT_CALLBACK = () =>
|
||||
window.history.replaceState({}, document.title, window.location.pathname);
|
||||
|
||||
export const Auth0Context = React.createContext();
|
||||
export const useAuth0 = () => useContext(Auth0Context);
|
||||
export const Auth0Provider = ({
|
||||
children,
|
||||
onRedirectCallback = DEFAULT_REDIRECT_CALLBACK,
|
||||
...initOptions
|
||||
}) => {
|
||||
const [isAuthenticated, setIsAuthenticated] = useState();
|
||||
const [user, setUser] = useState();
|
||||
const [auth0Client, setAuth0] = useState();
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [popupOpen, setPopupOpen] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const initAuth0 = async () => {
|
||||
const auth0FromHook = await createAuth0Client(initOptions);
|
||||
setAuth0(auth0FromHook);
|
||||
|
||||
if (
|
||||
window.location.search.includes("code=") &&
|
||||
window.location.search.includes("state=")
|
||||
) {
|
||||
const { appState } = await auth0FromHook.handleRedirectCallback();
|
||||
onRedirectCallback(appState);
|
||||
}
|
||||
|
||||
const isAuthenticated = await auth0FromHook.isAuthenticated();
|
||||
|
||||
setIsAuthenticated(isAuthenticated);
|
||||
|
||||
if (isAuthenticated) {
|
||||
const user = await auth0FromHook.getUser();
|
||||
setUser(user);
|
||||
}
|
||||
|
||||
setLoading(false);
|
||||
};
|
||||
initAuth0();
|
||||
// eslint-disable-next-line
|
||||
}, []);
|
||||
|
||||
const loginWithPopup = async (params = {}) => {
|
||||
setPopupOpen(true);
|
||||
try {
|
||||
await auth0Client.loginWithPopup(params);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
} finally {
|
||||
setPopupOpen(false);
|
||||
}
|
||||
const user = await auth0Client.getUser();
|
||||
setUser(user);
|
||||
setIsAuthenticated(true);
|
||||
};
|
||||
|
||||
const handleRedirectCallback = async () => {
|
||||
setLoading(true);
|
||||
await auth0Client.handleRedirectCallback();
|
||||
const user = await auth0Client.getUser();
|
||||
setLoading(false);
|
||||
setIsAuthenticated(true);
|
||||
setUser(user);
|
||||
};
|
||||
return (
|
||||
<Auth0Context.Provider
|
||||
value={{
|
||||
isAuthenticated,
|
||||
user,
|
||||
loading,
|
||||
popupOpen,
|
||||
loginWithPopup,
|
||||
handleRedirectCallback,
|
||||
getIdTokenClaims: (...p) => auth0Client.getIdTokenClaims(...p),
|
||||
loginWithRedirect: (...p) => auth0Client.loginWithRedirect(...p),
|
||||
getTokenSilently: (...p) => auth0Client.getTokenSilently(...p),
|
||||
getTokenWithPopup: (...p) => auth0Client.getTokenWithPopup(...p),
|
||||
logout: (...p) => auth0Client.logout(...p)
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</Auth0Context.Provider>
|
||||
);
|
||||
};
|
||||
137
frontend/src/serviceWorker.js
Normal file
137
frontend/src/serviceWorker.js
Normal file
|
|
@ -0,0 +1,137 @@
|
|||
// This optional code is used to register a service worker.
|
||||
// register() is not called by default.
|
||||
|
||||
// This lets the app load faster on subsequent visits in production, and gives
|
||||
// it offline capabilities. However, it also means that developers (and users)
|
||||
// will only see deployed updates on subsequent visits to a page, after all the
|
||||
// existing tabs open on the page have been closed, since previously cached
|
||||
// resources are updated in the background.
|
||||
|
||||
// To learn more about the benefits of this model and instructions on how to
|
||||
// opt-in, read https://bit.ly/CRA-PWA
|
||||
|
||||
const isLocalhost = Boolean(
|
||||
window.location.hostname === 'localhost' ||
|
||||
// [::1] is the IPv6 localhost address.
|
||||
window.location.hostname === '[::1]' ||
|
||||
// 127.0.0.0/8 are considered localhost for IPv4.
|
||||
window.location.hostname.match(
|
||||
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
|
||||
)
|
||||
);
|
||||
|
||||
export function register(config) {
|
||||
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
|
||||
// The URL constructor is available in all browsers that support SW.
|
||||
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
|
||||
if (publicUrl.origin !== window.location.origin) {
|
||||
// Our service worker won't work if PUBLIC_URL is on a different origin
|
||||
// from what our page is served on. This might happen if a CDN is used to
|
||||
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
|
||||
return;
|
||||
}
|
||||
|
||||
window.addEventListener('load', () => {
|
||||
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
|
||||
|
||||
if (isLocalhost) {
|
||||
// This is running on localhost. Let's check if a service worker still exists or not.
|
||||
checkValidServiceWorker(swUrl, config);
|
||||
|
||||
// Add some additional logging to localhost, pointing developers to the
|
||||
// service worker/PWA documentation.
|
||||
navigator.serviceWorker.ready.then(() => {
|
||||
console.log(
|
||||
'This web app is being served cache-first by a service ' +
|
||||
'worker. To learn more, visit https://bit.ly/CRA-PWA'
|
||||
);
|
||||
});
|
||||
} else {
|
||||
// Is not localhost. Just register service worker
|
||||
registerValidSW(swUrl, config);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function registerValidSW(swUrl, config) {
|
||||
navigator.serviceWorker
|
||||
.register(swUrl)
|
||||
.then(registration => {
|
||||
registration.onupdatefound = () => {
|
||||
const installingWorker = registration.installing;
|
||||
if (installingWorker == null) {
|
||||
return;
|
||||
}
|
||||
installingWorker.onstatechange = () => {
|
||||
if (installingWorker.state === 'installed') {
|
||||
if (navigator.serviceWorker.controller) {
|
||||
// At this point, the updated precached content has been fetched,
|
||||
// but the previous service worker will still serve the older
|
||||
// content until all client tabs are closed.
|
||||
console.log(
|
||||
'New content is available and will be used when all ' +
|
||||
'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
|
||||
);
|
||||
|
||||
// Execute callback
|
||||
if (config && config.onUpdate) {
|
||||
config.onUpdate(registration);
|
||||
}
|
||||
} else {
|
||||
// At this point, everything has been precached.
|
||||
// It's the perfect time to display a
|
||||
// "Content is cached for offline use." message.
|
||||
console.log('Content is cached for offline use.');
|
||||
|
||||
// Execute callback
|
||||
if (config && config.onSuccess) {
|
||||
config.onSuccess(registration);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
};
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error during service worker registration:', error);
|
||||
});
|
||||
}
|
||||
|
||||
function checkValidServiceWorker(swUrl, config) {
|
||||
// Check if the service worker can be found. If it can't reload the page.
|
||||
fetch(swUrl, {
|
||||
headers: { 'Service-Worker': 'script' }
|
||||
})
|
||||
.then(response => {
|
||||
// Ensure service worker exists, and that we really are getting a JS file.
|
||||
const contentType = response.headers.get('content-type');
|
||||
if (
|
||||
response.status === 404 ||
|
||||
(contentType != null && contentType.indexOf('javascript') === -1)
|
||||
) {
|
||||
// No service worker found. Probably a different app. Reload the page.
|
||||
navigator.serviceWorker.ready.then(registration => {
|
||||
registration.unregister().then(() => {
|
||||
window.location.reload();
|
||||
});
|
||||
});
|
||||
} else {
|
||||
// Service worker found. Proceed as normal.
|
||||
registerValidSW(swUrl, config);
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
console.log(
|
||||
'No internet connection found. App is running in offline mode.'
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export function unregister() {
|
||||
if ('serviceWorker' in navigator) {
|
||||
navigator.serviceWorker.ready.then(registration => {
|
||||
registration.unregister();
|
||||
});
|
||||
}
|
||||
}
|
||||
5
frontend/src/setupTests.js
Normal file
5
frontend/src/setupTests.js
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
// jest-dom adds custom jest matchers for asserting on DOM nodes.
|
||||
// allows you to do things like:
|
||||
// expect(element).toHaveTextContent(/react/i)
|
||||
// learn more: https://github.com/testing-library/jest-dom
|
||||
import '@testing-library/jest-dom/extend-expect';
|
||||
2
frontend/src/utils/history.js
Normal file
2
frontend/src/utils/history.js
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
import { createBrowserHistory } from "history";
|
||||
export default createBrowserHistory();
|
||||
37
frontend/src/views/ExternalApi.js
Normal file
37
frontend/src/views/ExternalApi.js
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
import React, { useState } from "react";
|
||||
import { useAuth0 } from "../react-auth0-spa";
|
||||
|
||||
const ExternalApi = () => {
|
||||
const [showResult, setShowResult] = useState(false);
|
||||
const [apiMessage, setApiMessage] = useState("");
|
||||
const { getTokenSilently } = useAuth0();
|
||||
|
||||
const callApi = async () => {
|
||||
try {
|
||||
const token = await getTokenSilently();
|
||||
|
||||
const response = await fetch("/api/v1/connections", {
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`
|
||||
}
|
||||
});
|
||||
|
||||
const responseData = await response.json();
|
||||
|
||||
setShowResult(true);
|
||||
setApiMessage(responseData);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<h1>External API</h1>
|
||||
<button onClick={callApi}>Ping API</button>
|
||||
{showResult && <code>{JSON.stringify(apiMessage, null, 2)}</code>}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default ExternalApi;
|
||||
22
frontend/src/views/Profile.js
Normal file
22
frontend/src/views/Profile.js
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
import React, { Fragment } from "react";
|
||||
import { useAuth0 } from "../react-auth0-spa";
|
||||
|
||||
const Profile = () => {
|
||||
const { loading, user } = useAuth0();
|
||||
|
||||
if (loading || !user) {
|
||||
return <div>Loading...</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<Fragment>
|
||||
<img src={user.picture} alt="Profile" />
|
||||
|
||||
<h2>{user.name}</h2>
|
||||
<p>{user.email}</p>
|
||||
<code>{JSON.stringify(user, null, 2)}</code>
|
||||
</Fragment>
|
||||
);
|
||||
};
|
||||
|
||||
export default Profile;
|
||||
Loading…
Add table
Add a link
Reference in a new issue