Linter pass

This commit is contained in:
Erik 2023-07-05 13:45:32 +03:00
parent 2da5c82360
commit fd4d72eb21
Signed by: Navy.gif
GPG Key ID: 2532FBBB61C65A68
26 changed files with 1927 additions and 1713 deletions

View File

@ -1,51 +1,52 @@
{
"name": "frontend",
"version": "0.1.0",
"private": true,
"dependencies": {
"@types/node": "^18.15.11",
"@types/react": "^18.0.37",
"@types/react-dom": "^18.0.11",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router": "^6.4.3",
"react-router-dom": "^6.4.3",
"react-scripts": "5.0.1",
"react-top-loading-bar": "^2.3.1",
"typescript": "^5.0.4",
"web-vitals": "^2.1.4"
},
"devDependencies": {
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"@types/jest": "^29.5.1",
"eslint": "^8.27.0",
"eslint-plugin-react": "^7.31.10",
"http-proxy-middleware": "^2.0.6"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
{
"name": "frontend",
"version": "0.1.0",
"private": true,
"dependencies": {
"@types/node": "^18.15.11",
"@types/react": "^18.0.37",
"@types/react-dom": "^18.0.11",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router": "^6.4.3",
"react-router-dom": "^6.4.3",
"react-scripts": "5.0.1",
"react-top-loading-bar": "^2.3.1",
"typescript": "^5.0.4",
"web-vitals": "^2.1.4"
},
"devDependencies": {
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"@types/jest": "^29.5.1",
"eslint": "^8.27.0",
"eslint-plugin-react": "^7.31.10",
"http-proxy-middleware": "^2.0.6"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"lint": "eslint src/ --fix"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}

View File

@ -1,119 +1,125 @@
import React, { useEffect, useState } from 'react';
import { Navigate, Route, Routes, useNavigate} from 'react-router-dom';
import './css/App.css';
import Home from './pages/Home';
import ErrorBoundary from './util/ErrorBoundary';
import Sidebar, { SidebarMenu } from './components/Sidebar';
import UserControls from './components/UserControls';
import { useLoginContext } from './structures/UserContext';
import Login from './pages/Login';
import { get, setSession, setSettings } from './util/Util';
import { PrivateRoute } from './structures/PrivateRoute';
import { UnauthedRoute } from './structures/UnauthedRoute';
import Admin from './pages/Admin';
import TitledPage from './components/TitledPage';
import Register from './pages/Register';
import { ClientSettings } from './@types/Other';
import { User } from './@types/ApiStructures';
function App() {
const [user, updateUser] = useLoginContext();
const [loading, setLoading] = useState(true);
const navigate = useNavigate();
useEffect(() => {
(async () => {
const settings = await get('/api/settings');
setSettings(settings.data as ClientSettings);
const result = await get('/api/user');
if (result.status === 200) {
setSession(result.data as User);
updateUser();
}
setLoading(false);
if (result.data?.twoFactor) return navigate('/login/verify');
})();
}, []);
const menuItems = [
{
to: '/home', label: 'Home', items: [
{ to: '/profile', label: 'Profile', relative: true },
{ to: '/applications', label: 'Applications', relative: true }
]
},
{
to: '/admin', label: 'Admin', items: [
{ to: '/users', label: 'Users', relative: true },
{ to: '/roles', label: 'Roles', relative: true },
{ to: '/flags', label: 'Flags', relative: true }
]
}
];
if (loading) return null;
return (
<div className='app'>
<div className='background'>
{user ?
<div>
<header className="card">
<UserControls />
</header>
<Sidebar>
<SidebarMenu menuItems={menuItems} />
</Sidebar>
</div>
: null}
<div className={`main-content ${user ? "" : "login"}`}>
<ErrorBoundary>
<Routes>
<Route path='/home/*' element={<PrivateRoute>
<TitledPage title='Home'>
<Home />
</TitledPage>
</PrivateRoute >} />
<Route path='/admin/*' element={<PrivateRoute>
<TitledPage title='Admin'>
<Admin />
</TitledPage>
</PrivateRoute >} />
<Route path='/login/*' element={<UnauthedRoute>
<Login />
</UnauthedRoute>} />
<Route path='/register/*' element={<UnauthedRoute>
<Register />
</UnauthedRoute>} />
<Route path='*' element={<Navigate to='/home' />} />
</Routes>
</ErrorBoundary>
<div className={`footer ${user ? "" : "login"}`}>
<p className='m-0'>Made with by <a href="https://corgi.wtf" target="_blank" rel="noreferrer">Navy.gif</a> &nbsp;|&nbsp; Front-end magic by <a href="https://d3vision.dev" target="_blank" rel="noreferrer">D3vision</a></p>
</div>
</div>
</div>
</div>
);
}
export default App;
import React, { useEffect, useState } from 'react';
import { Navigate, Route, Routes, useNavigate} from 'react-router-dom';
import './css/App.css';
import Home from './pages/Home';
import ErrorBoundary from './util/ErrorBoundary';
import Sidebar, { SidebarMenu } from './components/Sidebar';
import UserControls from './components/UserControls';
import { useLoginContext } from './structures/UserContext';
import Login from './pages/Login';
import { get, setSession, setSettings } from './util/Util';
import { PrivateRoute } from './structures/PrivateRoute';
import { UnauthedRoute } from './structures/UnauthedRoute';
import Admin from './pages/Admin';
import TitledPage from './components/TitledPage';
import Register from './pages/Register';
import { ClientSettings } from './@types/Other';
import { User } from './@types/ApiStructures';
function App()
{
const [user, updateUser] = useLoginContext();
const [loading, setLoading] = useState(true);
const navigate = useNavigate();
useEffect(() =>
{
(async () =>
{
const settings = await get('/api/settings');
setSettings(settings.data as ClientSettings);
const result = await get('/api/user');
if (result.status === 200)
{
setSession(result.data as User);
updateUser();
}
setLoading(false);
if (result.data?.twoFactor)
return navigate('/login/verify');
})();
}, []);
const menuItems = [
{
to: '/home', label: 'Home', items: [
{ to: '/profile', label: 'Profile', relative: true },
{ to: '/applications', label: 'Applications', relative: true }
]
},
{
to: '/admin', label: 'Admin', items: [
{ to: '/users', label: 'Users', relative: true },
{ to: '/roles', label: 'Roles', relative: true },
{ to: '/flags', label: 'Flags', relative: true }
]
}
];
if (loading)
return null;
return (
<div className='app'>
<div className='background'>
{user ?
<div>
<header className="card">
<UserControls />
</header>
<Sidebar>
<SidebarMenu menuItems={menuItems} />
</Sidebar>
</div>
: null}
<div className={`main-content ${user ? "" : "login"}`}>
<ErrorBoundary>
<Routes>
<Route path='/home/*' element={<PrivateRoute>
<TitledPage title='Home'>
<Home />
</TitledPage>
</PrivateRoute >} />
<Route path='/admin/*' element={<PrivateRoute>
<TitledPage title='Admin'>
<Admin />
</TitledPage>
</PrivateRoute >} />
<Route path='/login/*' element={<UnauthedRoute>
<Login />
</UnauthedRoute>} />
<Route path='/register/*' element={<UnauthedRoute>
<Register />
</UnauthedRoute>} />
<Route path='*' element={<Navigate to='/home' />} />
</Routes>
</ErrorBoundary>
<div className={`footer ${user ? "" : "login"}`}>
<p className='m-0'>Made with by <a href="https://corgi.wtf" target="_blank" rel="noreferrer">Navy.gif</a> &nbsp;|&nbsp; Front-end magic by <a href="https://d3vision.dev" target="_blank" rel="noreferrer">D3vision</a></p>
</div>
</div>
</div>
</div>
);
}
export default App;

View File

@ -1,217 +1,245 @@
import React, { Children, useRef, useState } from "react";
import ClickDetector from "../util/ClickDetector";
import { DropdownBaseProps, DropdownItemProps } from "../@types/Components";
import '../css/components/InputElements.css';
export const FileSelector = ({ cb }: { cb: (file: File) => void }) => {
if (!cb) throw new Error('Missing callback');
const [file, setFile] = useState<File | null>(null);
const onDragOver: React.MouseEventHandler = (event) => {
event.stopPropagation();
event.preventDefault();
};
const onDrop: React.DragEventHandler = (event) => {
event.preventDefault();
const { dataTransfer } = event;
if (!dataTransfer.files.length) return;
const [file] = dataTransfer.files;
setFile(file);
cb(file);
};
return <label onDrop={onDrop} onDragOver={onDragOver} htmlFor="pfp_upload" className="drop-container">
<span className="drop-title">Drag &apos;n&apos; drop a file here</span>
or
<span className="drop-title">Click to select a file</span>
<p className="fileName m-0">{file ? `Selected: ${file.name}` : null}</p>
<input onChange={(event) => {
if (!event.target.files) return;
const [f] = event.target.files;
setFile(f);
cb(f);
}}
type="file" id="pfp_upload" accept="image/*" required></input>
</label>;
};
export type InputElementProperties<T> = {
value?: T,
inputRef?: React.RefObject<HTMLInputElement>,
onChange?: React.ChangeEventHandler<HTMLInputElement>,
children?: React.ReactNode, //JSX.Element | JSX.Element[] | string,
placeholder?: string
}
export const ToggleSwitch = ({ value, onChange, inputRef, children }: InputElementProperties<boolean>) => {
return <label className="label-fix">
<span className="check-box check-box-row mb-2">
{children && <b>{children}</b>}
<input ref={inputRef} defaultChecked={value} onChange={onChange} type='checkbox' />
</span>
</label>;
};
export const VerticalToggleSwitch = ({ value, onChange, inputRef, children }: InputElementProperties<boolean>) => {
return <label className="label-fix">
{children && <b>{children}</b>}
<span className="check-box">
<input ref={inputRef} defaultChecked={value} onChange={onChange} type='checkbox' />
</span>
</label>;
};
type ManualInputProperties<T> = {
onBlur?: React.FocusEventHandler,
onKeyUp?: React.KeyboardEventHandler
} & InputElementProperties<T>;
type StringInputProperties = {
maxLength?: number,
minLength?: number
} & ManualInputProperties<string>
export const StringInput = ({ value, onChange, inputRef, children, placeholder, onBlur, onKeyUp, minLength, maxLength }: StringInputProperties) => {
const input = <input
onBlur={onBlur}
defaultValue={value}
placeholder={placeholder}
ref={inputRef}
onChange={onChange}
onKeyUp={onKeyUp}
maxLength={maxLength}
minLength={minLength}
/>;
if (children)
return <label>
<b>{children}</b>
{input}
</label>;
return input;
};
export type NumberInputProperties = {
min?: number,
max?: number,
type?: 'float' | 'int',
step?: number
} & ManualInputProperties<number>
export const NumberInput = ({ children, placeholder, inputRef, onChange, value, min, max, type, step }: NumberInputProperties) => {
if (typeof step === 'undefined') {
if (type === 'float') step = 0.1;
else if (type === 'int') step = 1;
else step = 1;
}
const input = <input
placeholder={placeholder}
ref={inputRef}
defaultValue={value}
onChange={onChange}
type="number"
min={min}
max={max}
step={step}
/>;
if (children) return <label>
<b>{children}</b>
{input}
</label>;
return input;
};
export const ClickToEdit = ({ value, onUpdate, inputElement }:
{ value: string, onUpdate?: (value: string) => void, inputElement?: React.ReactElement }) => {
const [editing, setEditing] = useState(false);
const ref = useRef<HTMLInputElement>(null);
const onClick = () => {
setEditing(false);
if (ref.current && onUpdate)
onUpdate(ref.current.value);
};
const input = inputElement ? inputElement : <input defaultValue={value} ref={ref} />;
if (editing) return <span className='input-group'>
{input}
<button className="button primary" onClick={onClick} >
OK
</button>
</span>;
return <span onClick={() => setEditing(true)} className='mt-0 mb-1 clickable'>{value}</span>;
};
const DropdownHeader = ({ children, className = '' }: DropdownBaseProps) => {
return <summary className={`clickable card is-vertical-align header p-2 ${className}`}>
{children}
</summary>;
};
const DropdownItem = ({ children, type, selected, onClick }: DropdownItemProps) => {
let InnerElement = null;
if (type === 'multi-select')
InnerElement = <ToggleSwitch value={selected || false} onChange={onClick}>
{children as string}
</ToggleSwitch>;
else InnerElement = <div onClick={(event) => {
event.preventDefault();
if (onClick) onClick(event);
}}>
{children}
</div>;
return <div className='card item clickable'>
{InnerElement}
</div>;
};
const DropdownItemList = ({ children, className = '' }: DropdownBaseProps) => {
return <div className={`card item-list ${className}`}>
{children}
</div>;
};
type DropdownProps = {
name?: string,
multi?: boolean,
selection?: [],
children: React.ReactNode[],
className?: string
}
const DropdownComp = ({ children, className = '' }: DropdownProps) => {
if (!children)
throw new Error('Missing children');
if (!children.some(element => element && (element as React.ReactElement).type === DropdownHeader))
throw new Error('Missing a header');
const detailsRef = useRef<HTMLDetailsElement>(null);
return <ClickDetector callback={() => {
if (detailsRef.current) detailsRef.current.open = false;
}}>
<details ref={detailsRef} className={`dropdown w-100 ${className}`}>
{children}
</details>
</ClickDetector>;
};
const Dropdown = Object.assign(DropdownComp, {
Header: DropdownHeader,
ItemList: DropdownItemList,
Item: DropdownItem
});
export type InputElementType =
| ((props: InputElementProperties<string>) => React.ReactElement)
| ((props: InputElementProperties<boolean>) => React.ReactElement)
| ((props: NumberInputProperties) => React.ReactElement);
import React, { Children, useRef, useState } from "react";
import ClickDetector from "../util/ClickDetector";
import { DropdownBaseProps, DropdownItemProps } from "../@types/Components";
import '../css/components/InputElements.css';
export const FileSelector = ({ cb }: { cb: (file: File) => void }) =>
{
if (!cb)
throw new Error('Missing callback');
const [file, setFile] = useState<File | null>(null);
const onDragOver: React.MouseEventHandler = (event) =>
{
event.stopPropagation();
event.preventDefault();
};
const onDrop: React.DragEventHandler = (event) =>
{
event.preventDefault();
const { dataTransfer } = event;
if (!dataTransfer.files.length)
return;
const [file] = dataTransfer.files;
setFile(file);
cb(file);
};
return <label onDrop={onDrop} onDragOver={onDragOver} htmlFor="pfp_upload" className="drop-container">
<span className="drop-title">Drag &apos;n&apos; drop a file here</span>
or
<span className="drop-title">Click to select a file</span>
<p className="fileName m-0">{file ? `Selected: ${file.name}` : null}</p>
<input onChange={(event) =>
{
if (!event.target.files)
return;
const [f] = event.target.files;
setFile(f);
cb(f);
}}
type="file" id="pfp_upload" accept="image/*" required></input>
</label>;
};
export type InputElementProperties<T> = {
value?: T,
inputRef?: React.RefObject<HTMLInputElement>,
onChange?: React.ChangeEventHandler<HTMLInputElement>,
children?: React.ReactNode, //JSX.Element | JSX.Element[] | string,
placeholder?: string
}
export const ToggleSwitch = ({ value, onChange, inputRef, children }: InputElementProperties<boolean>) =>
{
return <label className="label-fix">
<span className="check-box check-box-row mb-2">
{children && <b>{children}</b>}
<input ref={inputRef} defaultChecked={value} onChange={onChange} type='checkbox' />
</span>
</label>;
};
export const VerticalToggleSwitch = ({ value, onChange, inputRef, children }: InputElementProperties<boolean>) =>
{
return <label className="label-fix">
{children && <b>{children}</b>}
<span className="check-box">
<input ref={inputRef} defaultChecked={value} onChange={onChange} type='checkbox' />
</span>
</label>;
};
type ManualInputProperties<T> = {
onBlur?: React.FocusEventHandler,
onKeyUp?: React.KeyboardEventHandler
} & InputElementProperties<T>;
type StringInputProperties = {
maxLength?: number,
minLength?: number
} & ManualInputProperties<string>
export const StringInput = ({ value, onChange, inputRef, children, placeholder, onBlur, onKeyUp, minLength, maxLength }: StringInputProperties) =>
{
const input = <input
onBlur={onBlur}
defaultValue={value}
placeholder={placeholder}
ref={inputRef}
onChange={onChange}
onKeyUp={onKeyUp}
maxLength={maxLength}
minLength={minLength}
/>;
if (children)
return <label>
<b>{children}</b>
{input}
</label>;
return input;
};
export type NumberInputProperties = {
min?: number,
max?: number,
type?: 'float' | 'int',
step?: number
} & ManualInputProperties<number>
export const NumberInput = ({ children, placeholder, inputRef, onChange, value, min, max, type, step }: NumberInputProperties) =>
{
if (typeof step === 'undefined')
{
if (type === 'float')
step = 0.1;
else if (type === 'int')
step = 1;
else
step = 1;
}
const input = <input
placeholder={placeholder}
ref={inputRef}
defaultValue={value}
onChange={onChange}
type="number"
min={min}
max={max}
step={step}
/>;
if (children)
return <label>
<b>{children}</b>
{input}
</label>;
return input;
};
export const ClickToEdit = ({ value, onUpdate, inputElement }:
{ value: string, onUpdate?: (value: string) => void, inputElement?: React.ReactElement }) =>
{
const [editing, setEditing] = useState(false);
const ref = useRef<HTMLInputElement>(null);
const onClick = () =>
{
setEditing(false);
if (ref.current && onUpdate)
onUpdate(ref.current.value);
};
const input = inputElement ? inputElement : <input defaultValue={value} ref={ref} />;
if (editing)
return <span className='input-group'>
{input}
<button className="button primary" onClick={onClick} >
OK
</button>
</span>;
return <span onClick={() => setEditing(true)} className='mt-0 mb-1 clickable'>{value}</span>;
};
const DropdownHeader = ({ children, className = '' }: DropdownBaseProps) =>
{
return <summary className={`clickable card is-vertical-align header p-2 ${className}`}>
{children}
</summary>;
};
const DropdownItem = ({ children, type, selected, onClick }: DropdownItemProps) =>
{
let InnerElement = null;
if (type === 'multi-select')
InnerElement = <ToggleSwitch value={selected || false} onChange={onClick}>
{children as string}
</ToggleSwitch>;
else
InnerElement = <div onClick={(event) =>
{
event.preventDefault();
if (onClick)
onClick(event);
}}>
{children}
</div>;
return <div className='card item clickable'>
{InnerElement}
</div>;
};
const DropdownItemList = ({ children, className = '' }: DropdownBaseProps) =>
{
return <div className={`card item-list ${className}`}>
{children}
</div>;
};
type DropdownProps = {
name?: string,
multi?: boolean,
selection?: [],
children: React.ReactNode[],
className?: string
}
const DropdownComp = ({ children, className = '' }: DropdownProps) =>
{
if (!children)
throw new Error('Missing children');
if (!children.some(element => element && (element as React.ReactElement).type === DropdownHeader))
throw new Error('Missing a header');
const detailsRef = useRef<HTMLDetailsElement>(null);
return <ClickDetector callback={() =>
{
if (detailsRef.current)
detailsRef.current.open = false;
}}>
<details ref={detailsRef} className={`dropdown w-100 ${className}`}>
{children}
</details>
</ClickDetector>;
};
const Dropdown = Object.assign(DropdownComp, {
Header: DropdownHeader,
ItemList: DropdownItemList,
Item: DropdownItem
});
export type InputElementType =
| ((props: InputElementProperties<string>) => React.ReactElement)
| ((props: InputElementProperties<boolean>) => React.ReactElement)
| ((props: NumberInputProperties) => React.ReactElement);
export { Dropdown };

View File

@ -7,22 +7,27 @@ type PageButtonProps = {
pages: number
}
export const PageButtons = ({ setPage, page, pages }: PageButtonProps) => {
export const PageButtons = ({ setPage, page, pages }: PageButtonProps) =>
{
return <div className='flex is-vertical-align is-center page-controls'>
<button className="button dark" disabled={page === 1} onClick={() => {
<button className="button dark" disabled={page === 1} onClick={() =>
{
setPage(page - 1 || 1);
}}>Previous</button>
<p>Page: {page} / {pages}</p>
<button className="button dark" disabled={page === pages} onClick={() => {
<button className="button dark" disabled={page === pages} onClick={() =>
{
if (page < pages)
setPage(page + 1);
}}>Next</button>
</div>;
};
export const BackButton = () => {
export const BackButton = () =>
{
const navigate = useNavigate();
return <button className="button dark" onClick={() => {
return <button className="button dark" onClick={() =>
{
navigate(-1);
}}>Back</button>;
};

View File

@ -1,8 +1,10 @@
import React from "react";
import '../css/components/PageElements.css';
export const Popup = ({ display = false, children }: { display: boolean, children: React.ReactElement }) => {
if (!display) return null;
export const Popup = ({ display = false, children }: { display: boolean, children: React.ReactElement }) =>
{
if (!display)
return null;
return <div className='popup'>
{children}
</div>;

View File

@ -1,82 +1,95 @@
import React, {} from 'react';
import '../css/components/Sidebar.css';
import NavLink from '../structures/NavLink';
import logoImg from '../img/logo.png';
import { useNavigate } from "react-router";
import { useLoginContext } from "../structures/UserContext";
import { clearSession, post } from "../util/Util";
import { SidebarMenuItem } from '../@types/Other';
const Sidebar = ({children}: {children?: React.ReactNode}) => {
return <div className='sidebar card'>
{children}
</div>;
};
const toggleMenu: React.MouseEventHandler = (event) => {
event.preventDefault();
(event.target as HTMLElement).parentElement?.classList.toggle("open");
};
const expandMobileMenu: React.MouseEventHandler = (event) => {
event.preventDefault();
(event.target as HTMLElement).parentElement?.parentElement?.classList.toggle("show-menu");
};
const closeMobileMenu: React.MouseEventHandler = (event) => {
const element = event.target as HTMLElement;
if(element.classList.contains("sidebar-menu-item-carrot")) return;
(element.getRootNode() as ParentNode).querySelector(".sidebar")?.classList.remove("show-menu");
};
// Nav menu
const SidebarMenu = ({menuItems = [], children}: {menuItems: SidebarMenuItem[], children?: React.ReactNode}) => {
const [user, updateUser] = useLoginContext();
const navigate = useNavigate();
if (!user) return null;
const logOut = async () => {
const response = await post('/api/logout');
if (response.status === 200) {
clearSession();
updateUser();
navigate('/login');
}
};
const elements = [];
for (const menuItem of menuItems) {
const { label, items: subItems = [], ...rest } = menuItem;
let subElements = null;
if (subItems.length) subElements = subItems.map(({ label, to, relative = true }) => {
if(relative) to = `${menuItem.to}${to}`;
return <NavLink className='sidebar-menu-item sidebar-menu-child-item' onClick={closeMobileMenu} activeClassName='active' to={to} key={label}>{label}</NavLink>;
});
elements.push(<div key={label} className='parent-menu'>
<NavLink className={`sidebar-menu-item ${subElements?.length ? 'has-children' : ''}`} onClick={closeMobileMenu} activeClassName='active open' {...rest} key={label}>
{label}{subElements && <i className="sidebar-menu-item-carrot" onClick={toggleMenu}></i>}
</NavLink>
{subElements && <div className='sidebar-menu-child-wrapper'>
{subElements}
</div>}
</div>);
}
return <div className='sidebar-menu'>
<span className='hamburger' onClick={expandMobileMenu}></span>
<img className="sidebar-logo" src={logoImg}/>
{elements}
{children}
<div className="parent-menu log-out-menu-item">
<a className="sidebar-menu-item" onClick={logOut} href="#">Log Out</a>
</div>
</div>;
};
export {SidebarMenu, Sidebar};
import React, {} from 'react';
import '../css/components/Sidebar.css';
import NavLink from '../structures/NavLink';
import logoImg from '../img/logo.png';
import { useNavigate } from "react-router";
import { useLoginContext } from "../structures/UserContext";
import { clearSession, post } from "../util/Util";
import { SidebarMenuItem } from '../@types/Other';
const Sidebar = ({children}: {children?: React.ReactNode}) =>
{
return <div className='sidebar card'>
{children}
</div>;
};
const toggleMenu: React.MouseEventHandler = (event) =>
{
event.preventDefault();
(event.target as HTMLElement).parentElement?.classList.toggle("open");
};
const expandMobileMenu: React.MouseEventHandler = (event) =>
{
event.preventDefault();
(event.target as HTMLElement).parentElement?.parentElement?.classList.toggle("show-menu");
};
const closeMobileMenu: React.MouseEventHandler = (event) =>
{
const element = event.target as HTMLElement;
if(element.classList.contains("sidebar-menu-item-carrot"))
return;
(element.getRootNode() as ParentNode).querySelector(".sidebar")?.classList.remove("show-menu");
};
// Nav menu
const SidebarMenu = ({menuItems = [], children}: {menuItems: SidebarMenuItem[], children?: React.ReactNode}) =>
{
const [user, updateUser] = useLoginContext();
const navigate = useNavigate();
if (!user)
return null;
const logOut = async () =>
{
const response = await post('/api/logout');
if (response.status === 200)
{
clearSession();
updateUser();
navigate('/login');
}
};
const elements = [];
for (const menuItem of menuItems)
{
const { label, items: subItems = [], ...rest } = menuItem;
let subElements = null;
if (subItems.length)
subElements = subItems.map(({ label, to, relative = true }) =>
{
if(relative)
to = `${menuItem.to}${to}`;
return <NavLink className='sidebar-menu-item sidebar-menu-child-item' onClick={closeMobileMenu} activeClassName='active' to={to} key={label}>{label}</NavLink>;
});
elements.push(<div key={label} className='parent-menu'>
<NavLink className={`sidebar-menu-item ${subElements?.length ? 'has-children' : ''}`} onClick={closeMobileMenu} activeClassName='active open' {...rest} key={label}>
{label}{subElements && <i className="sidebar-menu-item-carrot" onClick={toggleMenu}></i>}
</NavLink>
{subElements && <div className='sidebar-menu-child-wrapper'>
{subElements}
</div>}
</div>);
}
return <div className='sidebar-menu'>
<span className='hamburger' onClick={expandMobileMenu}></span>
<img className="sidebar-logo" src={logoImg}/>
{elements}
{children}
<div className="parent-menu log-out-menu-item">
<a className="sidebar-menu-item" onClick={logOut} href="#">Log Out</a>
</div>
</div>;
};
export {SidebarMenu, Sidebar};
export default Sidebar;

View File

@ -1,45 +1,47 @@
import React from "react";
type Item = {
[key: string]: unknown
}
type TableEntry = {
onClick?: () => void,
item: Item,
itemKeys: string[]
}
type TableProps = {
headerItems: string[],
children?: React.ReactNode,
items?: Item[],
itemKeys?: string[]
}
export const TableListEntry = ({onClick, item, itemKeys}: TableEntry) => {
return <tr onClick={onClick}>
{itemKeys.map(key => <td key={key}>{item[key] as string}</td>)}
</tr>;
};
export const Table = ({headerItems, children, items, itemKeys}: TableProps) => {
if (!headerItems)
throw new Error(`Missing table headers`);
if(!children && !items)
throw new Error('Missing items or children');
let i = 0;
return <table className="striped hover" >
<thead>
<tr>
{headerItems.map(item => <th key={item}>{item}</th>)}
</tr>
</thead>
<tbody>
{children ? children : items?.map(item => <TableListEntry key={i++} item={item} itemKeys={itemKeys as string[]} />)}
</tbody>
</table>;
import React from "react";
type Item = {
[key: string]: unknown
}
type TableEntry = {
onClick?: () => void,
item: Item,
itemKeys: string[]
}
type TableProps = {
headerItems: string[],
children?: React.ReactNode,
items?: Item[],
itemKeys?: string[]
}
export const TableListEntry = ({onClick, item, itemKeys}: TableEntry) =>
{
return <tr onClick={onClick}>
{itemKeys.map(key => <td key={key}>{item[key] as string}</td>)}
</tr>;
};
export const Table = ({headerItems, children, items, itemKeys}: TableProps) =>
{
if (!headerItems)
throw new Error(`Missing table headers`);
if(!children && !items)
throw new Error('Missing items or children');
let i = 0;
return <table className="striped hover" >
<thead>
<tr>
{headerItems.map(item => <th key={item}>{item}</th>)}
</tr>
</thead>
<tbody>
{children ? children : items?.map(item => <TableListEntry key={i++} item={item} itemKeys={itemKeys as string[]} />)}
</tbody>
</table>;
};

View File

@ -1,14 +1,15 @@
import React from "react";
import '../css/pages/Empty.css';
const TitledPage = ({title, children}: {title: string, children: React.ReactNode}) => {
return <div className="page">
<h2 className="pageTitle">{title}</h2>
<div className='card'>
{children}
</div>
</div>;
};
import React from "react";
import '../css/pages/Empty.css';
const TitledPage = ({title, children}: {title: string, children: React.ReactNode}) =>
{
return <div className="page">
<h2 className="pageTitle">{title}</h2>
<div className='card'>
{children}
</div>
</div>;
};
export default TitledPage;

View File

@ -1,45 +1,51 @@
import React, { useRef } from "react";
import { useNavigate } from "react-router";
import '../css/components/UserControls.css';
import { useLoginContext } from "../structures/UserContext";
import ClickDetector from "../util/ClickDetector";
import { clearSession, post } from "../util/Util";
const UserControls = () => {
const [user, updateUser] = useLoginContext();
const detailsRef = useRef<HTMLDetailsElement>(null);
const navigate = useNavigate();
if (!user) return null;
const logOut = async () => {
const response = await post('/api/logout');
if (response.status === 200) {
clearSession();
updateUser();
navigate('/login');
}
};
return <ClickDetector callback={() => {
if (detailsRef.current) detailsRef.current.removeAttribute('open');
}}>
<details ref={detailsRef} className='dropdown user-controls'>
<summary className="is-vertical-align">
Hello {user.displayName || user.name}
<img className="profile-picture" src={`/api/users/${user.id}/avatar`}></img>
</summary>
<div className="card">
<p><a href="#">Profile</a></p>
<hr />
<p><a onClick={logOut} href="#" className="text-error">Logout</a></p>
</div>
</details>
</ClickDetector >;
};
import React, { useRef } from "react";
import { useNavigate } from "react-router";
import '../css/components/UserControls.css';
import { useLoginContext } from "../structures/UserContext";
import ClickDetector from "../util/ClickDetector";
import { clearSession, post } from "../util/Util";
const UserControls = () =>
{
const [user, updateUser] = useLoginContext();
const detailsRef = useRef<HTMLDetailsElement>(null);
const navigate = useNavigate();
if (!user)
return null;
const logOut = async () =>
{
const response = await post('/api/logout');
if (response.status === 200)
{
clearSession();
updateUser();
navigate('/login');
}
};
return <ClickDetector callback={() =>
{
if (detailsRef.current)
detailsRef.current.removeAttribute('open');
}}>
<details ref={detailsRef} className='dropdown user-controls'>
<summary className="is-vertical-align">
Hello {user.displayName || user.name}
<img className="profile-picture" src={`/api/users/${user.id}/avatar`}></img>
</summary>
<div className="card">
<p><a href="#">Profile</a></p>
<hr />
<p><a onClick={logOut} href="#" className="text-error">Logout</a></p>
</div>
</details>
</ClickDetector >;
};
export default UserControls;

View File

@ -8,11 +8,11 @@ import { BrowserRouter } from 'react-router-dom';
const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement);
root.render(<React.StrictMode>
<UserContext>
<BrowserRouter>
<App />
</BrowserRouter>
</UserContext>
<UserContext>
<BrowserRouter>
<App />
</BrowserRouter>
</UserContext>
</React.StrictMode>);
// root.render(<UserContext>
// <App />

View File

@ -1,51 +1,54 @@
import React, { useState } from "react";
import { Route, Routes } from "react-router";
import { FileSelector } from "../components/InputElements";
import '../css/pages/Admin.css';
import ErrorBoundary from "../util/ErrorBoundary";
import Roles from "./admin/Roles";
import Users from "./admin/Users";
import Flags from "./admin/Flags";
const Main = () => {
const [file, setFile] = useState<File | null>(null);
const submit: React.MouseEventHandler = (event) => {
event.preventDefault();
console.log(file);
};
return <div className="row">
<div className="col-6-lg col-12">
<h2>Thematic customisation</h2>
<form>
<input type='text' placeholder='Site name' />
<FileSelector cb={setFile} />
<button onClick={submit}>Submit</button>
</form>
</div>
<div className="col-6-lg col-12">
<h2>Dingus</h2>
</div>
</div>;
};
const Admin = () => {
return <ErrorBoundary>
<Routes>
<Route path="/" element={<Main />} />
<Route path="/users/*" element={<Users />} />
<Route path='/roles/*' element={<Roles />} />
<Route path='/flags/*' element={<Flags />} />
</Routes>
</ErrorBoundary>;
};
import React, { useState } from "react";
import { Route, Routes } from "react-router";
import { FileSelector } from "../components/InputElements";
import '../css/pages/Admin.css';
import ErrorBoundary from "../util/ErrorBoundary";
import Roles from "./admin/Roles";
import Users from "./admin/Users";
import Flags from "./admin/Flags";
const Main = () =>
{
const [file, setFile] = useState<File | null>(null);
const submit: React.MouseEventHandler = (event) =>
{
event.preventDefault();
console.log(file);
};
return <div className="row">
<div className="col-6-lg col-12">
<h2>Thematic customisation</h2>
<form>
<input type='text' placeholder='Site name' />
<FileSelector cb={setFile} />
<button onClick={submit}>Submit</button>
</form>
</div>
<div className="col-6-lg col-12">
<h2>Dingus</h2>
</div>
</div>;
};
const Admin = () =>
{
return <ErrorBoundary>
<Routes>
<Route path="/" element={<Main />} />
<Route path="/users/*" element={<Users />} />
<Route path='/roles/*' element={<Roles />} />
<Route path='/flags/*' element={<Flags />} />
</Routes>
</ErrorBoundary>;
};
export default Admin;

View File

@ -1,25 +1,27 @@
import React from "react";
import { Route, Routes } from "react-router";
import '../css/pages/Home.css';
import ErrorBoundary from "../util/ErrorBoundary";
import Applications from "./home/Applications";
import Profile from "./home/Profile";
const Main = () => {
return <div>
What to put here? hmmm
</div>;
};
const Home = () => {
return <ErrorBoundary>
<Routes>
<Route path="/" element={<Main />} />
<Route path="/profile" element={<Profile />} />
<Route path="/applications/*" element={<Applications />} />
</Routes>
</ErrorBoundary>;
};
import React from "react";
import { Route, Routes } from "react-router";
import '../css/pages/Home.css';
import ErrorBoundary from "../util/ErrorBoundary";
import Applications from "./home/Applications";
import Profile from "./home/Profile";
const Main = () =>
{
return <div>
What to put here? hmmm
</div>;
};
const Home = () =>
{
return <ErrorBoundary>
<Routes>
<Route path="/" element={<Main />} />
<Route path="/profile" element={<Profile />} />
<Route path="/applications/*" element={<Applications />} />
</Routes>
</ErrorBoundary>;
};
export default Home;

View File

@ -1,146 +1,159 @@
import React, { useState, useRef } from "react";
import { Route, Routes, useNavigate } from "react-router";
import '../css/pages/Login.css';
import logoImg from '../img/logo.png';
import { useLoginContext } from "../structures/UserContext";
import LoadingBar, {LoadingBarRef} from 'react-top-loading-bar';
import { fetchUser, getSettings, post } from "../util/Util";
import { OAuthProvider } from "../@types/Other";
const CredentialFields = () => {
const [, setUser] = useLoginContext();
const [fail, setFail] = useState(false);
const navigate = useNavigate();
const ref = useRef<LoadingBarRef>(null);
const usernameRef = useRef<HTMLInputElement>(null);
const passwordRef = useRef<HTMLInputElement>(null);
const loginMethods = getSettings()?.OAuthProviders || [];
const loginClick: React.MouseEventHandler = async (event: React.MouseEvent) => {
ref.current?.continuousStart();
event.preventDefault();
// const username = (document.getElementById('username') as HTMLInputElement)?.value;
// const password = (document.getElementById('password') as HTMLInputElement)?.value;
const username = usernameRef.current?.value;
const password = passwordRef.current?.value;
if (!username?.length || !password?.length) return;
const result = await post('/api/login', { username, password });
if (![200, 302].includes(result.status)) {
ref.current?.complete();
setFail(true);
return;
}
if (!result.data?.twoFactor) {
setUser(await fetchUser());
ref.current?.complete();
return navigate('/home');
}
ref.current?.complete();
return navigate('verify');
};
return <div>
<LoadingBar color='#2685ff' ref={ref} />
<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>
{fail ? <p>Invalid credentials</p> : null}
<form className="loginForm">
<input ref={usernameRef} autoComplete='off' placeholder='Username' required id='username' type='text' autoFocus />
<input ref={passwordRef} autoComplete='off' placeholder='Password' required id='password' type='password' />
<button className="button primary" onClick={loginClick}>Enter</button>
</form>
<div className="text-center registerText">
Don&apos;t have an account?<br/><a onClick={() => navigate('/register')} className="clickable">Register</a> instead!
</div>
</div>
<div className="card is-center dir-column">
<b>Alternate login methods</b>
<div className="methodsWrapper is-center flex-wrap">
{loginMethods.map((method: OAuthProvider) => <div
className='third-party-login'
key={method.name}
onClick={() => { window.location.pathname = `/api/login/${method.name}`; }}>
<img
crossOrigin="anonymous"
alt={method.name}
src={method.icon}
width={48} height={48}
/>
<p><b>{method.name}</b></p>
</div>)}
</div>
</div>
</div>;
};
const TwoFactor = () => {
const [fail, setFail] = useState(false);
const [, setUser] = useLoginContext();
const navigate = useNavigate();
const mfaCode = useRef<HTMLInputElement>(null);
const ref = useRef<LoadingBarRef>(null);
const twoFactorClick: React.MouseEventHandler = async (event) => {
event.preventDefault();
// const code = document.getElementById('2faCode').value;
const code = mfaCode.current?.value;
if (!code) return;
ref.current?.continuousStart();
const result = await post('/api/login/verify', { code });
if (result.status === 200) {
setUser(await fetchUser());
ref.current?.complete();
return navigate('/home');
}
ref.current?.complete();
setFail(true);
};
return <div>
<LoadingBar color='#2685ff' ref={ref} />
<div className="is-center">
<img className="logoImg mb-4" src={logoImg}></img>
</div>
<div className="card mb-3 is-center dir-column">
<h2>Verification Code</h2>
{fail ? <p className="mt-0">Invalid code</p> : null}
<form className="is-center dir-column">
<input ref={mfaCode} autoComplete='off' placeholder='Your 2FA code...' required id='2faCode' type='password' />
<button className="button primary mt-1 mb-3" onClick={twoFactorClick}>Enter</button>
</form>
</div>
</div>;
};
const Login = () => {
return <div className="row is-center is-full-screen is-marginless">
<div className='loginWrapper col-6 col-6-md col-3-lg'>
<Routes>
<Route path='/' element={<CredentialFields />} />
<Route path='/verify' element={<TwoFactor />} />
</Routes>
</div>
</div>;
};
import React, { useState, useRef } from "react";
import { Route, Routes, useNavigate } from "react-router";
import '../css/pages/Login.css';
import logoImg from '../img/logo.png';
import { useLoginContext } from "../structures/UserContext";
import LoadingBar, {LoadingBarRef} from 'react-top-loading-bar';
import { fetchUser, getSettings, post } from "../util/Util";
import { OAuthProvider } from "../@types/Other";
const CredentialFields = () =>
{
const [, setUser] = useLoginContext();
const [fail, setFail] = useState(false);
const navigate = useNavigate();
const ref = useRef<LoadingBarRef>(null);
const usernameRef = useRef<HTMLInputElement>(null);
const passwordRef = useRef<HTMLInputElement>(null);
const loginMethods = getSettings()?.OAuthProviders || [];
const loginClick: React.MouseEventHandler = async (event: React.MouseEvent) =>
{
ref.current?.continuousStart();
event.preventDefault();
// const username = (document.getElementById('username') as HTMLInputElement)?.value;
// const password = (document.getElementById('password') as HTMLInputElement)?.value;
const username = usernameRef.current?.value;
const password = passwordRef.current?.value;
if (!username?.length || !password?.length)
return;
const result = await post('/api/login', { username, password });
if (![200, 302].includes(result.status))
{
ref.current?.complete();
setFail(true);
return;
}
if (!result.data?.twoFactor)
{
setUser(await fetchUser());
ref.current?.complete();
return navigate('/home');
}
ref.current?.complete();
return navigate('verify');
};
return <div>
<LoadingBar color='#2685ff' ref={ref} />
<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>
{fail ? <p>Invalid credentials</p> : null}
<form className="loginForm">
<input ref={usernameRef} autoComplete='off' placeholder='Username' required id='username' type='text' autoFocus />
<input ref={passwordRef} autoComplete='off' placeholder='Password' required id='password' type='password' />
<button className="button primary" onClick={loginClick}>Enter</button>
</form>
<div className="text-center registerText">
Don&apos;t have an account?<br/><a onClick={() => navigate('/register')} className="clickable">Register</a> instead!
</div>
</div>
<div className="card is-center dir-column">
<b>Alternate login methods</b>
<div className="methodsWrapper is-center flex-wrap">
{loginMethods.map((method: OAuthProvider) => <div
className='third-party-login'
key={method.name}
onClick={() =>
{
window.location.pathname = `/api/login/${method.name}`;
}}>
<img
crossOrigin="anonymous"
alt={method.name}
src={method.icon}
width={48} height={48}
/>
<p><b>{method.name}</b></p>
</div>)}
</div>
</div>
</div>;
};
const TwoFactor = () =>
{
const [fail, setFail] = useState(false);
const [, setUser] = useLoginContext();
const navigate = useNavigate();
const mfaCode = useRef<HTMLInputElement>(null);
const ref = useRef<LoadingBarRef>(null);
const twoFactorClick: React.MouseEventHandler = async (event) =>
{
event.preventDefault();
// const code = document.getElementById('2faCode').value;
const code = mfaCode.current?.value;
if (!code)
return;
ref.current?.continuousStart();
const result = await post('/api/login/verify', { code });
if (result.status === 200)
{
setUser(await fetchUser());
ref.current?.complete();
return navigate('/home');
}
ref.current?.complete();
setFail(true);
};
return <div>
<LoadingBar color='#2685ff' ref={ref} />
<div className="is-center">
<img className="logoImg mb-4" src={logoImg}></img>
</div>
<div className="card mb-3 is-center dir-column">
<h2>Verification Code</h2>
{fail ? <p className="mt-0">Invalid code</p> : null}
<form className="is-center dir-column">
<input ref={mfaCode} autoComplete='off' placeholder='Your 2FA code...' required id='2faCode' type='password' />
<button className="button primary mt-1 mb-3" onClick={twoFactorClick}>Enter</button>
</form>
</div>
</div>;
};
const Login = () =>
{
return <div className="row is-center is-full-screen is-marginless">
<div className='loginWrapper col-6 col-6-md col-3-lg'>
<Routes>
<Route path='/' element={<CredentialFields />} />
<Route path='/verify' element={<TwoFactor />} />
</Routes>
</div>
</div>;
};
export default Login;

View File

@ -1,66 +1,70 @@
import React, { useState, useRef } from "react";
import { useNavigate, useSearchParams } from "react-router-dom";
import { post } from "../util/Util";
import '../css/pages/Register.css';
import logoImg from '../img/logo.png';
import LoadingBar, {LoadingBarRef} from 'react-top-loading-bar';
const Register = () => {
const [error, setError] = useState<string>();
const [params] = useSearchParams();
const navigate = useNavigate();
const ref = useRef<LoadingBarRef>(null);
const usernameRef = useRef<HTMLInputElement>(null);
const passwordRef = useRef<HTMLInputElement>(null);
document.body.classList.add('bg-triangles');
const code = params.get('code');
const submit: React.MouseEventHandler = async (event) => {
ref.current?.continuousStart();
event.preventDefault();
const username = usernameRef.current?.value;
const password = passwordRef.current?.value;
if (!username?.length || !password?.length) {
ref.current?.complete();
return;
}
const response = await post('/api/register', { username, password, code });
if (response.status !== 200) {
ref.current?.complete();
return setError(response.message as string || 'unknown error');
}
ref.current?.complete();
navigate('/login');
};
return <div className="row is-center is-full-screen is-marginless">
<LoadingBar color='#2685ff' ref={ref} />
<div className='registerWrapper col-6 col-6-md col-3-lg'>
<div>
<div className="is-center">
<img className="logoImg mb-4" src={logoImg}></img>
</div>
<div className="card mb-3 is-center dir-column">
<h2>Register</h2>
{error && <p>{error}</p>}
<form className="registerForm">
<input ref={usernameRef} autoComplete='off' placeholder='Username' required id='username' type='text' autoFocus />
<input ref={passwordRef} autoComplete='off' placeholder='Password' required id='password' type='password' />
<button className="button primary" onClick={submit}>Register</button>
</form>
<div className="text-center registerText">
Have an account?<br/><a onClick={() => navigate('/login')} className="clickable">Log in</a> instead!
</div>
</div>
</div>
</div>
</div>;
};
import React, { useState, useRef } from "react";
import { useNavigate, useSearchParams } from "react-router-dom";
import { post } from "../util/Util";
import '../css/pages/Register.css';
import logoImg from '../img/logo.png';
import LoadingBar, {LoadingBarRef} from 'react-top-loading-bar';
const Register = () =>
{
const [error, setError] = useState<string>();
const [params] = useSearchParams();
const navigate = useNavigate();
const ref = useRef<LoadingBarRef>(null);
const usernameRef = useRef<HTMLInputElement>(null);
const passwordRef = useRef<HTMLInputElement>(null);
document.body.classList.add('bg-triangles');
const code = params.get('code');
const submit: React.MouseEventHandler = async (event) =>
{
ref.current?.continuousStart();
event.preventDefault();
const username = usernameRef.current?.value;
const password = passwordRef.current?.value;
if (!username?.length || !password?.length)
{
ref.current?.complete();
return;
}
const response = await post('/api/register', { username, password, code });
if (response.status !== 200)
{
ref.current?.complete();
return setError(response.message as string || 'unknown error');
}
ref.current?.complete();
navigate('/login');
};
return <div className="row is-center is-full-screen is-marginless">
<LoadingBar color='#2685ff' ref={ref} />
<div className='registerWrapper col-6 col-6-md col-3-lg'>
<div>
<div className="is-center">
<img className="logoImg mb-4" src={logoImg}></img>
</div>
<div className="card mb-3 is-center dir-column">
<h2>Register</h2>
{error && <p>{error}</p>}
<form className="registerForm">
<input ref={usernameRef} autoComplete='off' placeholder='Username' required id='username' type='text' autoFocus />
<input ref={passwordRef} autoComplete='off' placeholder='Password' required id='password' type='password' />
<button className="button primary" onClick={submit}>Register</button>
</form>
<div className="text-center registerText">
Have an account?<br/><a onClick={() => navigate('/login')} className="clickable">Log in</a> instead!
</div>
</div>
</div>
</div>
</div>;
};
export default Register;

View File

@ -9,12 +9,14 @@ import { get, patch, post } from "../../util/Util";
import { Permissions as Perms, Role as R } from "../../@types/ApiStructures";
import { ToggleSwitch } from "../../components/InputElements";
const Role = ({ role }: {role: R}) => {
const Role = ({ role }: {role: R}) =>
{
// const perms = { ...role.permissions };
const [perms, updatePerms] = useState<Perms>(role.permissions);
const commitPerms = async () => {
const commitPerms = async () =>
{
await patch(`/api/roles/${role.id}`, perms);
};
@ -35,9 +37,9 @@ const Role = ({ role }: {role: R}) => {
<p><b>Created: </b>{new Date(role.createdTimestamp).toDateString()}</p>
{/* <p><b>Disabled: </b>{role.disabled.toString()}</p> */}
<ToggleSwitch value={role.disabled}>
<ToggleSwitch value={role.disabled}>
Disabled
</ToggleSwitch>
</ToggleSwitch>
<label htmlFor='username'>Name</label>
<input autoComplete='off' id='username' defaultValue={role.name} />
@ -57,21 +59,25 @@ const Role = ({ role }: {role: R}) => {
</div>;
};
const CreateRoleField = ({ numRoles, className, addRole }: { numRoles: number, className?: string, addRole: (role: R) => void }) => {
const CreateRoleField = ({ numRoles, className, addRole }: { numRoles: number, className?: string, addRole: (role: R) => void }) =>
{
const [error, setError] = useState<string | null>(null);
const nameRef = useRef<HTMLInputElement>(null);
const positionRef = useRef<HTMLInputElement>(null);
const createRole: React.MouseEventHandler<HTMLButtonElement> = async (event) => {
const createRole: React.MouseEventHandler<HTMLButtonElement> = async (event) =>
{
event.preventDefault();
if (!nameRef.current || !positionRef.current) return setError('Must supply name and position');
if (!nameRef.current || !positionRef.current)
return setError('Must supply name and position');
const name = nameRef.current.value;
const position = parseInt(positionRef.current.value);
const response = await post('/api/roles', { name, position });
if (!response.success) return setError(response.message || 'Unknown error');
if (!response.success)
return setError(response.message || 'Unknown error');
addRole(response.data as R);
};
@ -94,7 +100,8 @@ const CreateRoleField = ({ numRoles, className, addRole }: { numRoles: number, c
};
const Roles = () => {
const Roles = () =>
{
const [error, setError] = useState<string | null>(null);
const [roles, setRoles] = useState<R[]>([]);
@ -102,41 +109,50 @@ const Roles = () => {
const [pages, setPages] = useState(1);
const [loading, setLoading] = useState(true);
useEffect(() => {
(async () => {
useEffect(() =>
{
(async () =>
{
const result = await get('/api/roles', { page });
if (result.success && result.data) {
if (result.success && result.data)
{
setError(null);
setRoles(result.data.roles as R[]);
setPages(result.data.pages);
} else {
}
else
{
setError(result.message || 'Unknown error');
}
setLoading(false);
})();
}, [page]);
const RoleWrapper = () => {
const RoleWrapper = () =>
{
const { id } = useParams();
const role = roles.find(r => r.id === id);
if(!role) return <p>Unknown role</p>;
if(!role)
return <p>Unknown role</p>;
return <Role role={role} />;
};
const navigate = useNavigate();
const RoleListWrapper = () => {
const RoleListWrapper = () =>
{
return <div className="role-list-wrapper row">
<div className={`col-6-lg col-12 ld ${loading && 'loading'}`}>
<h4>All Roles</h4>
<Table headerItems={['Name', 'ID']}>
{roles.map(role => <TableListEntry
onClick={() => {
navigate(role.id);
}}
key={role.id}
item={role}
itemKeys={['name', 'id']}
/>)}
onClick={() =>
{
navigate(role.id);
}}
key={role.id}
item={role}
itemKeys={['name', 'id']}
/>)}
</Table>
<PageButtons {...{page, setPage, pages}} />

View File

@ -1,321 +1,359 @@
import React, { useContext, useEffect, useState } from "react";
import { Route, Routes, useNavigate, useParams } from "react-router";
import ErrorBoundary from "../../util/ErrorBoundary";
import { get, post } from '../../util/Util';
import '../../css/pages/Users.css';
import { Table, TableListEntry } from "../../components/Table";
import { BackButton, PageButtons } from "../../components/PageControls";
import { Permissions } from "../../views/PermissionsView";
import { Application as App, Permissions as Perms, User as APIUser, Role } from "../../@types/ApiStructures";
import { Dropdown, ToggleSwitch } from "../../components/InputElements";
type PartialUser = {
apps: App[]
}
const SelectedUserContext = React.createContext<{
user: PartialUser | null,
updateUser:(user: PartialUser) => void
}>({
user: null,
updateUser: () => { /** */ }
});
const Context = ({ children }: { children: React.ReactNode }) => {
const [user, updateUser] = useState<PartialUser | null>(null);
return <SelectedUserContext.Provider value={{ user, updateUser }}>
{children}
</SelectedUserContext.Provider>;
};
const ApplicationList = ({ apps }: { apps: App[] }) => {
const navigate = useNavigate();
return <Table headerItems={['Name', 'ID']}>
{apps.map(app => <TableListEntry
onClick={() => {
navigate(`applications/${app.id}`);
}}
key={app.id}
item={app}
itemKeys={['name', 'id']}
/>)}
</Table>;
};
const Application = ({ app }: { app: App }) => {
const commitPerms = async () => {
await post(`/api/applications/${app.id}/permissions`, perms);
};
const [perms, updatePerms] = useState<Perms>(app.permissions);
const descProps = { defaultValue: app.description || '', placeholder: 'Describe your application' };
return <div>
<div className='row'>
<div className='col-6-lg col-12'>
<div className='flex is-vertical-align flex-wrap'>
<BackButton />
<h2 className='userId'>Application {app.name} ({app.id})</h2>
</div>
<p><b>Created: </b>{new Date(app.createdTimestamp).toDateString()}</p>
<ToggleSwitch value={app.disabled}>
Disabled:
</ToggleSwitch>
<b>Description</b>
<textarea {...descProps} >
</textarea>
</div>
<div className="col-6-lg col-12">
<Permissions onUpdate={updatePerms} perms={perms} />
<button onClick={commitPerms} className="button primary">Save Permissions</button>
</div>
</div>
</div>;
};
const RoleComp = ({ role, onClick }: { role: Role, onClick: React.ReactEventHandler }) => {
return <div className='card role' >
{role.name} <span className="clickable" onClick={onClick}>X</span>
</div>;
};
const Roles = ({ userRoles, roles }: { userRoles: Role[], roles: Role[] }) => {
const [unequippedRoles, updateUnequipped] = useState<Role[]>(roles.filter(role => !userRoles.some(r => role.id === r.id)));
const [equippedRoles, updateEquipped] = useState<Role[]>(userRoles);
const roleSelected = (role: Role) => {
updateEquipped([...equippedRoles, role]);
updateUnequipped(unequippedRoles.filter(r => r.id !== role.id));
};
const roleDeselected = (role: Role) => {
updateEquipped(equippedRoles.filter(r => r.id !== role.id));
updateUnequipped([...unequippedRoles, role]);
};
return <Dropdown>
<Dropdown.Header className='role-selector'>
{equippedRoles.map(role => <RoleComp key={role.id} role={role} onClick={(event) => {
event.preventDefault();
roleDeselected(role);
}} />)}
</Dropdown.Header>
<Dropdown.ItemList>
{unequippedRoles.map(role => <Dropdown.Item
key={role.id}
onClick={() => {
roleSelected(role);
}}
>
{role.name}
</Dropdown.Item>)}
</Dropdown.ItemList>
</Dropdown>;
};
const User = ({ user, roles }: { user: APIUser, roles: Role[] }) => {
// const [apps, updateApps] = useState<App[]>([]);
const [perms, updatePerms] = useState<Perms>(user.permissions);
const userContext = useContext(SelectedUserContext);
useEffect(() => {
(async () => {
const appsResponse = await get(`/api/users/${user.id}/applications`);
if (appsResponse.success) {
const a = appsResponse.data as App[];
// updateApps(a);
userContext.updateUser({ apps: a });
import React, { useContext, useEffect, useState } from "react";
import { Route, Routes, useNavigate, useParams } from "react-router";
import ErrorBoundary from "../../util/ErrorBoundary";
import { get, post } from '../../util/Util';
import '../../css/pages/Users.css';
import { Table, TableListEntry } from "../../components/Table";
import { BackButton, PageButtons } from "../../components/PageControls";
import { Permissions } from "../../views/PermissionsView";
import { Application as App, Permissions as Perms, User as APIUser, Role } from "../../@types/ApiStructures";
import { Dropdown, ToggleSwitch } from "../../components/InputElements";
type PartialUser = {
apps: App[]
}
const SelectedUserContext = React.createContext<{
user: PartialUser | null,
updateUser:(user: PartialUser) => void
}>({
user: null,
updateUser: () =>
{ /** */ }
});
const Context = ({ children }: { children: React.ReactNode }) =>
{
const [user, updateUser] = useState<PartialUser | null>(null);
return <SelectedUserContext.Provider value={{ user, updateUser }}>
{children}
</SelectedUserContext.Provider>;
};
const ApplicationList = ({ apps }: { apps: App[] }) =>
{
const navigate = useNavigate();
return <Table headerItems={['Name', 'ID']}>
{apps.map(app => <TableListEntry
onClick={() =>
{
navigate(`applications/${app.id}`);
}}
key={app.id}
item={app}
itemKeys={['name', 'id']}
/>)}
</Table>;
};
const Application = ({ app }: { app: App }) =>
{
const commitPerms = async () =>
{
await post(`/api/applications/${app.id}/permissions`, perms);
};
const [perms, updatePerms] = useState<Perms>(app.permissions);
const descProps = { defaultValue: app.description || '', placeholder: 'Describe your application' };
return <div>
<div className='row'>
<div className='col-6-lg col-12'>
<div className='flex is-vertical-align flex-wrap'>
<BackButton />
<h2 className='userId'>Application {app.name} ({app.id})</h2>
</div>
<p><b>Created: </b>{new Date(app.createdTimestamp).toDateString()}</p>
<ToggleSwitch value={app.disabled}>
Disabled:
</ToggleSwitch>
<b>Description</b>
<textarea {...descProps} >
</textarea>
</div>
<div className="col-6-lg col-12">
<Permissions onUpdate={updatePerms} perms={perms} />
<button onClick={commitPerms} className="button primary">Save Permissions</button>
</div>
</div>
</div>;
};
const RoleComp = ({ role, onClick }: { role: Role, onClick: React.ReactEventHandler }) =>
{
return <div className='card role' >
{role.name} <span className="clickable" onClick={onClick}>X</span>
</div>;
};
const Roles = ({ userRoles, roles }: { userRoles: Role[], roles: Role[] }) =>
{
const [unequippedRoles, updateUnequipped] = useState<Role[]>(roles.filter(role => !userRoles.some(r => role.id === r.id)));
const [equippedRoles, updateEquipped] = useState<Role[]>(userRoles);
const roleSelected = (role: Role) =>
{
updateEquipped([...equippedRoles, role]);
updateUnequipped(unequippedRoles.filter(r => r.id !== role.id));
};
const roleDeselected = (role: Role) =>
{
updateEquipped(equippedRoles.filter(r => r.id !== role.id));
updateUnequipped([...unequippedRoles, role]);
};
return <Dropdown>
<Dropdown.Header className='role-selector'>
{equippedRoles.map(role => <RoleComp key={role.id} role={role} onClick={(event) =>
{
event.preventDefault();
roleDeselected(role);
}} />)}
</Dropdown.Header>
<Dropdown.ItemList>
{unequippedRoles.map(role => <Dropdown.Item
key={role.id}
onClick={() =>
{
roleSelected(role);
}}
>
{role.name}
</Dropdown.Item>)}
</Dropdown.ItemList>
</Dropdown>;
};
const User = ({ user, roles }: { user: APIUser, roles: Role[] }) =>
{
// const [apps, updateApps] = useState<App[]>([]);
const [perms, updatePerms] = useState<Perms>(user.permissions);
const userContext = useContext(SelectedUserContext);
useEffect(() =>
{
(async () =>
{
const appsResponse = await get(`/api/users/${user.id}/applications`);
if (appsResponse.success)
{
const a = appsResponse.data as App[];
// updateApps(a);
userContext.updateUser({ apps: a });
}
})();
}, []);
const commitPerms = async () =>
{
await post(`/api/users/${user.id}/permissions`, perms);
};
return <div className='user-card'>
<div className="row">
<div className="col-6-lg col-12">
<div className="flex is-vertical-align flex-wrap">
<BackButton />
<h2 className="userId">User {user.displayName} ({user.id})</h2>
</div>
<p><b>Created: </b>{new Date(user.createdTimestamp).toDateString()}</p>
<p><b>2FA:</b> {(user.twoFactor && <button className='button danger'>Disable</button>) || 'Disabled'}</p>
<ToggleSwitch value={user.disabled}>
Login Disabled:
</ToggleSwitch>
<label htmlFor='username'>Username</label>
<input autoComplete='off' id='username' defaultValue={user.name} />
<label htmlFor='displayName'>Display Name</label>
<input autoComplete='off' id='displayName' placeholder='Name to display instead of username' defaultValue={user.displayName || ''} />
<label htmlFor='userNote'>Note</label>
<textarea id='userNote' defaultValue={user.note} />
<label>Roles</label>
<Roles userRoles={user.roles} roles={roles} />
{/* <button className="button primary">
Save User
</button> */}
</div>
<div className="col-6-lg col-12">
<Permissions onUpdate={updatePerms} perms={user.permissions} />
<button onClick={commitPerms} className="button primary">Save Permissions</button>
</div>
</div>
<div className='row'>
<div className='col-6-lg col-12'>
<h3>Applications</h3>
{userContext.user && <ApplicationList apps={userContext.user.apps} />}
</div>
</div>
</div>;
};
const CreateUserField = ({ className }: { className: string }) =>
{
const [link, setLink] = useState<string | null>(null);
const getSignupCode = async () =>
{
const response = await get('/api/register/code');
if (response.status === 200 && response.data)
{
const link = `${window.location.origin}/register?code=${response.data.code}`;
setLink(link);
}
};
const copyToClipboard: React.MouseEventHandler = (event) =>
{
const element = event.target as HTMLElement;
const { parentElement } = element;
navigator.clipboard.writeText(element.innerText);
if (parentElement)
(parentElement.childNodes[parentElement.childNodes.length - 1] as HTMLElement).style.visibility = "visible";
};
const closeToolTip: React.MouseEventHandler = (event) =>
{
(event.target as HTMLElement).style.visibility = "hidden";
};
// TODO: Finish this
return <div className={className}>
<h4>One-Click Sign-Up</h4>
{link ?
<div className="registerCodeWrapper tooltip"><p onClick={copyToClipboard}>{link}</p><span onClick={closeToolTip} className="tooltiptext">Code copied!</span></div> :
<button onClick={getSignupCode} className="button primary is-center">Create sign-up link</button>}
<hr />
<h4>Create User</h4>
<form>
<p>Users will be forced to change the password you set here.</p>
<input placeholder="Username" autoComplete="off" type='text' id='username' />
<input placeholder="Password" autoComplete="off" type='password' id='password' />
</form>
</div>;
};
const Users = () =>
{
const [users, setUsers] = useState<APIUser[]>([]);
const [roles, updateRoles] = useState<Role[]>([]);
const [page, setPage] = useState(1);
const [pages, setPages] = useState(1);
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() =>
{
(async () =>
{
const result = await get('/api/users', { page });
if (result.success && result.data)
{
setError(null);
setUsers(result.data.users as APIUser[]);
setPages(result.data.pages);
}
})();
}, []);
const commitPerms = async () => {
await post(`/api/users/${user.id}/permissions`, perms);
};
return <div className='user-card'>
<div className="row">
<div className="col-6-lg col-12">
<div className="flex is-vertical-align flex-wrap">
<BackButton />
<h2 className="userId">User {user.displayName} ({user.id})</h2>
</div>
<p><b>Created: </b>{new Date(user.createdTimestamp).toDateString()}</p>
<p><b>2FA:</b> {(user.twoFactor && <button className='button danger'>Disable</button>) || 'Disabled'}</p>
<ToggleSwitch value={user.disabled}>
Login Disabled:
</ToggleSwitch>
<label htmlFor='username'>Username</label>
<input autoComplete='off' id='username' defaultValue={user.name} />
<label htmlFor='displayName'>Display Name</label>
<input autoComplete='off' id='displayName' placeholder='Name to display instead of username' defaultValue={user.displayName || ''} />
<label htmlFor='userNote'>Note</label>
<textarea id='userNote' defaultValue={user.note} />
<label>Roles</label>
<Roles userRoles={user.roles} roles={roles} />
{/* <button className="button primary">
Save User
</button> */}
</div>
<div className="col-6-lg col-12">
<Permissions onUpdate={updatePerms} perms={user.permissions} />
<button onClick={commitPerms} className="button primary">Save Permissions</button>
</div>
</div>
<div className='row'>
<div className='col-6-lg col-12'>
<h3>Applications</h3>
{userContext.user && <ApplicationList apps={userContext.user.apps} />}
</div>
</div>
</div>;
};
const CreateUserField = ({ className }: { className: string }) => {
const [link, setLink] = useState<string | null>(null);
const getSignupCode = async () => {
const response = await get('/api/register/code');
if (response.status === 200 && response.data) {
const link = `${window.location.origin}/register?code=${response.data.code}`;
setLink(link);
}
};
const copyToClipboard: React.MouseEventHandler = (event) => {
const element = event.target as HTMLElement;
const { parentElement } = element;
navigator.clipboard.writeText(element.innerText);
if (parentElement)
(parentElement.childNodes[parentElement.childNodes.length - 1] as HTMLElement).style.visibility = "visible";
};
const closeToolTip: React.MouseEventHandler = (event) => {
(event.target as HTMLElement).style.visibility = "hidden";
};
// TODO: Finish this
return <div className={className}>
<h4>One-Click Sign-Up</h4>
{link ?
<div className="registerCodeWrapper tooltip"><p onClick={copyToClipboard}>{link}</p><span onClick={closeToolTip} className="tooltiptext">Code copied!</span></div> :
<button onClick={getSignupCode} className="button primary is-center">Create sign-up link</button>}
<hr />
<h4>Create User</h4>
<form>
<p>Users will be forced to change the password you set here.</p>
<input placeholder="Username" autoComplete="off" type='text' id='username' />
<input placeholder="Password" autoComplete="off" type='password' id='password' />
</form>
</div>;
};
const Users = () => {
const [users, setUsers] = useState<APIUser[]>([]);
const [roles, updateRoles] = useState<Role[]>([]);
const [page, setPage] = useState(1);
const [pages, setPages] = useState(1);
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
(async () => {
const result = await get('/api/users', { page });
if (result.success && result.data) {
setError(null);
setUsers(result.data.users as APIUser[]);
setPages(result.data.pages);
} else setError(result.message || 'Unknown error');
setLoading(false);
const rolesResponse = await get('/api/roles', { all: true });
if (rolesResponse.success && rolesResponse.data)
updateRoles(rolesResponse.data.roles as Role[]);
})();
}, [page]);
const UserWrapper = () => {
const { id } = useParams();
const user = users.find(u => u.id === id);
if (!user) return <p>Unknown user</p>;
return <User roles={roles} user={user} />;
};
const navigate = useNavigate();
const UserListWrapper = () => {
return <div className="user-list-wrapper row">
<div className={`col-6-lg col-12 ld ${loading && 'loading'}`}>
<h4>All Users</h4>
<Table headerItems={['Username', 'ID']}>
{users.map(user => <TableListEntry
onClick={() => {
navigate(user.id);
}}
key={user.id}
item={user}
itemKeys={['name', 'id']} />)}
</Table>
<PageButtons {...{ page, setPage, pages }} />
</div>
<CreateUserField className="col-6-lg col-12" />
</div>;
};
const ApplicationWrapper = () => {
const { appid } = useParams();
if (!appid) return null;
const userContext = useContext(SelectedUserContext);
const [app, setApp] = useState<App | null>(userContext.user?.apps.find(app => app.id === appid) || null);
useEffect(() => {
(async () => {
if (userContext.user) return;
const result = await get(`/api/applications/${appid}`);
if (result.success)
setApp(result.data as App);
})();
}, [appid]);
if (!app) return <p>Loading...</p>;
return <Application app={app} />;
};
return <div className="user-list">
{error && <p>{error}</p>}
<ErrorBoundary>
<Context>
<Routes>
<Route path='/:id/*' element={<UserWrapper />} />
<Route path='/' element={<UserListWrapper />} />
<Route path='/:id/applications/:appid' element={<ApplicationWrapper />} />
</Routes>
</Context>
</ErrorBoundary>
</div>;
};
else
setError(result.message || 'Unknown error');
setLoading(false);
const rolesResponse = await get('/api/roles', { all: true });
if (rolesResponse.success && rolesResponse.data)
updateRoles(rolesResponse.data.roles as Role[]);
})();
}, [page]);
const UserWrapper = () =>
{
const { id } = useParams();
const user = users.find(u => u.id === id);
if (!user)
return <p>Unknown user</p>;
return <User roles={roles} user={user} />;
};
const navigate = useNavigate();
const UserListWrapper = () =>
{
return <div className="user-list-wrapper row">
<div className={`col-6-lg col-12 ld ${loading && 'loading'}`}>
<h4>All Users</h4>
<Table headerItems={['Username', 'ID']}>
{users.map(user => <TableListEntry
onClick={() =>
{
navigate(user.id);
}}
key={user.id}
item={user}
itemKeys={['name', 'id']} />)}
</Table>
<PageButtons {...{ page, setPage, pages }} />
</div>
<CreateUserField className="col-6-lg col-12" />
</div>;
};
const ApplicationWrapper = () =>
{
const { appid } = useParams();
if (!appid)
return null;
const userContext = useContext(SelectedUserContext);
const [app, setApp] = useState<App | null>(userContext.user?.apps.find(app => app.id === appid) || null);
useEffect(() =>
{
(async () =>
{
if (userContext.user)
return;
const result = await get(`/api/applications/${appid}`);
if (result.success)
setApp(result.data as App);
})();
}, [appid]);
if (!app)
return <p>Loading...</p>;
return <Application app={app} />;
};
return <div className="user-list">
{error && <p>{error}</p>}
<ErrorBoundary>
<Context>
<Routes>
<Route path='/:id/*' element={<UserWrapper />} />
<Route path='/' element={<UserListWrapper />} />
<Route path='/:id/applications/:appid' element={<ApplicationWrapper />} />
</Routes>
</Context>
</ErrorBoundary>
</div>;
};
export default Users;

View File

@ -1,108 +1,122 @@
import React, { useEffect, useRef, useState } from "react";
import { Route, Routes, useNavigate, useParams } from "react-router";
import { Table, TableListEntry } from "../../components/Table";
import ErrorBoundary from "../../util/ErrorBoundary";
import { post, get, del } from "../../util/Util";
import { Application as App } from "../../@types/ApiStructures";
import { Res } from "../../@types/Other";
const Application = ({ app }: {app: App}) => {
const navigate = useNavigate();
const deleteApp = async () => {
// const response =
await del(`/api/user/applications/${app.id}`);
};
return <div>
<button className="button secondary" onClick={() => navigate(-1)}>Back</button>
<h2>{app.name}</h2>
<p>{app.description}</p>
<p>{app.token}</p>
<button onClick={deleteApp}>Delete</button>
</div>;
};
const Applications = () => {
const [applications, setApplications] = useState<App[]>([]);
const [loading, setLoading] = useState(true);
const navigate = useNavigate();
useEffect(() => {
(async () => {
const response = await get('/api/user/applications') as Res;
if (response.status === 200) setApplications(response.data as App[]);
setLoading(false);
})();
}, []);
const descField = useRef<HTMLTextAreaElement>(null);
const nameField = useRef<HTMLInputElement>(null);
const [error, setError] = useState<string | null>(null);
const createApp: React.MouseEventHandler = async (event) => {
event.preventDefault();
const button = event.target as HTMLButtonElement;
if (!nameField.current || !descField.current) return;
const name = nameField.current?.value;
if (!name) return setError('Missing name');
const description = descField.current?.value || null;
nameField.current.value = '';
descField.current.value = '';
button.disabled = true;
const response = await post('/api/user/applications', { name, description });
if (response.status !== 200) setError(response.message || 'Unknown error');
else setApplications((apps) => [...apps, response.data as App]);
button.disabled = false;
};
const Main = () => {
return <div className="row">
<div className={`col ld ${loading && 'loading'}`}>
<h2>Applications</h2>
<Table headerItems={['Name', 'ID']}>
{applications.map(application => <TableListEntry
key={application.id}
onClick={() => navigate(application.id)}
item={application}
itemKeys={['name', 'id']}
/>)}
</Table>
</div>
<div className="col">
<h2>Create Application</h2>
{error && <p>{error}</p>}
<form>
<input ref={nameField} placeholder="Name" type='text' />
<textarea ref={descField} rows={5} placeholder="Describe your application" />
<button onClick={createApp} className="button primary mt-3">Create</button>
</form>
</div>
</div>;
};
const ApplicationWrapper = () => {
const { id } = useParams();
const application = applications.find(app => app.id === id);
if(!application) return <p>Unknown application</p>;
return <Application app={application} />;
};
return <ErrorBoundary>
<Routes>
<Route path="/" element={<Main />} />
<Route path="/:id" element={<ApplicationWrapper />} />
</Routes>
</ErrorBoundary>;
};
import React, { useEffect, useRef, useState } from "react";
import { Route, Routes, useNavigate, useParams } from "react-router";
import { Table, TableListEntry } from "../../components/Table";
import ErrorBoundary from "../../util/ErrorBoundary";
import { post, get, del } from "../../util/Util";
import { Application as App } from "../../@types/ApiStructures";
import { Res } from "../../@types/Other";
const Application = ({ app }: {app: App}) =>
{
const navigate = useNavigate();
const deleteApp = async () =>
{
// const response =
await del(`/api/user/applications/${app.id}`);
};
return <div>
<button className="button secondary" onClick={() => navigate(-1)}>Back</button>
<h2>{app.name}</h2>
<p>{app.description}</p>
<p>{app.token}</p>
<button onClick={deleteApp}>Delete</button>
</div>;
};
const Applications = () =>
{
const [applications, setApplications] = useState<App[]>([]);
const [loading, setLoading] = useState(true);
const navigate = useNavigate();
useEffect(() =>
{
(async () =>
{
const response = await get('/api/user/applications') as Res;
if (response.status === 200)
setApplications(response.data as App[]);
setLoading(false);
})();
}, []);
const descField = useRef<HTMLTextAreaElement>(null);
const nameField = useRef<HTMLInputElement>(null);
const [error, setError] = useState<string | null>(null);
const createApp: React.MouseEventHandler = async (event) =>
{
event.preventDefault();
const button = event.target as HTMLButtonElement;
if (!nameField.current || !descField.current)
return;
const name = nameField.current?.value;
if (!name)
return setError('Missing name');
const description = descField.current?.value || null;
nameField.current.value = '';
descField.current.value = '';
button.disabled = true;
const response = await post('/api/user/applications', { name, description });
if (response.status !== 200)
setError(response.message || 'Unknown error');
else
setApplications((apps) => [...apps, response.data as App]);
button.disabled = false;
};
const Main = () =>
{
return <div className="row">
<div className={`col ld ${loading && 'loading'}`}>
<h2>Applications</h2>
<Table headerItems={['Name', 'ID']}>
{applications.map(application => <TableListEntry
key={application.id}
onClick={() => navigate(application.id)}
item={application}
itemKeys={['name', 'id']}
/>)}
</Table>
</div>
<div className="col">
<h2>Create Application</h2>
{error && <p>{error}</p>}
<form>
<input ref={nameField} placeholder="Name" type='text' />
<textarea ref={descField} rows={5} placeholder="Describe your application" />
<button onClick={createApp} className="button primary mt-3">Create</button>
</form>
</div>
</div>;
};
const ApplicationWrapper = () =>
{
const { id } = useParams();
const application = applications.find(app => app.id === id);
if(!application)
return <p>Unknown application</p>;
return <Application app={application} />;
};
return <ErrorBoundary>
<Routes>
<Route path="/" element={<Main />} />
<Route path="/:id" element={<ApplicationWrapper />} />
</Routes>
</ErrorBoundary>;
};
export default Applications;

View File

@ -1,189 +1,210 @@
import React, { useRef, useState } from "react";
import { capitalise, get, post } from "../../util/Util";
import { useLoginContext } from "../../structures/UserContext";
import { FileSelector } from "../../components/InputElements";
import { ExternalProfile as EP, User } from "../../@types/ApiStructures";
const TwoFactorControls = ({ user }: {user: User}) => {
const [twoFactorError, set2FAError] = useState<string | null>(null);
const [displayInput, setDisplayInput] = useState(false);
const [qr, setQr] = useState<string | null>(null);
const displayQr = async () => {
const response = await get('/api/user/2fa');
if (response.status !== 200) return set2FAError(response.message || 'Uknown error');
setQr(response.message as string);
};
const codeRef = useRef<HTMLInputElement>(null);
const disable2FA: React.MouseEventHandler = async (event) => {
event.preventDefault();
const code = codeRef.current?.value;
if (!code) return;
const response = await post('/api/user/2fa/disable', { code });
if (response.status !== 200) return set2FAError(response.message || 'Unknown error');
};
const submitCode: React.MouseEventHandler = async (event) => {
event.preventDefault();
const code = codeRef.current?.value;
if (!code) return;
const response = await post('/api/user/2fa/verify', { code });
if (response.status !== 200) return set2FAError(response.message || 'Unknown error');
};
let inner = <div>
{qr ?
<div>
<img src={qr} />
<form>
<input placeholder='Authenticator code' ref={codeRef} type='password' />
<button onClick={submitCode} className="button success">Submit</button>
</form>
</div> :
<button onClick={displayQr} className="button primary">Enable 2FA</button>}
</div>;
if (user.twoFactor) inner = <div>
{displayInput ?
<form>
<input placeholder='Authenticator code to disable' ref={codeRef} type='password' />
<button className="button error" onClick={disable2FA}>Submit</button>
</form>
: <button onClick={() => setDisplayInput(true)} className="button error">Disable 2FA</button>}
</div>;
return <div>
{twoFactorError && <p>{twoFactorError}</p>}
{inner}
</div>;
};
const ExternalProfile = ({ profile }: {profile: EP}) => {
return <div>
<b>{capitalise(profile.provider)}</b>
<p className="m-0">Username: {profile.username}</p>
<p className="m-0">ID: {profile.id}</p>
</div>;
};
const ThirdPartyConnections = ({ user }: {user: User}) => {
const { externalProfiles } = user;
return <div>
{externalProfiles.map(profile => <ExternalProfile key={profile.id} profile={profile} />)}
</div>;
};
const Profile = () => {
const user = useLoginContext()[0] as User;
const [file, setFile] = useState<File | null>(null);
const [error, setError] = useState<string | null>(null);
const usernameRef = useRef<HTMLInputElement>(null);
const displayNameRef = useRef<HTMLInputElement>(null);
const currPassRef = useRef<HTMLInputElement>(null);
const newPassRef = useRef<HTMLInputElement>(null);
const newPassRepeatRef = useRef<HTMLInputElement>(null);
const submit: React.MouseEventHandler = async (event) => {
if (!file) return;
const button = event.target as HTMLButtonElement;
button.disabled = true;
const body = new FormData();
body.append('file', file, file.name);
const response = await post('/api/user/avatar', body, {
headers: null
});
if (!response.success) setError(response.message || 'Unknown error');
else setFile(null);
button.disabled = false;
};
const updateSettings: React.MouseEventHandler = async (event) => {
event.preventDefault();
const button = event.target as HTMLButtonElement;
const username = usernameRef.current?.value;
const displayName = displayNameRef.current?.value;
const currentPassword = currPassRef.current?.value;
const newPassword = newPassRef.current?.value;
const newPasswordRepeat = newPassRepeatRef.current?.value;
if (!currentPassword) return setError('Missing password');
button.disabled = true;
const data: {username?: string, displayName?: string, password?: string, newPassword?: string} = { username, displayName, password: currentPassword };
if (currentPassword && newPassword && newPasswordRepeat) {
if (newPassword !== newPasswordRepeat) {
button.disabled = false;
return setError('Passwords do not match');
}
data.newPassword = newPassword;
}
const response = await post('/api/user/settings', data);
console.log(response);
button.disabled = false;
};
return <div className="row">
<div className="col-6-lg col-12">
<h3>Profile</h3>
<div className="dir-row pfp-wrapper">
<div className="w-auto f-s0">
<p><b>Profile Picture</b></p>
<img draggable={false} width={256} height={256} src={`/api/users/${user.id}/avatar`} />
</div>
<div className="f-g f-b0">
<p><b>Change Profile Picture</b></p>
<form className="f-g f-b0">
<FileSelector cb={setFile} />
<button type='button' onClick={submit} className="button primary mt-3">Submit</button>
</form>
</div>
</div>
<h4 className="mt-5">Third party connections</h4>
<ThirdPartyConnections user={user} />
</div>
<div className="col-6-lg col-12">
<h3>Settings</h3>
<p><b>ID:</b> {user.id}</p>
<p>{error}</p>
<form>
<label>Username</label>
<input ref={usernameRef} id='username' defaultValue={user.name} type='text' autoComplete="off" />
<label>Display Name</label>
<input ref={displayNameRef} id='displayName' defaultValue={user.displayName || ''} type='text' autoComplete="off" />
<label>Change password</label>
<input ref={currPassRef} id='currentPassword' placeholder="Current password" type='password' autoComplete="off" />
<input ref={newPassRef} id='newPassword' placeholder="New password" type='password' autoComplete="off" />
<input ref={newPassRepeatRef} id='newPasswordRepeat' placeholder="Repeat new password" type='password' autoComplete="off" />
<button onClick={updateSettings} className="button primary">Save</button>
</form>
<p className="mb-0 mt-5"><b>Two Factor:</b> {user.twoFactor ? 'enabled' : 'disabled'}</p>
<TwoFactorControls user={user} />
</div>
</div>;
};
import React, { useRef, useState } from "react";
import { capitalise, get, post } from "../../util/Util";
import { useLoginContext } from "../../structures/UserContext";
import { FileSelector } from "../../components/InputElements";
import { ExternalProfile as EP, User } from "../../@types/ApiStructures";
const TwoFactorControls = ({ user }: {user: User}) =>
{
const [twoFactorError, set2FAError] = useState<string | null>(null);
const [displayInput, setDisplayInput] = useState(false);
const [qr, setQr] = useState<string | null>(null);
const displayQr = async () =>
{
const response = await get('/api/user/2fa');
if (response.status !== 200)
return set2FAError(response.message || 'Uknown error');
setQr(response.message as string);
};
const codeRef = useRef<HTMLInputElement>(null);
const disable2FA: React.MouseEventHandler = async (event) =>
{
event.preventDefault();
const code = codeRef.current?.value;
if (!code)
return;
const response = await post('/api/user/2fa/disable', { code });
if (response.status !== 200)
return set2FAError(response.message || 'Unknown error');
};
const submitCode: React.MouseEventHandler = async (event) =>
{
event.preventDefault();
const code = codeRef.current?.value;
if (!code)
return;
const response = await post('/api/user/2fa/verify', { code });
if (response.status !== 200)
return set2FAError(response.message || 'Unknown error');
};
let inner = <div>
{qr ?
<div>
<img src={qr} />
<form>
<input placeholder='Authenticator code' ref={codeRef} type='password' />
<button onClick={submitCode} className="button success">Submit</button>
</form>
</div> :
<button onClick={displayQr} className="button primary">Enable 2FA</button>}
</div>;
if (user.twoFactor)
inner = <div>
{displayInput ?
<form>
<input placeholder='Authenticator code to disable' ref={codeRef} type='password' />
<button className="button error" onClick={disable2FA}>Submit</button>
</form>
: <button onClick={() => setDisplayInput(true)} className="button error">Disable 2FA</button>}
</div>;
return <div>
{twoFactorError && <p>{twoFactorError}</p>}
{inner}
</div>;
};
const ExternalProfile = ({ profile }: {profile: EP}) =>
{
return <div>
<b>{capitalise(profile.provider)}</b>
<p className="m-0">Username: {profile.username}</p>
<p className="m-0">ID: {profile.id}</p>
</div>;
};
const ThirdPartyConnections = ({ user }: {user: User}) =>
{
const { externalProfiles } = user;
return <div>
{externalProfiles.map(profile => <ExternalProfile key={profile.id} profile={profile} />)}
</div>;
};
const Profile = () =>
{
const user = useLoginContext()[0] as User;
const [file, setFile] = useState<File | null>(null);
const [error, setError] = useState<string | null>(null);
const usernameRef = useRef<HTMLInputElement>(null);
const displayNameRef = useRef<HTMLInputElement>(null);
const currPassRef = useRef<HTMLInputElement>(null);
const newPassRef = useRef<HTMLInputElement>(null);
const newPassRepeatRef = useRef<HTMLInputElement>(null);
const submit: React.MouseEventHandler = async (event) =>
{
if (!file)
return;
const button = event.target as HTMLButtonElement;
button.disabled = true;
const body = new FormData();
body.append('file', file, file.name);
const response = await post('/api/user/avatar', body, {
headers: null
});
if (!response.success)
setError(response.message || 'Unknown error');
else
setFile(null);
button.disabled = false;
};
const updateSettings: React.MouseEventHandler = async (event) =>
{
event.preventDefault();
const button = event.target as HTMLButtonElement;
const username = usernameRef.current?.value;
const displayName = displayNameRef.current?.value;
const currentPassword = currPassRef.current?.value;
const newPassword = newPassRef.current?.value;
const newPasswordRepeat = newPassRepeatRef.current?.value;
if (!currentPassword)
return setError('Missing password');
button.disabled = true;
const data: {username?: string, displayName?: string, password?: string, newPassword?: string} = { username, displayName, password: currentPassword };
if (currentPassword && newPassword && newPasswordRepeat)
{
if (newPassword !== newPasswordRepeat)
{
button.disabled = false;
return setError('Passwords do not match');
}
data.newPassword = newPassword;
}
const response = await post('/api/user/settings', data);
console.log(response);
button.disabled = false;
};
return <div className="row">
<div className="col-6-lg col-12">
<h3>Profile</h3>
<div className="dir-row pfp-wrapper">
<div className="w-auto f-s0">
<p><b>Profile Picture</b></p>
<img draggable={false} width={256} height={256} src={`/api/users/${user.id}/avatar`} />
</div>
<div className="f-g f-b0">
<p><b>Change Profile Picture</b></p>
<form className="f-g f-b0">
<FileSelector cb={setFile} />
<button type='button' onClick={submit} className="button primary mt-3">Submit</button>
</form>
</div>
</div>
<h4 className="mt-5">Third party connections</h4>
<ThirdPartyConnections user={user} />
</div>
<div className="col-6-lg col-12">
<h3>Settings</h3>
<p><b>ID:</b> {user.id}</p>
<p>{error}</p>
<form>
<label>Username</label>
<input ref={usernameRef} id='username' defaultValue={user.name} type='text' autoComplete="off" />
<label>Display Name</label>
<input ref={displayNameRef} id='displayName' defaultValue={user.displayName || ''} type='text' autoComplete="off" />
<label>Change password</label>
<input ref={currPassRef} id='currentPassword' placeholder="Current password" type='password' autoComplete="off" />
<input ref={newPassRef} id='newPassword' placeholder="New password" type='password' autoComplete="off" />
<input ref={newPassRepeatRef} id='newPasswordRepeat' placeholder="Repeat new password" type='password' autoComplete="off" />
<button onClick={updateSettings} className="button primary">Save</button>
</form>
<p className="mb-0 mt-5"><b>Two Factor:</b> {user.twoFactor ? 'enabled' : 'disabled'}</p>
<TwoFactorControls user={user} />
</div>
</div>;
};
export default Profile;

View File

@ -1,29 +1,30 @@
import React from 'react';
import { NavLink as BaseNavLink } from 'react-router-dom';
type NavLinkOptions = {
activeClassName?: string,
activeStyle?: object,
children?: React.ReactNode,
className?: string,
style?: object,
to: string,
onClick?: React.MouseEventHandler
}
// eslint-disable-next-line react/display-name
const NavLink = React.forwardRef(({ activeClassName, activeStyle, ...props }: NavLinkOptions, ref: React.ForwardedRef<HTMLAnchorElement>) => {
return <BaseNavLink
ref={ref}
{...props}
className={({ isActive }) => [props.className, isActive ? activeClassName : null].filter(Boolean).join(' ')}
style={({ isActive }) => ({
...props.style,
...isActive ? activeStyle : null
})}>
{props?.children}
</BaseNavLink>;
});
import React from 'react';
import { NavLink as BaseNavLink } from 'react-router-dom';
type NavLinkOptions = {
activeClassName?: string,
activeStyle?: object,
children?: React.ReactNode,
className?: string,
style?: object,
to: string,
onClick?: React.MouseEventHandler
}
// eslint-disable-next-line react/display-name
const NavLink = React.forwardRef(({ activeClassName, activeStyle, ...props }: NavLinkOptions, ref: React.ForwardedRef<HTMLAnchorElement>) =>
{
return <BaseNavLink
ref={ref}
{...props}
className={({ isActive }) => [props.className, isActive ? activeClassName : null].filter(Boolean).join(' ')}
style={({ isActive }) => ({
...props.style,
...isActive ? activeStyle : null
})}>
{props?.children}
</BaseNavLink>;
});
export default NavLink;

View File

@ -1,10 +1,12 @@
import React from 'react';
import { Navigate, useLocation } from "react-router-dom";
import { getUser } from "../util/Util";
export const PrivateRoute = ({ children }: {children: JSX.Element}) => {
const user = getUser();
const location = useLocation();
if (!user) return <Navigate to='/login' replace state={{ from: location }} />;
return children;
import React from 'react';
import { Navigate, useLocation } from "react-router-dom";
import { getUser } from "../util/Util";
export const PrivateRoute = ({ children }: {children: JSX.Element}) =>
{
const user = getUser();
const location = useLocation();
if (!user)
return <Navigate to='/login' replace state={{ from: location }} />;
return children;
};

View File

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

View File

@ -1,31 +1,35 @@
import React, { useContext, useState } from 'react';
import { getUser } from '../util/Util';
import {User} from '../@types/ApiStructures';
type UpdateFunc = ((user?: User | null) => void)
const LoginContext = React.createContext<User | null>(null);
const LoginUpdateContext = React.createContext<UpdateFunc>(() => { /* */ });
// Hook
export const useLoginContext = (): [User | null, UpdateFunc] => {
return [useContext(LoginContext), useContext(LoginUpdateContext)];
};
// Component
export const UserContext = ({ children }: {children: React.ReactNode}) => {
const [user, setLoginState] = useState(getUser());
const updateLoginState = () => {
setLoginState(getUser());
};
return (
<LoginContext.Provider value={user}>
<LoginUpdateContext.Provider value={updateLoginState}>
{children}
</LoginUpdateContext.Provider>
</LoginContext.Provider>
);
import React, { useContext, useState } from 'react';
import { getUser } from '../util/Util';
import {User} from '../@types/ApiStructures';
type UpdateFunc = ((user?: User | null) => void)
const LoginContext = React.createContext<User | null>(null);
const LoginUpdateContext = React.createContext<UpdateFunc>(() =>
{ /* */ });
// Hook
export const useLoginContext = (): [User | null, UpdateFunc] =>
{
return [useContext(LoginContext), useContext(LoginUpdateContext)];
};
// Component
export const UserContext = ({ children }: {children: React.ReactNode}) =>
{
const [user, setLoginState] = useState(getUser());
const updateLoginState = () =>
{
setLoginState(getUser());
};
return (
<LoginContext.Provider value={user}>
<LoginUpdateContext.Provider value={updateLoginState}>
{children}
</LoginUpdateContext.Provider>
</LoginContext.Provider>
);
};

View File

@ -1,41 +1,47 @@
import React, { useEffect, useRef } from "react";
// Listens for mouse clicks outside of the wrapped element
const alerter = (ref: React.RefObject<HTMLElement>, callback: () => void) => {
useEffect(() => {
const listener = (event: MouseEvent) => {
if (ref.current && !ref.current.contains(event.target as Node)) {
return callback();
}
};
document.addEventListener('mousedown', listener);
return () => {
document.removeEventListener('mousedown', listener);
};
}, [ref]);
};
/**
* Component wrapper to enable listening for clicks outside of the given component
*
* @param {{children: React.ReactNode, callback: () => void}} { children, callback }
* @return {*}
*/
const ClickDetector = ({ children, callback }: {children: React.ReactNode, callback: () => void}) => {
const wrapperRef = useRef(null);
alerter(wrapperRef, callback);
return (
<div className='click-detector' ref={wrapperRef}>
{children}
</div>
);
};
import React, { useEffect, useRef } from "react";
// Listens for mouse clicks outside of the wrapped element
const alerter = (ref: React.RefObject<HTMLElement>, callback: () => void) =>
{
useEffect(() =>
{
const listener = (event: MouseEvent) =>
{
if (ref.current && !ref.current.contains(event.target as Node))
{
return callback();
}
};
document.addEventListener('mousedown', listener);
return () =>
{
document.removeEventListener('mousedown', listener);
};
}, [ref]);
};
/**
* Component wrapper to enable listening for clicks outside of the given component
*
* @param {{children: React.ReactNode, callback: () => void}} { children, callback }
* @return {*}
*/
const ClickDetector = ({ children, callback }: {children: React.ReactNode, callback: () => void}) =>
{
const wrapperRef = useRef(null);
alerter(wrapperRef, callback);
return (
<div className='click-detector' ref={wrapperRef}>
{children}
</div>
);
};
export default ClickDetector;

View File

@ -1,34 +1,39 @@
import React from "react";
type BoundaryProps = {
[key: string]: unknown,
fallback?: React.ReactNode,
children: React.ReactNode
}
type StateProps = {
error: boolean
}
class ErrorBoundary extends React.Component<BoundaryProps, StateProps> {
fallback?: React.ReactNode;
constructor(props: BoundaryProps) {
super(props);
this.state = { error: false };
this.fallback = props.fallback;
}
override componentDidCatch(error: Error, errorInfo: unknown) {
this.setState({error: true});
console.error(error, errorInfo);
}
override render() {
if (this.state.error) return this.fallback || <h1>Something went wrong :/</h1>;
return this.props.children;
}
}
import React from "react";
type BoundaryProps = {
[key: string]: unknown,
fallback?: React.ReactNode,
children: React.ReactNode
}
type StateProps = {
error: boolean
}
class ErrorBoundary extends React.Component<BoundaryProps, StateProps>
{
fallback?: React.ReactNode;
constructor(props: BoundaryProps)
{
super(props);
this.state = { error: false };
this.fallback = props.fallback;
}
override componentDidCatch(error: Error, errorInfo: unknown)
{
this.setState({error: true});
console.error(error, errorInfo);
}
override render()
{
if (this.state.error)
return this.fallback || <h1>Something went wrong :/</h1>;
return this.props.children;
}
}
export default ErrorBoundary;

View File

@ -1,11 +1,14 @@
import React, { useRef } from "react";
import { Permissions as Perms } from "../@types/ApiStructures";
export const Permission = ({ name, value, chain, updatePerms }: {name: string, value: number | Perms, chain: string, updatePerms: (chain: string, perm: string) => void}) => {
export const Permission = ({ name, value, chain, updatePerms }: {name: string, value: number | Perms, chain: string, updatePerms: (chain: string, perm: string) => void}) =>
{
const inputRef = useRef<HTMLInputElement>(null);
const onChange = () => {
const onChange = () =>
{
const val = inputRef.current?.value || null;
if (val === null) return;
if (val === null)
return;
updatePerms(chain, val);
};
@ -15,13 +18,17 @@ export const Permission = ({ name, value, chain, updatePerms }: {name: string, v
</li>;
};
export const PermissionGroup = ({ name, value, chain, updatePerms }: {name: string, value: number | Perms, chain: string, updatePerms: (chain: string, perm: string) => void}) => {
export const PermissionGroup = ({ name, value, chain, updatePerms }: {name: string, value: number | Perms, chain: string, updatePerms: (chain: string, perm: string) => void}) =>
{
const elements = [];
for (const [perm, val] of Object.entries(value)) {
for (const [perm, val] of Object.entries(value))
{
const props = { key: perm, name: perm, value: val, updatePerms, chain: `${chain}:${perm}` };
if(typeof val ==='object') elements.push(<PermissionGroup {...props} />);
else elements.push(<Permission {...props} />);
if(typeof val ==='object')
elements.push(<PermissionGroup {...props} />);
else
elements.push(<Permission {...props} />);
}
return <li>
<div className="groupName">
@ -33,39 +40,48 @@ export const PermissionGroup = ({ name, value, chain, updatePerms }: {name: stri
</li>;
};
export const Permissions = ({ perms, onUpdate }: { perms: Perms, onUpdate: (perms: Perms) => void }) => {
export const Permissions = ({ perms, onUpdate }: { perms: Perms, onUpdate: (perms: Perms) => void }) =>
{
const updatePerms = (chain: string, raw: string) => {
const updatePerms = (chain: string, raw: string) =>
{
const value = parseInt(raw);
if (isNaN(value)) return;
if (isNaN(value))
return;
let selected = perms;
const keys = chain.split(':');
for (const key of keys) {
if (key === keys[keys.length - 1]) selected[key] = value;
else selected = selected[key] as Perms;
for (const key of keys)
{
if (key === keys[keys.length - 1])
selected[key] = value;
else
selected = selected[key] as Perms;
}
onUpdate(perms);
};
const elements = [];
const keys = Object.keys(perms);
for (const perm of keys) {
for (const perm of keys)
{
const props = { key: perm, name: perm, value: perms[perm], chain: perm, updatePerms };
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;
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} />);
}

View File

@ -1,38 +1,41 @@
import React, {Fragment} from "react";
import { RateLimit as RL, RateLimits as RLs } from "../@types/ApiStructures";
const RateLimit = ({route, limit}: {route: string, limit: RL}) => {
return <Fragment>
<p><b>{route}</b></p>
<label>Limit</label>
<input min={0} defaultValue={limit.limit} type='number' />
<label>Time</label>
<input min={0} defaultValue={limit.time} type='number' />
<label>Enabled</label>
<div className="check-box">
<input defaultChecked={!limit.disabled} type='checkbox' />
</div>
</Fragment>;
};
export const RateLimits = ({ rateLimits }: {rateLimits: RLs}) => {
const routes = Object.keys(rateLimits);
const elements = routes.map((route, index) => {
return <div key={index} className="card">
<RateLimit {...{route, limit:rateLimits[route], index}} />
</div>;
});
return <div className='col-6-lg col-12'>
<h2>Rate Limits</h2>
<div className="flex flex-wrap">
{elements}
</div>
<code>
{JSON.stringify(rateLimits, null, 4)}
</code>
</div>;
import React, {Fragment} from "react";
import { RateLimit as RL, RateLimits as RLs } from "../@types/ApiStructures";
const RateLimit = ({route, limit}: {route: string, limit: RL}) =>
{
return <Fragment>
<p><b>{route}</b></p>
<label>Limit</label>
<input min={0} defaultValue={limit.limit} type='number' />
<label>Time</label>
<input min={0} defaultValue={limit.time} type='number' />
<label>Enabled</label>
<div className="check-box">
<input defaultChecked={!limit.disabled} type='checkbox' />
</div>
</Fragment>;
};
export const RateLimits = ({ rateLimits }: {rateLimits: RLs}) =>
{
const routes = Object.keys(rateLimits);
const elements = routes.map((route, index) =>
{
return <div key={index} className="card">
<RateLimit {...{route, limit:rateLimits[route], index}} />
</div>;
});
return <div className='col-6-lg col-12'>
<h2>Rate Limits</h2>
<div className="flex flex-wrap">
{elements}
</div>
<code>
{JSON.stringify(rateLimits, null, 4)}
</code>
</div>;
};