Merge pull request 'Get updated framework' (#1) from Navy.gif/webserver-framework-frontend:master into master

Reviewed-on: #1
This commit is contained in:
D3vision 2022-11-23 14:14:01 +01:00
commit 61b5b7d927
20 changed files with 9621 additions and 28773 deletions

View File

@ -113,7 +113,7 @@
"jsx-quotes": "off",
"key-spacing": "off",
"keyword-spacing": "off",
"line-comment-position": "error",
"line-comment-position": "off",
"linebreak-style": "off",
"lines-around-comment": "error",
"lines-between-class-members": "error",
@ -165,7 +165,7 @@
"no-implicit-coercion": "error",
"no-implicit-globals": "error",
"no-implied-eval": "error",
"no-inline-comments": "error",
"no-inline-comments": "off",
"no-invalid-this": "error",
"no-iterator": "error",
"no-label-var": "error",
@ -226,7 +226,7 @@
"no-useless-return": "error",
"no-var": "error",
"no-void": "error",
"no-warning-comments": "error",
"no-warning-comments": "warn",
"no-whitespace-before-property": "error",
"nonblock-statement-body-position": "error",
"object-curly-newline": "error",

28711
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -7,7 +7,7 @@
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
content="Navy's framework frontend"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
@ -24,9 +24,9 @@
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>
<title>Framework dashboard</title>
</head>
<body>
<body class="is-full-screen">
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--

View File

@ -1,5 +1,5 @@
import React, { useEffect } from 'react';
import { BrowserRouter, Route, Routes} from 'react-router-dom';
import { BrowserRouter, Navigate, Route, Routes} from 'react-router-dom';
import './css/App.css';
import Home from './pages/Home';
@ -9,6 +9,10 @@ import UserControls from './components/UserControls';
import { useLoginContext } from './structures/UserContext';
import Login from './pages/Login';
import { fetchUser } from './util/Util';
import PrivateRoute from './structures/PrivateRoute';
import { UnauthedRoute } from './structures/UnauthedRoute';
import Users from './pages/Users';
import Admin from './pages/Admin';
function App() {
@ -19,35 +23,37 @@ function App() {
}, []);
const menuItems = [
{ to: '/', label: 'Home' },
{ to: '/home', label: 'Home' },
{ to: '/users', label: 'Users' },
{ to: '/admin', label: 'Admin' }
];
return (
<div className='app'>
<div className='app is-full-screen'>
<header>
<UserControls />
</header>
{user ?
<div className='background'>
<div className='background'>
<BrowserRouter>
{user ?
<Sidebar>
SIDEBAR
<SidebarMenu menuItems={menuItems}>
</SidebarMenu>
<SidebarMenu menuItems={menuItems} />
</Sidebar>
: null}
<div className='main-content'>
<ErrorBoundary>
<Routes>
<Route exact path='/' element={<Home />} />
<Route path='/home/*' element={<PrivateRoute><Home /></PrivateRoute >} />
<Route path='/users/*' element={<PrivateRoute><Users /></PrivateRoute >} />
<Route path='/admin/*' element={<PrivateRoute><Admin /></PrivateRoute >} />
<Route path='/login/*' element={<UnauthedRoute><Login /></UnauthedRoute>} />
<Route path='*' element={<Navigate to='/home' />} />
</Routes>
</ErrorBoundary>
</div>
@ -56,7 +62,6 @@ function App() {
</BrowserRouter>
</div>
: <Login />}
</div>
);

View File

@ -4,7 +4,7 @@ import NavLink from '../structures/NavLink';
const Sidebar = ({children}) => {
return <div className='sidebar'>
return <div className='sidebar card'>
{children}
</div>;

View File

@ -5,12 +5,13 @@ import { useLoginContext } from "../structures/UserContext";
const UserControls = () => {
const [user] = useLoginContext();
console.log(user);
if (!user) return;
return <div className='user-controls'>
Hello {user.displayName}
<div>
Hello {user.displayName}
</div>
</div>;
};

View File

@ -1,14 +1,14 @@
.app {
width: 100vw;
height: 100vh;
background-color: var(--background-primary);
}
header {
position: absolute;
right: 0;
display: flex;
flex-direction: row;
text-align: center;
height: var(--header-height);
height: 50px;
background-color: var(--background-tertiary);
}
@ -20,7 +20,7 @@
.main-content {
width: 100%;
height: 91%;
margin: 20px;
height: 100%;
padding-right: 30px;
background-color: var(--background-secondary);
}

View File

@ -1,7 +1,7 @@
.sidebar {
min-width: 200px;
height: 100%;
background-color: var(--background-secondary);
margin-right: 10px;
}
.sidebar-menu {

View File

@ -1,3 +1,3 @@
.user-controls {
display: flex;
}

View File

@ -3,7 +3,7 @@
:root {
--bg-color: #232323;
--bg-secondary-color: #343434;
--color-primary: #00377e;
--color-primary: #2760aa;
--color-lightGrey: #d2d6dd;
--color-grey: #ccc;
--color-darkGrey: #777;
@ -16,6 +16,38 @@
--font-family-sans: sans-serif;
--font-family-mono: monaco, "Consolas", "Lucida Console", monospace;
}
.flex {
display: flex;
gap: 10px;
}
html {
height: 100%;
}
ul {
list-style-type: none;
/* padding: 0; */
}
tbody tr:hover {
background-color: rgba(0, 0, 0, 0.199) !important;
}
/* * {
outline: red dashed 1px;
} */
#root {
height: 100%;
}
.is-full-screen {
height: 100%;
min-height: unset;
}
.card {
background: var(--bg-secondary-color);
box-shadow: 0 1px 3px #00000085;

View File

@ -7,7 +7,7 @@ input{
.logoImg{
max-height: 120px;
}
.row>div{
.dingus{
max-width: 407px;
}
.methodsWrapper{

11
src/css/pages/Users.css Normal file
View File

@ -0,0 +1,11 @@
.user-page {
height: 100%;
}
.user-list {
height: 95%;
}
li input {
margin: 0;
}

View File

@ -15,4 +15,4 @@ root.render(<React.StrictMode>
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals(console.log);
// reportWebVitals(console.log);

11
src/pages/Admin.js Normal file
View File

@ -0,0 +1,11 @@
import React from "react";
const Admin = () => {
return <div>
ADMIN
</div>;
};
export default Admin;

View File

@ -1,7 +1,9 @@
import React from "react";
import React, { useState } from "react";
import { Route, Routes, useNavigate } from "react-router";
import '../css/pages/Login.css';
import logoImg from '../img/logo.png';
import { post } from "../util/Util";
import { useLoginContext } from "../structures/UserContext";
import { fetchUser, post } from "../util/Util";
const loginMethods = [
{
@ -10,35 +12,51 @@ const loginMethods = [
}
];
const Login = () => {
document.body.classList.add('bg-triangles');
const CredentialFields = () => {
const [, setUser] = useLoginContext();
const [fail, setFail] = useState(false);
const navigate = useNavigate();
const loginClick = async () => {
const username = document.getElementById('username').value;
const password = document.getElementById('password').value;
if (!username.length || !password.length) return;
await post('/api/login', {username, password});
const result = await post('/api/login', { username, password });
console.log(result);
if (![200, 302].includes(result.status)) {
setFail(true);
return;
}
if (!result.data.twoFactor) {
setUser(await fetchUser());
return navigate('/home');
}
return navigate('/login/verify');
};
return <div className="row is-center is-full-screen is-marginless">
<div className='col-6 col-6-md col-3-lg'>
<div className="is-center">
<img className="logoImg mb-4" src={logoImg}></img>
</div>
<div className="card mb-3 is-center dir-column">
<h2>Log in</h2>
return <div>
<div className="is-center">
<img className="logoImg mb-4" src={logoImg}></img>
</div>
<div className="card mb-3 is-center dir-column">
{fail ? <p>Invalid credentials</p> : null}
<h2>Log in</h2>
<input autoComplete='off' placeholder='Username' required id='username' type='text' autoFocus />
<input autoComplete='off' placeholder='Password' required id='password' type='password' />
<button onClick={loginClick}>Enter</button>
</div>
<input autoComplete='off' placeholder='Username' required id='username' type='text' autoFocus />
<input autoComplete='off' placeholder='Password' required id='password' type='password' />
<button onClick={loginClick}>Enter</button>
</div>
<div className="card is-center dir-column">
<b>Alternate login methods</b>
<div className="methodsWrapper is-center flex-wrap">
<div className="card is-center dir-column">
<b>Alternate login methods</b>
<div className="methodsWrapper is-center flex-wrap">
{loginMethods.map(method => <img
crossOrigin="anonymous"
className='third-party-login'
key={method.name}
alt={method.name}
@ -46,10 +64,48 @@ const Login = () => {
width={48} height={48}
onClick={() => { window.location.pathname = `/api/login/${method.name}`; }}
/>)}
</div>
</div>
</div>
</div>;
};
const TwoFactor = () => {
const [fail, setFail] = useState(false);
const [, setUser] = useLoginContext();
const navigate = useNavigate();
const twoFactorClick = async () => {
const code = document.getElementById('2faCode').value;
if (!code) return;
const result = await post('/api/login/verify', { code });
console.log(result);
if (result.status === 200) {
setUser(await fetchUser());
return navigate('/home', { replace: true });
}
setFail(true);
};
return <div className="card mb-3 is-center dir-column">
{fail ? <p>Invalid code</p> : null}
<h2>Verification code</h2>
<input autoComplete='off' placeholder='Code' required id='2faCode' type='password' />
<button onClick={twoFactorClick}>Enter</button>
</div>;
};
const Login = () => {
document.body.classList.add('bg-triangles');
return <div className="row is-center is-full-screen is-marginless">
<div className='dingus col-6 col-6-md col-3-lg'>
<Routes>
<Route path='/' element={<CredentialFields />} />
<Route path='/verify' element={<TwoFactor />} />
</Routes>
</div>
</div>;

211
src/pages/Users.js Normal file
View File

@ -0,0 +1,211 @@
import React, { useEffect, useState } from "react";
import { Route, Routes, useNavigate, useParams } from "react-router";
import ErrorBoundary from "../util/ErrorBoundary";
import { get } from '../util/Util';
import '../css/pages/Users.css';
const Permission = ({name, value}) => {
return <li className="flex is-vertical-align">
<label>{name}</label>
<input max={10} min={0} type='number' style={{maxWidth: '60px'}} defaultValue={value}></input>
</li>;
};
const PermissionGroup = ({ name, value }) => {
const elements = [];
for (const [perm, val] of Object.entries(value)) {
const props = { key: perm, name: perm, value: val };
if(typeof val ==='object') elements.push(<PermissionGroup {...props} />);
else elements.push(<Permission {...props} />);
}
return <li>
<b>Group: {name}</b>
<ul>
{elements}
</ul>
</li>;
};
const Permissions = ({ perms }) => {
const elements = [];
const keys = Object.keys(perms);
for (const perm of keys) {
const props = { key: perm, name: perm, value: perms[perm] };
let Elem = null;
switch (typeof perms[perm]) {
case 'number':
Elem = Permission;
break;
case 'object':
Elem = PermissionGroup;
break;
default:
// eslint-disable-next-line react/display-name
Elem = () => {
return <p>Uknown permission structure</p>;
};
break;
}
elements.push(<Elem {...props} />);
}
return <div>
<h4>Permissions </h4>
<ul>
{elements}
</ul>
</div>;
};
// TODO: Make generic table list component and use it here and the user list
const ApplicationList = ({ apps }) => {
};
const Application = ({ app }) => {
};
const User = ({ user }) => {
const navigate = useNavigate();
const [apps, updateApps] = useState([]);
useEffect(() => {
(async () => {
const response = await get(`/api/users/${user._id}/applications`);
if(response.status === 200) updateApps(response.data);
})();
}, [user]);
return <div className='user-card'>
<div className="row">
<div className="col-6">
<div className="flex">
<button className="button primary" onClick={() => {
navigate(-1);
}}>Back</button>
<h3>User {user._id}</h3>
</div>
<label htmlFor='username'>Username:</label>
<input id='username' defaultValue={user.username} />
<label htmlFor='displayName'>Display Name:</label>
<input id='displayName' placeholder='Name to display instead of username' defaultValue={user.displayName} />
<select>
<option>User</option>
<option>Bob</option>
</select>
<h4>Applications</h4>
<Routes>
<Route path='/' element={<ApplicationList apps={apps} />} />
</Routes>
{apps.map(app => <Application key={app._id} app={app} />)}
</div>
<div className="col-6">
<Permissions perms={user.permissions} />
</div>
</div>
<button className="button primary">
Save
</button>
</div>;
};
const UserListEntry = ({ user }) => {
const navigate = useNavigate();
const onClick = () => {
navigate(`/users/${user._id}`);
};
return <tr onClick={onClick} style={{cursor: 'pointer'}}>
<td>{user.username}</td>
<td>{user._id}</td>
</tr>;
};
// TODO: Make table list generic component
const UserList = ({ users }) => {
return <table className="striped" style={{maxWidth: '30em', marginBottom: '10px'}}>
<thead>
<tr>
<th>Username</th>
<th>ID</th>
</tr>
</thead>
<tbody>
{users.map(user => <UserListEntry key={user._id} user={user} />)}
</tbody>
</table>;
};
const Users = () => {
const [users, setUsers] = useState([]);
const [page, setPage] = useState(1);
const [error, setError] = useState(null);
useEffect(() => {
(async () => {
const result = await get('/api/users', { page });
if (result.success) {
setError(null);
setUsers(result.data);
} else setError(result.message);
})();
}, [page]);
const UserWrapper = () => {
const { id } = useParams();
const user = users.find(u => u._id === id);
if (!user) return null;
return <User user={user} />;
};
const UserListWrapper = () => {
return <div className="user-list-wrapper">
<UserList users={users} />
<div className='flex is-vertical-align page-controls'>
<button className="col-1 button dark" onClick={() => setPage(page - 1 || 1)}>Previous</button>
<p>Page: {page}</p>
<button className="col-1 button dark" onClick={() => {
if (users.length === 10) setPage(page + 1);
}}>Next</button>
</div>
</div>;
};
return <div className="user-page">
<p>USERS</p>
{error && <p>{error}</p>}
<div className='user-list card'>
<ErrorBoundary>
<Routes>
<Route path='/:id/*' element={<UserWrapper />} />
<Route path='/' element={<UserListWrapper />} />
</Routes>
</ErrorBoundary>
</div>
</div>;
};
export default Users;

View File

@ -0,0 +1,9 @@
import React from 'react';
import { Navigate } from "react-router-dom";
import { getUser } from "../util/Util";
export const UnauthedRoute = ({ children }) => {
const user = getUser();
if (user) return <Navigate to='/home' replace />;
return children;
};

View File

@ -8,12 +8,12 @@ class ErrorBoundary extends React.Component {
}
componentDidCatch(error, errorInfo) {
this.sate.error = true;
console.log(error, errorInfo);
this.setState({error: true});
console.error(error, errorInfo);
}
render() {
if (this.state.error) return <h1>Something went wrong :(</h1>;
if (this.state.error) return <h1>Something went wrong :/</h1>;
return this.props.children;
}

View File

@ -16,23 +16,55 @@ export const setSession = (user) => {
sessionStorage.setItem('user', JSON.stringify(user));
};
export const fetchUser = async () => {
const result = await fetch('/api/user');
export const fetchUser = async (force = false) => {
const user = getUser();
if (!force && user) return user;
const result = await get('/api/user');
if (result.status === 200) {
const data = await result.json();
setSession(data);
return data;
setSession(result.data);
return result.data;
}
return null;
};
export const post = (url, body) => {
return fetch(url, {
const parseResponse = async (response) => {
const { headers: rawHeaders, status } = response;
// Fetch returns heders as an interable for some reason
const headers = [...rawHeaders].reduce((acc, [key, val]) => {
acc[key.toLowerCase()] = val;
return acc;
}, {});
const success = status >= 200 && status < 300;
const base = { success, status };
if (headers['content-type']?.includes('application/json')) {
const data = await response.json();
if (status === 401) {
// const currentPath = window.location.pathname;
// if (data.twoFactor && !currentPath.includes('/login/verify')) window.location.pathname = '/login/verify';
// else if(!data.twoFactor && !currentPath.includes('/login')) window.location.pathname = '/login';
}
return {...base, data};
}
return { ...base, message: await response.text() };
};
export const post = async (url, body) => {
const response = await fetch(url, {
method: 'post',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(body)
});
console.log(response);
return parseResponse(response);
};
export const get = async (url, params) => {
if (params) url += '?' + Object.entries(params)
.map(([key, val]) => `${key}=${val}`)
.join('&');
const response = await fetch(url);
return parseResponse(response);
};

9191
yarn.lock Normal file

File diff suppressed because it is too large Load Diff