Compare commits

..

2 Commits
v0.0.1 ... main

Author SHA1 Message Date
f8647c50ae fix signup url
All checks were successful
Build and Push Docker Image / Build image (push) Successful in 1m31s
2025-04-09 03:49:17 +03:00
e81b7abd1a added config
Some checks failed
Build and Push Docker Image / Build image (push) Has been cancelled
2025-04-09 02:39:33 +03:00
8 changed files with 856 additions and 812 deletions

View File

@ -1,6 +1,6 @@
FROM node:alpine
FROM node:alpine as builder
EXPOSE 3000
WORKDIR /app
COPY package.json .
@ -9,9 +9,13 @@ COPY tsconfig.json .
RUN npm install
COPY --chmod=111 startup.sh .
COPY public public
COPY src src
ENTRYPOINT [ "/usr/bin/env", "./startup.sh" ]
RUN npm run build
FROM node:alpine
COPY --from=builder /app/build /opt/server
WORKDIR /opt/server
ENTRYPOINT [ "npx", "-y" , "serve", "-s", "/opt/server" ]

1
config.js Normal file
View File

@ -0,0 +1 @@
var API_URL = 'https://games.acooldomain.co'

803
package-lock.json generated

File diff suppressed because it is too large Load Diff

1
public/config.js Normal file
View File

@ -0,0 +1 @@
var API_URL = "http://localhost"

View File

@ -3,6 +3,7 @@
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.svg"/>
<script type="text/javascript" src="%PUBLIC_URL%/config.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta

View File

