Skip to content

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
jonashendrickx committed Aug 8, 2023
1 parent a481c72 commit 181dd3d
Showing 31 changed files with 822 additions and 43 deletions.
41 changes: 20 additions & 21 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,24 +1,23 @@
# General
.DS_Store
Thumbs.db
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js

# IDEs and editors
.idea/
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# testing
/coverage

# Visual Studio Code
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
.history/*
# production
/build

# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local

# Node
node_modules
npm-debug.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
165 changes: 163 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,164 @@
# Template Repository
# Backend
## Signup
Request
```json
POST /signup

This repository serves as a template for others and establishes very basic structure and tooling setup for later customization.
{
"username": "string",
"firstName": "string",
"lastName": "string",
"deviceName": "string"
}
```

```json
{"username":"bitwardenjonas","firstName":"Jonas","lastName":"Hendrickx","deviceName":"macven"}
```

Response
```json
{"token":"string"}
```

```json
{
"token": "register_k8QgsL93tVqRKJfb8b2SiZLBzEb4NPLpLzYHt7I-cFbf8A3Ei9wAE9f_SqW9wGTSS5bZJDAwMDAwMDAwLTAwMDAtMDAwMC0wMDAwLTAwMDAwMDAwMDAwMMDAwMDAwMDA2SQ1OTY5NmU1NS01ZWEzLTQ5NzgtOTExZS03NDAyZTAyYThhN2XArmJpdHdhcmRlbmpvbmFzpE5vbmXAw6lQcmVmZXJyZWSRpm1hY3ZlbsPOeHVcDw"
}
```

## Sign in
Request
```
GET /signin?token=verify_xxx
```

```
GET /signin?token=verify_k8QgFoqG-yjEr0Kz4LDOjutPnAY7_yXKHWYFSuIJlWfr08zE6NwAE9f_QTTfAGTSTR3ZJDNlZmFjOWRhLTNiZTktNDJjNi05YWJkLTcyMzIxZTFmZDkwMK5wYXNza2V5X3NpZ25pbsDAwMDAwMDZJDU5Njk2ZTU1LTVlYTMtNDk3OC05MTFlLTc0MDJlMDJhOGE3Zdf_QTSwIGTSTKWpbG9jYWxob3N0tWh0dHA6Ly9sb2NhbGhvc3Q6MzAwMMOzQ2hyb21lLCBNYWMgT1MgWCAxMKCmbWFjdmVuxDAGJ_src8cEWarNaMyWCFaTQ2I3bfUVmnf1J-_atUKpDk647a0S6I0OGZyPAdB9Cr3OeHVcDw
```

Response
```json
{
"jwt": "string",
"webAuthn": {
"userId": "string",
"credentialId": "string",
"success": true,
"timestamp": "2023-08-08T14:09:41.273493Z",
"rpId": "string",
"origin": "http://localhost:3000",
"device": "string",
"country": "",
"nickname": "string",
"expiresAt": "2023-08-08T14:11:41.273496Z",
"type": "string"
}
}
```

```json
{
"jwt": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjpbIlVzZXIiLCJBZG1pbiJdLCJuYW1laWQiOiI1OTY5NmU1NS01ZWEzLTQ5NzgtOTExZS03NDAyZTAyYThhN2UiLCJuYmYiOjE2OTE1MDUzNDMsImV4cCI6MTY5MjExMDE0MywiaWF0IjoxNjkxNTA1MzQzLCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjUwMTMiLCJhdWQiOiJodHRwOi8vbG9jYWxob3N0OjMwMDAifQ.yFByxlI7H9EMedfkNPYk0oheXl7j12fJiH1f8EqoiBY",
"webAuthn": {
"userId": "59696e55-5ea3-4978-911e-7402e02a8a7e",
"credentialId": "Bif7K3PHBFmqzWjMlghWk0NiN231FZp39Sfv2rVCqQ5OuO2tEuiNDhmcjwHQfQq9",
"success": true,
"timestamp": "2023-08-08T14:35:43.703799Z",
"rpId": "localhost",
"origin": "http://localhost:3000",
"device": "Chrome, Mac OS X 10",
"country": "",
"nickname": "macven",
"expiresAt": "2023-08-08T14:37:43.703799Z",
"type": "passkey_signin"
}
}
```

The JWT token, when decoded, will look like:
```json
{
"role": [
"User",
"Admin"
],
"nameid": "59696e55-5ea3-4978-911e-7402e02a8a7e",
"nbf": 1691505343,
"exp": 1692110143,
"iat": 1691505343,
"iss": "http://localhost:5013",
"aud": "http://localhost:3000"
}
```

# Getting Started with Create React App

This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).

## Available Scripts

In the project directory, you can run:

### `npm start`

Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in your browser.

The page will reload when you make changes.\
You may also see any lint errors in the console.

### `npm test`

Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.

### `npm run build`

Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.

The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!

See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.

### `npm run eject`

**Note: this is a one-way operation. Once you `eject`, you can't go back!**

If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.

Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own.

You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it.

## Learn More

You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).

To learn React, check out the [React documentation](https://reactjs.org/).

### Code Splitting

This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting)

### Analyzing the Bundle Size

This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size)

### Making a Progressive Web App

This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app)

### Advanced Configuration

This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration)

### Deployment

This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment)

### `npm run build` fails to minify

This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)
60 changes: 40 additions & 20 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,26 +1,46 @@
{
"name": "@bitwarden/template",
"version": "0.0.0",
"description": "Bitwarden Template",
"repository": {
"type": "git",
"url": "git+https://github.com/bitwarden/template.git"
"name": "passwordless-react",
"version": "0.1.0",
"private": true,
"dependencies": {
"@passwordlessdev/passwordless-client": "^1.1.0",
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"@types/jest": "^27.5.2",
"@types/node": "^16.18.38",
"@types/react": "^18.2.15",
"@types/react-dom": "^18.2.7",
"jwt-decode": "^3.1.2",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.14.1",
"react-scripts": "5.0.1",
"react-toastify": "^9.1.3",
"web-vitals": "^2.1.4"
},
"author": "Bitwarden Inc. <hello@bitwarden.com> (https://bitwarden.com)",
"license": "SEE LICENSE IN LICENSE.txt",
"bugs": {
"url": "https://github.com/bitwarden/template/issues"
},
"homepage": "https://bitwarden.com",
"devDependencies": {
"husky": "8.0.3",
"lint-staged": "13.2.3",
"prettier": "3.0.1"
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"lint-staged": {
"*": "prettier --cache --write --ignore-unknown"
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"scripts": {
"prepare": "husky install"
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
Binary file added public/favicon.ico
Binary file not shown.
43 changes: 43 additions & 0 deletions public/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
Binary file added public/logo192.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added public/logo512.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
25 changes: 25 additions & 0 deletions public/manifest.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}
3 changes: 3 additions & 0 deletions public/robots.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:
38 changes: 38 additions & 0 deletions src/App.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
.App {
text-align: center;
}

.App-logo {
height: 40vmin;
pointer-events: none;
}

@media (prefers-reduced-motion: no-preference) {
.App-logo {
animation: App-logo-spin infinite 20s linear;
}
}

.App-header {
background-color: #282c34;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
}

.App-link {
color: #61dafb;
}

@keyframes App-logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
42 changes: 42 additions & 0 deletions src/App.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import React, {Component} from 'react';
import {Route, Routes} from "react-router-dom";
import UserPage from "./pages/UserPage";
import AdminPage from "./pages/AdminPage";
import PublicPage from "./pages/PublicPage";
import Layout from "./components/Layout";
import LoginPage from "./pages/LoginPage";
import RegisterPage from "./pages/RegisterPage";
import RequireAuth from "./components/RequireAuth";
import {ROLE_ADMIN, ROLE_USER} from "./constants/Roles";
import UnauthorizedPage from "./pages/UnauthorizedPage";
import 'react-toastify/dist/ReactToastify.css';


class App extends Component {
constructor(props) {
super(props);
}

render() {
return (
<Layout>
<Routes>
<Route exact path="/" element={ <PublicPage/> } />
<Route path="/register" element={ <RegisterPage/> } />
<Route path="/login" element={ <LoginPage/> } />
<Route path="unauthorized" element={<UnauthorizedPage />} />

<Route element={<RequireAuth allowedRoles={[ROLE_USER]} />}>
<Route path="/user" element={ <UserPage/> } />
</Route>

<Route element={<RequireAuth allowedRoles={[ROLE_ADMIN]} />}>
<Route path="/admin" element={ <AdminPage/> } />
</Route>
</Routes>
</Layout>
);
}
}

export default App;
13 changes: 13 additions & 0 deletions src/components/Layout.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import Menu from './Menu';
import classes from './Layout.module.css';

function Layout(props) {
return (
<div>
<Menu />
<main className={classes.main}>{props.children}</main>
</div>
);
}

export default Layout;
5 changes: 5 additions & 0 deletions src/components/Layout.module.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
.main {
margin: 3rem auto;
width: 90%;
max-width: 40rem;
}
22 changes: 22 additions & 0 deletions src/components/Menu.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { Link } from 'react-router-dom';

import classes from './Menu.module.css';

function Menu() {
return (
<header className={classes.header}>
<div className={classes.logo}></div>
<nav>
<ul>
<li><Link to='/login'>Login</Link></li>
<li><Link to='/register'>Register</Link></li>
<li><Link to='/'>Public</Link></li>
<li><Link to='/user'>User</Link></li>
<li><Link to='/admin'>Admin</Link></li>
</ul>
</nav>
</header>
);
}

export default Menu;
46 changes: 46 additions & 0 deletions src/components/Menu.module.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
.header {
width: 100%;
height: 5rem;
display: flex;
align-items: center;
background-color: #175ddc;
padding: 0 10%;
}

.logo {
font-size: 2rem;
color: white;
font-weight: bold;
}

.header ul {
list-style: none;
margin: 0;
padding: 0;
display: flex;
align-items: baseline;
}

.header li {
margin-left: 3rem;
}

.header a {
text-decoration: none;
font-size: 1.5rem;
color: white;
}

.header a:hover,
.header a:active,
.header a.active {
color: white;
}

.badge {
background-color: #175ddc;
color: white;
border-radius: 12px;
padding: 0 1rem;
margin-left: 0.5rem;
}
44 changes: 44 additions & 0 deletions src/components/RequireAuth.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { useLocation, Navigate, Outlet } from "react-router-dom";
import useAuth from "../hooks/useAuth";
import jwtDecode from "jwt-decode";

function hasMatchingRole(allowedRoles, userRoles) {
if (!allowedRoles || allowedRoles.length === 0) {
return true;
}

for (let i = 0; i < allowedRoles.length; i++) {
if (userRoles.indexOf(allowedRoles[i]) !== -1) {
return true;
}
}

return false;
}


const RequireAuth = ({ allowedRoles }) => {
const { auth } = useAuth();
const location = useLocation();

let isAllowed = true;

if (allowedRoles) {
if (auth?.verifiedToken?.jwt) {
const decodedToken = jwtDecode(auth.verifiedToken.jwt);
isAllowed = hasMatchingRole(allowedRoles, decodedToken.role);
} else {
isAllowed = false;
}
}

return (
isAllowed
? <Outlet />
: auth?.verifiedToken
? <Navigate to="/unauthorized" state={{ from: location }} replace />
: <Navigate to="/login" state={{ from: location }} replace />
);
}

export default RequireAuth;
3 changes: 3 additions & 0 deletions src/configuration/PasswordlessOptions.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export const BACKEND_URL = 'http://localhost:5013';
export const PASSWORDLESS_API_KEY = 'jonashendrickx1:public:ed1efdf1c5f4434696ebbca72de12958';
export const PASSWORDLESS_API_URL = 'http://localhost:7001';
3 changes: 3 additions & 0 deletions src/constants/Roles.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@

export const ROLE_USER = 'User';
export const ROLE_ADMIN = 'Admin'
14 changes: 14 additions & 0 deletions src/context/AuthProvider.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { createContext, useState } from "react";

const AuthContext = createContext({});

export const AuthProvider = ({ children }) => {
const [auth, setAuth] = useState({});
return (
<AuthContext.Provider value={{ auth, setAuth }}>
{children}
</AuthContext.Provider>
);
};

export default AuthContext;
8 changes: 8 additions & 0 deletions src/hooks/useAuth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { useContext } from "react";
import AuthContext from "../context/AuthProvider";

const useAuth = () => {
return useContext(AuthContext);
}

export default useAuth;
13 changes: 13 additions & 0 deletions src/index.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}

code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}
22 changes: 22 additions & 0 deletions src/index.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import './index.css';
import App from './App';
import {AuthProvider} from "./context/AuthProvider";
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(
document.getElementById('root')
);
root.render(
<React.StrictMode>
<AuthProvider>
<BrowserRouter>
<App />
</BrowserRouter>
</AuthProvider>
</React.StrictMode>
);

reportWebVitals();
1 change: 1 addition & 0 deletions src/logo.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
3 changes: 3 additions & 0 deletions src/pages/AdminPage.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default function AdminPage() {
return (<section><p>Congrats, you're an admin.</p></section>)
}
60 changes: 60 additions & 0 deletions src/pages/LoginPage.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import {useContext, useRef, useState} from "react";
import authContext from "../context/AuthProvider";
import * as Passwordless from "@passwordlessdev/passwordless-client";
import YourBackendClient from "../services/YourBackendClient";
import {PASSWORDLESS_API_KEY, PASSWORDLESS_API_URL} from "../configuration/PasswordlessOptions";

export default function LoginPage() {
const errRef = useRef();
const [errMsg, setErrMsg] = useState("");
const [success, setSuccess] = useState(false);
const { setAuth } = useContext(authContext);

const handleSubmit = async (e) => {
e.preventDefault();
const passwordless = new Passwordless.Client({
apiUrl: PASSWORDLESS_API_URL,
apiKey: PASSWORDLESS_API_KEY
});
const yourBackendClient = new YourBackendClient()
const token = await passwordless.signinWithDiscoverable();
if (!token) {
return;
}
const verifiedToken = await yourBackendClient.signIn(token.token);
localStorage.setItem('jwt', verifiedToken.jwt);
setAuth({ verifiedToken });
setSuccess(true);
}

return (
<>
{success ? (
<section>
<h1>You are logged in!</h1>
<br />
<p>{/* <a href="#">Go to Home</a> */}</p>
</section>
) : (
<section>
<p
ref={errRef}
className={errMsg ? "errmsg" : "offscreen"}
aria-live="assertive"
>
{errMsg}
</p>
<h1>Sign In</h1>
<button onClick={handleSubmit}>Sign In</button>
<p>
Need an Account?
<br />
<span className="line">
<a href="#">Sign Up</a>
</span>
</p>
</section>
)}
</>
);
}
3 changes: 3 additions & 0 deletions src/pages/PublicPage.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default function PublicPage() {
return (<section><p>Congrats, you're a guest.</p></section>)
}
116 changes: 116 additions & 0 deletions src/pages/RegisterPage.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
import {useEffect, useRef, useState} from "react";
import * as Passwordless from "@passwordlessdev/passwordless-client";
import {PASSWORDLESS_API_KEY, PASSWORDLESS_API_URL} from "../configuration/PasswordlessOptions";
import { ToastContainer, toast } from 'react-toastify';
import YourBackendClient from "../services/YourBackendClient";

export default function RegisterPage() {
const userRef = useRef();
const firstNameRef = useRef();
const lastNameRef = useRef();
const aliasRef = useRef();
const errRef = useRef();
const [user, setUser] = useState("");
const [firstName, setFirstName] = useState("");
const [lastName, setLastName] = useState("");
const [alias, setAlias] = useState("");
const [errMsg, setErrMsg] = useState("");

useEffect(() => {
userRef.current.focus();
}, []);


useEffect(() => {
setErrMsg("");
}, [user]);

const handleSubmit = async (e) => {
let registerToken = null;
try {
const yourBackendClient = new YourBackendClient();
registerToken = await yourBackendClient.register(user, firstName, lastName, alias);
}
catch (error)
{
toast(error.message, {
className: 'toast-error'
});
}

// If an error previously happened, 'registerToken' will be null, so you don't want to register a token.
if (registerToken) {
const p = new Passwordless.Client({
apiKey: PASSWORDLESS_API_KEY,
apiUrl: PASSWORDLESS_API_URL
});
const finalResponse = await p.register(registerToken.token, alias);

if (finalResponse) {
toast(`Registered '${alias}'!`);
}
}
};

return (
<>
<section>
<p
ref={errRef}
className={errMsg ? "errmsg" : "offscreen"}
aria-live="assertive"
>
{errMsg}
</p>
<h1>Register</h1>
<label htmlFor="username">Username:</label>
<input
type="text"
id="username"
ref={userRef}
autoComplete="off"
onChange={(e) => setUser(e.target.value)}
value={user}
required
aria-describedby="uidnote"
/>
<label htmlFor="firstname">FirstName:</label>
<input
type="text"
id="firstName"
ref={firstNameRef}
autoComplete="off"
onChange={(e) => setFirstName(e.target.value)}
value={firstName}
required
aria-describedby="uidnote"
/>
<label htmlFor="lastname">LastName:</label>
<input
type="text"
id="lastname"
ref={lastNameRef}
autoComplete="off"
onChange={(e) => setLastName(e.target.value)}
value={lastName}
required
aria-describedby="uidnote"
/>
<label htmlFor="alias">Alias:</label>
<input
type="text"
id="alias"
ref={aliasRef}
autoComplete="off"
onChange={(e) => setAlias(e.target.value)}
value={alias}
required
aria-describedby="uidnote"
/>
<button onClick={handleSubmit}>Register</button>
<p>Already registered?</p>
<ToastContainer />
</section>
</>
);
}
18 changes: 18 additions & 0 deletions src/pages/UnauthorizedPage.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { useNavigate } from "react-router-dom"

export default function UnauthorizedPage() {
const navigate = useNavigate();

const goBack = () => navigate(-1);

return (
<section>
<h1>Unauthorized</h1>
<br />
<p>You do not have access to the requested page.</p>
<div className="flexGrow">
<button onClick={goBack}>Go Back</button>
</div>
</section>
)
}
3 changes: 3 additions & 0 deletions src/pages/UserPage.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default function UserPage() {
return (<section><p>Congrats, you're a user.</p></section>)
}
15 changes: 15 additions & 0 deletions src/reportWebVitals.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { ReportHandler } from 'web-vitals';

const reportWebVitals = (onPerfEntry?: ReportHandler) => {
if (onPerfEntry && onPerfEntry instanceof Function) {
import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
getCLS(onPerfEntry);
getFID(onPerfEntry);
getFCP(onPerfEntry);
getLCP(onPerfEntry);
getTTFB(onPerfEntry);
});
}
};

export default reportWebVitals;
36 changes: 36 additions & 0 deletions src/services/YourBackendClient.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import {BACKEND_URL} from "../configuration/PasswordlessOptions";

export default class YourBackendClient {
async register(user, firstName, lastName, deviceName) {
const request = {
username: user,
firstName: firstName,
lastName: lastName,
deviceName: deviceName
};

const response = await fetch(`${BACKEND_URL}/signup`, {
method: 'post',
body: JSON.stringify(request),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
});

if (!response.ok) {
const problemDetails = await response.json();
if (problemDetails && problemDetails.detail) {
throw new Error(problemDetails.detail);
} else {
throw new Error(`An unknown error prevented us from obtaining a registration token.`);
}
}

return await response.json();
}

async signIn(token) {
return await fetch(`${BACKEND_URL}/signin?token=${token}`).then(r => r.json());
}
}

0 comments on commit 181dd3d

Please sign in to comment.