@ -1,7 +1,7 @@
import { Box, Paper, ThemeProvider, List, ListItem, ListItemButton, ListItemText, SwipeableDrawer, ListItemIcon, IconButton, AppBar, Toolbar, PaletteMode, createTheme, useMediaQuery, useTheme } from "@mui/material";
import React, { Dispatch, ReactNode } from "react";
import { BrowserRouter, Routes, Route, Navigate } from "react-router-dom";
import { ApiWrapper, getDesignTokens, GlobalUserInfo } from "./common";
import { ApiWrapper, getDesignTokens, GlobalUserInfo } from "./common";
import { LoginPage } from "./login";
import ServersBoard from "./servers";
import MenuIcon from '@mui/icons-material/Menu';
@ -118,10 +118,10 @@ export default function App() {
return (
<ColorModeContext.Provider value={colorMode}>
<Box height={'100vh'} width={'100vw'} overflow='clip' maxHeight='-webkit-fill-available'>
<ThemeProvider theme={theme}>
<BrowserRouter>
<ApiWrapper>
<GlobalUserInfo>
<ThemeProvider theme={theme}>
<BrowserRouter>
<ApiWrapper>
<GlobalUserInfo>
<Menu setMode={setMode}>
<Routes>
<Route path='login' element={<LoginPage />} />
@ -133,10 +133,10 @@ export default function App() {
</Routes>
</Menu>
</GlobalUserInfo>
</ApiWrapper>
</BrowserRouter>
</ThemeProvider>
</Box>
</ApiWrapper>
</BrowserRouter>
</ThemeProvider>
</Box>
</ColorModeContext.Provider>
)
}

View File

@ -1,7 +1,7 @@
import axios, { AxiosInstance, AxiosResponse } from "axios";
import React, { Context, Dispatch, ReactNode, createContext, useContext, useState } from "react";
import { useLocation, Navigate } from "react-router-dom";
import Cookies from 'js-cookie'
import Cookies from 'js-cookie';
import { Box, Button, ButtonGroup, ButtonOwnProps, Modal, PaletteMode, Paper, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, TextField } from "@mui/material";
import { Form } from "@rjsf/mui";
import validator from '@rjsf/validator-ajv8';
@ -19,255 +19,255 @@ import { Permission } from "./actions";
import TerminalComponent from "./terminal";
import ReactDOM from "react-dom/client";
export const apiAuthenticatedContext: Context<[boolean, Dispatch<boolean>]> = createContext([false, (value: boolean) => {}] as [boolean, Dispatch<boolean>])
export const apiAuthenticatedContext: Context<[boolean, Dispatch<boolean>]> = createContext([false, (value: boolean) => { }] as [boolean, Dispatch<boolean>])
export const formModalStyle = {
position: 'absolute' as 'absolute',
maxHeight: "90%",
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
width: '70%',
bgcolor: 'background.paper',
overflowY: 'auto',
p: 4,
borderRadius: 3,
position: 'absolute' as 'absolute',
maxHeight: "90%",
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
width: '70%',
bgcolor: 'background.paper',
overflowY: 'auto',
p: 4,
borderRadius: 3,
}
export const terminalModalStyle = {
position: 'absolute' as 'absolute',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
width: '70%',
bgcolor: 'background.paper',
p: 1,
borderRadius: 3,
position: 'absolute' as 'absolute',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
width: '70%',
bgcolor: 'background.paper',
p: 1,
borderRadius: 3,
}
export const getDesignTokens = (mode: PaletteMode) => ({
palette: {
mode,
...(mode === 'light'
? {
// palette values for light mode
primary: blue,
divider: blue[200],
background: {
default: grey[200],
light: grey[100],
},
text: {
primary: grey[900],
secondary: grey[800],
},
}
: {
// palette values for dark mode
primary: grey,
divider: grey[700],
background: {
default: grey[900],
paper: grey[900],
light: grey[700],
},
text: {
primary: '#fff',
secondary: grey[500],
},
}),
},
components: {
MuiTypography: {
defaultProps: {
color: 'text.primary'
}
palette: {
mode,
...(mode === 'light'
? {
// palette values for light mode
primary: blue,
divider: blue[200],
background: {
default: grey[200],
light: grey[100],
},
}
text: {
primary: grey[900],
secondary: grey[800],
},
}
: {
// palette values for dark mode
primary: grey,
divider: grey[700],
background: {
default: grey[900],
paper: grey[900],
light: grey[700],
},
text: {
primary: '#fff',
secondary: grey[500],
},
}),
},
components: {
MuiTypography: {
defaultProps: {
color: 'text.primary'
}
},
}
});
const API_URL = `${process.env.REACT_APP_API_SCHEME}://${process.env.REACT_APP_API_URL}`
const API_URL = (window as any).API_URL
axios.defaults.withCredentials = true
export const api: AxiosInstance = axios.create({
baseURL: API_URL,
withCredentials: true,
baseURL: API_URL,
withCredentials: true,
});
export function ApiWrapper(p: { children: ReactNode}) {
const {children} = p
const token = Cookies.get('auth')
export function ApiWrapper(p: { children: ReactNode }) {
const { children } = p
const token = Cookies.get('auth')
const [apiAuthenticated, setApiAuthenticated] = useState(Boolean(token))
if (!apiAuthenticated) {
Cookies.remove('auth')
}
const path = useLocation()
return (<apiAuthenticatedContext.Provider value={[apiAuthenticated, setApiAuthenticated]}>
{children}
{!apiAuthenticated && (path.pathname !== '/login' && path.pathname !== '/signup') && <Navigate to='/login' />}
</apiAuthenticatedContext.Provider>)
const [apiAuthenticated, setApiAuthenticated] = useState(Boolean(token))
if (!apiAuthenticated) {
Cookies.remove('auth')
}
const path = useLocation()
return (<apiAuthenticatedContext.Provider value={[apiAuthenticated, setApiAuthenticated]}>
{children}
{!apiAuthenticated && (path.pathname !== '/login' && path.pathname !== '/signup') && <Navigate to='/login' />}
</apiAuthenticatedContext.Provider>)
}
export interface ActionInfo {
name: string
requestType: 'post' | 'get' | 'delete' | 'patch'
endpoint: string
args: {}
permissions?: number
response_action?: 'Ignore' | 'Browse' | 'Terminal'
ServerState?: 'on' | 'off'
name: string
requestType: 'post' | 'get' | 'delete' | 'patch'
endpoint: string
args: {}
permissions?: number
response_action?: 'Ignore' | 'Browse' | 'Terminal'
ServerState?: 'on' | 'off'
}
interface Options{
label: string
const: string
}
interface Options {
label: string
const: string
}
export const actionIdentifierContext: Context<string> = createContext('')
function convertNumber(permissions: number): number[]{
var arr: number[] = []
function convertNumber(permissions: number): number[] {
var arr: number[] = []
Object.entries(Permission).forEach(
([key, value]) => {
if (permissions&value){
arr.push(value)
}
}
);
Object.entries(Permission).forEach(
([key, value]) => {
if (permissions & value) {
arr.push(value)
}
}
);
return arr
return arr
}
function CustomField(props: WidgetProps){
const jp = require('jsonpath')
const [options2, setOptions]: [Options[]|null, Dispatch<Options[]>] = useState(null as Options[]|null)
const {schema, registry, options, ...newProps} = props
const {SelectWidget, CheckboxesWidget} = registry.widgets
function CustomField(props: WidgetProps) {
const jp = require('jsonpath')
const [options2, setOptions]: [Options[] | null, Dispatch<Options[]>] = useState(null as Options[] | null)
const { schema, registry, options, ...newProps } = props
const { SelectWidget, CheckboxesWidget } = registry.widgets
if (!schema.fetch_url){
if (!schema.permissions){
return <TextField onChange={(event)=>(props.onChange(event.target.value))} value={props.value} label={props.label}/>
}
return <CheckboxesWidget
{...newProps}
onChange={(event)=>{
props.onChange(event.reduce((partialSum: number, a: number) => (partialSum + a), 0))
}
}
schema={{}}
options={{
if (!schema.fetch_url) {
if (!schema.permissions) {
return <TextField onChange={(event) => (props.onChange(event.target.value))} value={props.value} label={props.label} />
}
return <CheckboxesWidget
{...newProps}
onChange={(event) => {
props.onChange(event.reduce((partialSum: number, a: number) => (partialSum + a), 0))
}
}
schema={{}}
options={{
enumOptions: [
{label: 'Start', value: Permission.Start},
{label: 'Stop', value: Permission.Stop},
{label: 'Browse', value: Permission.Browse},
{label: 'Delete', value: Permission.Delete},
{label: 'Run Command', value: Permission.RunCommand},
{label: 'Create', value: Permission.Create},
{label: 'Admin', value: Permission.Admin},
{label: 'Cloud', value: Permission.Cloud},
]}} registry={registry} value={convertNumber(props.value)} />
}
if (options2 === null){
api.get(schema.fetch_url as string).then((event)=>{
let newOptions: Options[] = []
for (let response of event.data){
newOptions.push({
const: jp.query(response, `$.${schema.fetch_key_path}`).join(' '),
label: jp.query(response, `$.${schema.fetch_display_path}`).join(' '),
})
}
{ label: 'Start', value: Permission.Start },
{ label: 'Stop', value: Permission.Stop },
{ label: 'Browse', value: Permission.Browse },
{ label: 'Delete', value: Permission.Delete },
{ label: 'Run Command', value: Permission.RunCommand },
{ label: 'Create', value: Permission.Create },
{ label: 'Admin', value: Permission.Admin },
{ label: 'Cloud', value: Permission.Cloud },
]
}} registry={registry} value={convertNumber(props.value)} />
}
setOptions(newOptions)
if (options2 === null) {
api.get(schema.fetch_url as string).then((event) => {
let newOptions: Options[] = []
for (let response of event.data) {
newOptions.push({
const: jp.query(response, `$.${schema.fetch_key_path}`).join(' '),
label: jp.query(response, `$.${schema.fetch_display_path}`).join(' '),
})
}
return <SelectWidget {...newProps} schema={{oneOf: options2?options2:[]}} registry={registry} options={{enumOptions: (options2?options2:[]).map((value: Options)=>({label: value.label, value: value.const}))}}/>
}
setOptions(newOptions)
})
}
return <SelectWidget {...newProps} schema={{ oneOf: options2 ? options2 : [] }} registry={registry} options={{ enumOptions: (options2 ? options2 : []).map((value: Options) => ({ label: value.label, value: value.const })) }} />
}
function isUserAllowed(user: User|null, action: ActionInfo): boolean{
if (user === null){
return false
}
const isAdmin = (user.Permissions & Permission.Admin) === Permission.Admin
if (isAdmin){
return true
}
if (!action.permissions){
return true
}
if ((action.permissions & user.Permissions) == action.permissions){
return true
}
function isUserAllowed(user: User | null, action: ActionInfo): boolean {
if (user === null) {
return false
}
const isAdmin = (user.Permissions & Permission.Admin) === Permission.Admin
if (isAdmin) {
return true
}
if (!action.permissions) {
return true
}
if ((action.permissions & user.Permissions) == action.permissions) {
return true
}
return false
}
export function ActionItem(p: { action: ActionInfo, identifierSubstring?: string, sx?: ButtonOwnProps, variant?: any, onClick?: Function }) {
const actionIdentifier: string = useContext(actionIdentifierContext)
const identifierSubstring = (typeof p.identifierSubstring !== 'undefined') ? p.identifierSubstring : ''
const user = useContext(UserInfoContext)
const actionIdentifier: string = useContext(actionIdentifierContext)
const identifierSubstring = (typeof p.identifierSubstring !== 'undefined') ? p.identifierSubstring : ''
const user = useContext(UserInfoContext)
const [form, setForm] = useState(false);
const [terminal, setTerminal] = useState(null as string|null);
const [formData, setFormData]: [RJSFSchema, Dispatch<RJSFSchema>] = useState({})
const url = p.action.endpoint.replaceAll(`{${identifierSubstring}}`, actionIdentifier)
const [form, setForm] = useState(false);
const [terminal, setTerminal] = useState(null as string | null);
const [formData, setFormData]: [RJSFSchema, Dispatch<RJSFSchema>] = useState({})
const url = p.action.endpoint.replaceAll(`{${identifierSubstring}}`, actionIdentifier)
function handleSubmit() {
let promise: Promise<AxiosResponse<any, any>>|null = null
switch (p.action.requestType) {
case 'post': {
promise = api.post(url, formData)
break
}
case 'patch':{
promise = api.patch(url, formData)
break
}
case 'get': {
if (formData){
console.warn('get can get no arguments, dropping')
}
promise = api.get(url)
break
}
case 'delete': {
if (formData){
console.warn('delete can get no arguments, dropping')
}
promise = api.delete(url)
break
}
function handleSubmit() {
let promise: Promise<AxiosResponse<any, any>> | null = null
switch (p.action.requestType) {
case 'post': {
promise = api.post(url, formData)
break
}
case 'patch': {
promise = api.patch(url, formData)
break
}
case 'get': {
if (formData) {
console.warn('get can get no arguments, dropping')
}
switch (p.action.response_action){
case 'Browse':{
if (promise !== null){
promise.then((event)=>{window.open(`https://${event.data}`)})
}
}
promise = api.get(url)
break
}
case 'delete': {
if (formData) {
console.warn('delete can get no arguments, dropping')
}
setForm(false)
setFormData({})
promise = api.delete(url)
break
}
}
function onFormChange(args: IChangeEvent<any, RJSFSchema, any>) {
setFormData(args.formData)
switch (p.action.response_action) {
case 'Browse': {
if (promise !== null) {
promise.then((event) => { window.open(`https://${event.data}`) })
}
}
}
setForm(false)
setFormData({})
}
function createTerminal(websocket: string){
const NewWindow = window.open('', '', 'width=800 height=600')!
NewWindow.document.write(`<!doctype html>
function onFormChange(args: IChangeEvent<any, RJSFSchema, any>) {
setFormData(args.formData)
}
function createTerminal(websocket: string) {
const NewWindow = window.open('', '', 'width=800 height=600')!
NewWindow.document.write(`<!doctype html>
<html>
<head>
<link rel="stylesheet" href="xterm/css/xterm.css" />
@ -329,71 +329,71 @@ export function ActionItem(p: { action: ActionInfo, identifierSubstring?: string
</body>
</html>
`)
NewWindow.onload = () => {
const root = ReactDOM.createRoot(NewWindow.document.getElementById('root') as HTMLElement);
root.render(<TerminalComponent websocket={websocket}/>);
NewWindow.onload = () => {
const root = ReactDOM.createRoot(NewWindow.document.getElementById('root') as HTMLElement);
root.render(<TerminalComponent websocket={websocket} />);
};
}
}
return (<>
<Button variant={p.variant} disabled={!isUserAllowed(user, p.action)} onClick={() => { if (p.onClick) { p.onClick() } p.action.response_action == 'Terminal'?createTerminal(`ws${API_URL.slice("http".length)}${url}`):setForm(true) }} sx={p.sx}>{p.action.name}</Button >
<Modal
onClose={() => { setForm(false); setFormData({}); }}
open={form}
>
<Box sx={{ ...formModalStyle}}>
<Form validator={validator} widgets={{TextWidget: CustomField}} schema={p.action.args} onChange={onFormChange} formData={formData} onSubmit={handleSubmit} />
</Box>
</Modal>
<Modal
onClose={() => { setTerminal(null); }}
open={terminal != null}
>
<Box sx={terminalModalStyle}>
{/* <TerminalComponent websocket={terminal} /> */}
</Box>
</Modal>
</>)
return (<>
<Button variant={p.variant} disabled={!isUserAllowed(user, p.action)} onClick={() => { if (p.onClick) { p.onClick() } p.action.response_action == 'Terminal' ? createTerminal(`ws${API_URL.slice("http".length)}${url}`) : setForm(true) }} sx={p.sx}>{p.action.name}</Button >
<Modal
onClose={() => { setForm(false); setFormData({}); }}
open={form}
>
<Box sx={{ ...formModalStyle }}>
<Form validator={validator} widgets={{ TextWidget: CustomField }} schema={p.action.args} onChange={onFormChange} formData={formData} onSubmit={handleSubmit} />
</Box>
</Modal>
<Modal
onClose={() => { setTerminal(null); }}
open={terminal != null}
>
<Box sx={terminalModalStyle}>
{/* <TerminalComponent websocket={terminal} /> */}
</Box>
</Modal>
</>)
}
export function ActionGroup(p: { actions: ActionInfo[], identifierSubstring?: string, children?: ReactNode}) {
const actionItems: any[] = p.actions.map((action, index, array) => (<ActionItem action={action} identifierSubstring={p.identifierSubstring} /> ))
const [open, setOpen] = React.useState(false);
const anchorRef = React.useRef<HTMLDivElement>(null);
const [selectedIndex, setSelectedIndex] = React.useState(0);
const user = useContext(UserInfoContext)
for (let child of React.Children.toArray(p.children)){
actionItems.push(child)
export function ActionGroup(p: { actions: ActionInfo[], identifierSubstring?: string, children?: ReactNode }) {
const actionItems: any[] = p.actions.map((action, index, array) => (<ActionItem action={action} identifierSubstring={p.identifierSubstring} />))
const [open, setOpen] = React.useState(false);
const anchorRef = React.useRef<HTMLDivElement>(null);
const [selectedIndex, setSelectedIndex] = React.useState(0);
const user = useContext(UserInfoContext)
for (let child of React.Children.toArray(p.children)) {
actionItems.push(child)
}
const handleMenuItemClick = (
event: React.MouseEvent<HTMLLIElement, MouseEvent>,
index: number,
) => {
setSelectedIndex(index);
setOpen(false)
};
const handleToggle = () => {
setOpen((prevOpen) => !prevOpen);
};
const handleClose = (event: Event) => {
if (
anchorRef.current &&
anchorRef.current.contains(event.target as HTMLElement)
) {
return;
}
const handleMenuItemClick = (
event: React.MouseEvent<HTMLLIElement, MouseEvent>,
index: number,
) => {
setSelectedIndex(index);
setOpen(false)
};
const handleToggle = () => {
setOpen((prevOpen) => !prevOpen);
};
const handleClose = (event: Event) => {
if (
anchorRef.current &&
anchorRef.current.contains(event.target as HTMLElement)
) {
return;
}
setOpen(false);
}
return (
<React.Fragment>
<ButtonGroup variant="outlined" ref={anchorRef} aria-label="split button">
{actionItems[selectedIndex]}
<Button
setOpen(false);
}
return (
<React.Fragment>
<ButtonGroup variant="outlined" ref={anchorRef} aria-label="split button">
{actionItems[selectedIndex]}
<Button
size="small"
aria-controls={open ? 'split-button-menu' : undefined}
aria-expanded={open ? 'true' : undefined}
@ -403,87 +403,87 @@ export function ActionGroup(p: { actions: ActionInfo[], identifierSubstring?: st
>
<ArrowDropDownIcon />
</Button>
</ButtonGroup>
<Popper
sx={{
zIndex: 1,
</ButtonGroup>
<Popper
sx={{
zIndex: 1,
}}
open={open}
anchorEl={anchorRef.current}
role={undefined}
transition
disablePortal
>
{({ TransitionProps, placement }) => (
<Grow
{...TransitionProps}
style={{
transformOrigin:
placement === 'bottom' ? 'center top' : 'center bottom',
}}
open={open}
anchorEl={anchorRef.current}
role={undefined}
transition
disablePortal
>
{({ TransitionProps, placement }) => (
<Grow
{...TransitionProps}
style={{
transformOrigin:
placement === 'bottom' ? 'center top' : 'center bottom',
}}
>
<Paper>
<ClickAwayListener onClickAway={handleClose}>
<MenuList id="split-button-menu" autoFocusItem>
{actionItems.map((option, index) => {
return <MenuItem
key={option.props.action.name}
selected={index === selectedIndex}
onClick={(event) => handleMenuItemClick(event, index)}
disabled={!isUserAllowed(user, option.props.action)}
>
{option.props.action.name}
</MenuItem>
}
)
}
</MenuList>
</ClickAwayListener>
</Paper>
</Grow>
)}
</Popper>
</React.Fragment>
);
<Paper>
<ClickAwayListener onClickAway={handleClose}>
<MenuList id="split-button-menu" autoFocusItem>
{actionItems.map((option, index) => {
return <MenuItem
key={option.props.action.name}
selected={index === selectedIndex}
onClick={(event) => handleMenuItemClick(event, index)}
disabled={!isUserAllowed(user, option.props.action)}
>
{option.props.action.name}
</MenuItem>
}
)
}
</MenuList>
</ClickAwayListener>
</Paper>
</Grow>
)}
</Popper>
</React.Fragment>
);
}
export function DataTable(props: { headers: string[], children: ReactNode, actionInfo?: ActionInfo, actionHook?: Function }) {
const { children, headers, actionInfo, actionHook } = props
return <Box padding={4} overflow='clip'>
<TableContainer component={Paper} sx={{maxHeight: '80svh'}}>
<Table stickyHeader>
<TableHead>
<TableRow sx={{ backgroundColor: 'background.light', fontWeight: 'bold' }}>
{headers.map((value, index, array) => (<TableCell sx={{ backgroundColor: 'background.light', fontWeight: 'bold' }}>{value}</TableCell>))}
</TableRow>
</TableHead>
<TableBody>
{children}
</TableBody>
</Table>
</TableContainer>
{(actionInfo && <Box marginTop={2} overflow='clip'>
<ActionItem variant="contained" action={actionInfo} onClick={actionHook} />
</Box>)}
</Box>
const { children, headers, actionInfo, actionHook } = props
return <Box padding={4} overflow='clip'>
<TableContainer component={Paper} sx={{ maxHeight: '80svh' }}>
<Table stickyHeader>
<TableHead>
<TableRow sx={{ backgroundColor: 'background.light', fontWeight: 'bold' }}>
{headers.map((value, index, array) => (<TableCell sx={{ backgroundColor: 'background.light', fontWeight: 'bold' }}>{value}</TableCell>))}
</TableRow>
</TableHead>
<TableBody>
{children}
</TableBody>
</Table>
</TableContainer>
{(actionInfo && <Box marginTop={2} overflow='clip'>
<ActionItem variant="contained" action={actionInfo} onClick={actionHook} />
</Box>)}
</Box>
}
export const UserInfoContext: Context<User|null> = createContext(null as User|null)
export const UserInfoContext: Context<User | null> = createContext(null as User | null)
export function GlobalUserInfo(props: {children: any}){
const [user, setUser]: [User|null, Dispatch<User|null>] = useState(null as User|null)
const [apiAuthenticated, _] = useContext(apiAuthenticatedContext)
export function GlobalUserInfo(props: { children: any }) {
const [user, setUser]: [User | null, Dispatch<User | null>] = useState(null as User | null)
const [apiAuthenticated, _] = useContext(apiAuthenticatedContext)
if (user === null && apiAuthenticated){
api.get('/users/@me').then((event)=>{setUser(event.data)}).catch(()=>{setUser(null)})
}
if (user === null && apiAuthenticated) {
api.get('/users/@me').then((event) => { setUser(event.data) }).catch(() => { setUser(null) })
}
return <UserInfoContext.Provider value={user}>
{props.children}
</UserInfoContext.Provider>
return <UserInfoContext.Provider value={user}>
{props.children}
</UserInfoContext.Provider>
}

View File

@ -6,101 +6,101 @@ import Cookies from 'js-cookie'
import { fetchToken } from "./login";
const signUp = async (username: string, password: string, token: string) => {
try {
const response = await api.post(`/signup?token=${token}`, {
username: username,
password: password,
}, {
});
return response.data.access_token;
} catch (error) {
console.error('Error fetching token:', error);
throw error;
}
try {
const response = await api.post(`/auth/signup?token=${token}`, {
username: username,
password: password,
}, {
});
return response.data.access_token;
} catch (error) {
console.error('Error fetching token:', error);
throw error;
}
};
export function SignupPage(props: {}) {
const [apiAuthenticated, setApiAuthenticated] = useContext(apiAuthenticatedContext)
const [searchParam, setSearchParam] = useSearchParams();
const token = searchParam.get('token');
if (token === null){
return <Navigate to='/' />
const [apiAuthenticated, setApiAuthenticated] = useContext(apiAuthenticatedContext)
const [searchParam, setSearchParam] = useSearchParams();
const token = searchParam.get('token');
if (token === null) {
return <Navigate to='/' />
}
if (apiAuthenticated) {
return <Navigate to='/' />
}
const handleSubmit: FormEventHandler<HTMLFormElement> = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
const data = new FormData(event.currentTarget);
const usernameFormData: FormDataEntryValue | null = data.get('username');
const passwordFormData: FormDataEntryValue | null = data.get('password');
if (usernameFormData === null || passwordFormData === null) {
return
}
if (apiAuthenticated) {
return <Navigate to='/' />
}
const handleSubmit: FormEventHandler<HTMLFormElement> = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
const data = new FormData(event.currentTarget);
const usernameFormData: FormDataEntryValue | null = data.get('username');
const passwordFormData: FormDataEntryValue | null = data.get('password');
if (usernameFormData === null || passwordFormData === null){
return
}
const username: string = usernameFormData.toString();
const password: string = passwordFormData.toString();
const username: string = usernameFormData.toString();
const password: string = passwordFormData.toString();
signUp(username, password, token).then(
() => {
fetchToken(username, password, true).then(
(token) => {
setApiAuthenticated(true)
},
(error) => {
return Promise.reject(error);
}
)
}
signUp(username, password, token).then(
() => {
fetchToken(username, password, true).then(
(token) => {
setApiAuthenticated(true)
},
(error) => {
return Promise.reject(error);
}
)
}
return (
<Container component="main" maxWidth="xs">
<CssBaseline />
<Box
sx={{
marginTop: 8,
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
}}
>
<Typography component="h1" variant="h5">
Sign up
</Typography>
<Box component="form" onSubmit={handleSubmit} noValidate sx={{ mt: 1 }}>
<TextField
margin="normal"
required
fullWidth
id="username"
label="User Name"
name="username"
autoFocus
/>
<TextField
margin="normal"
required
fullWidth
name="password"
label="Password"
type="password"
id="password"
autoComplete="new-password"
/>
<Button
type="submit"
fullWidth
variant="contained"
sx={{ mt: 3, mb: 2 }}
>
Sign Up
</Button>
</Box>
</Box>
</Container>
}
)
}
return (
<Container component="main" maxWidth="xs">
<CssBaseline />
<Box
sx={{
marginTop: 8,
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
}}
>
<Typography component="h1" variant="h5">
Sign up
</Typography>
<Box component="form" onSubmit={handleSubmit} noValidate sx={{ mt: 1 }}>
<TextField
margin="normal"
required
fullWidth
id="username"
label="User Name"
name="username"
autoFocus
/>
<TextField
margin="normal"
required
fullWidth
name="password"
label="Password"
type="password"
id="password"
autoComplete="new-password"
/>
<Button
type="submit"
fullWidth
variant="contained"
sx={{ mt: 3, mb: 2 }}
>
Sign Up
</Button>
</Box>
</Box>
</Container>
)
}