Skip to content

Commit

Permalink
wip: bunch of small random tasks
Browse files Browse the repository at this point in the history
  • Loading branch information
tabarra committed Dec 29, 2023
1 parent af2d9b0 commit d71c9e3
Show file tree
Hide file tree
Showing 28 changed files with 249 additions and 213 deletions.
42 changes: 40 additions & 2 deletions core/components/WebServer/middlewares/ctxUtilsMw.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ export type CtxTxUtils = {
render: (view: string, data?: { headerTitle?: string, [key: string]: any }) => Promise<void>;
error: (httpStatus?: number, message?: string) => void;
serveReactIndex: () => Promise<void>;
legacyNavigateToPage: (href: string) => void;
};
}

Expand Down Expand Up @@ -70,6 +71,36 @@ const RESOURCE_PATH = 'nui://monitor/web/public/';
const displayFxserverVersionPrefix = convars.isZapHosting && '/ZAP' || convars.isPterodactyl && '/Ptero' || '';
const displayFxserverVersion = `${txEnv.fxServerVersion}${displayFxserverVersionPrefix}`;

const legaciNavigateHtmlTemplate = `<style>
body {
margin: 0;
}
.notice {
font-family: sans-serif;
font-size: 1.5em;
text-align: center;
background-color: #222326;
color: #F7F7F8;
padding: 2em;
border: 1px solid #333539;
border-radius: 0.5em;
}
.notice a {
color: #F00A53;
}
</style>
<p class="notice">
Redirecting to <a href="{{href}}" target="_parent">{{href}}</a>...
</p>
<script>
// Notify parent window that auth failed
window.parent.postMessage({ type: 'navigateToPage', href: '{{href}}'});
// If parent redirect didn't work, redirect here
setTimeout(function() {
window.parent.location.href = '{{href}}';
}, 2000);
</script>`


/**
* Loads re-usable base templates
Expand Down Expand Up @@ -164,11 +195,11 @@ export default async function ctxUtilsMw(ctx: CtxWithVars, next: Next) {
//Setting up legacy theme
let legacyTheme = '';
const themeCookie = ctx.cookies.get('txAdmin-theme');
if(!themeCookie || themeCookie === 'dark' || !isWebInterface){
if (!themeCookie || themeCookie === 'dark' || !isWebInterface) {
legacyTheme = 'theme--dark';
} else {
const selectorTheme = tmpCustomThemes.find((theme) => theme.name === themeCookie);
if(selectorTheme?.isDark){
if (selectorTheme?.isDark) {
legacyTheme = 'theme--dark';
}
}
Expand Down Expand Up @@ -211,6 +242,12 @@ export default async function ctxUtilsMw(ctx: CtxWithVars, next: Next) {
};
};

//Legacy page util to navigate parent (react) to some page
const legacyNavigateToPage = (href: string) => {
ctx.body = legaciNavigateHtmlTemplate.replace(/{{href}}/g, href);
ctx.type = 'text/html';
}

const serveReactIndex = async () => {
//FIXME: no cache, even in prod mode
ctx.body = await getReactIndex(ctx);
Expand All @@ -222,6 +259,7 @@ export default async function ctxUtilsMw(ctx: CtxWithVars, next: Next) {
render: renderUtil,
error: errorUtil,
serveReactIndex,
legacyNavigateToPage,
};
ctx.send = <T = string | object>(data: T) => {
ctx.body = data;
Expand Down
1 change: 1 addition & 0 deletions core/components/WebServer/middlewares/sessionMws.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ export const koaSessMw = (cookieName: string, store: SessionMemoryStorage) => {
path: '/',
maxAge: store.maxAgeMs,
httpOnly: true,
sameSite: 'lax',
secure: false,
overwrite: true,
signed: false,
Expand Down
4 changes: 2 additions & 2 deletions core/webroutes/dashboard.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@ const console = consoleFactory(modulename);
export default async function Dashboard(ctx) {
// Check if the deployer is running or setup is pending
if (globals.deployer !== null) {
return ctx.response.redirect('/deployer');
return ctx.utils.legacyNavigateToPage('/server/deployer');
}
if (!globals.fxRunner.config.serverDataPath || !globals.fxRunner.config.cfgPath) {
return ctx.response.redirect('/setup');
return ctx.utils.legacyNavigateToPage('/server/setup');
}

//Shortcut function
Expand Down
6 changes: 4 additions & 2 deletions core/webroutes/deployer/stepper.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,10 @@ export default async function DeployerStepper(ctx) {

//Check if this is the correct state for the deployer
if (globals.deployer == null) {
const redirPath = (!globals.fxRunner.config.cfgPath || !globals.fxRunner.config.serverDataPath) ? '/setup' : '/';
return ctx.response.redirect(redirPath);
const redirPath = (!globals.fxRunner.config.cfgPath || !globals.fxRunner.config.serverDataPath)
? '/server/setup'
: '/';
return ctx.utils.legacyNavigateToPage(redirPath);
}

//Prepare Output
Expand Down
18 changes: 2 additions & 16 deletions core/webroutes/player/modal.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const modulename = 'WebServer:PlayerModal';
import dateFormat from 'dateformat';
import playerResolver from '@core/playerLogic/playerResolver';
import { PlayerHistoryItem, PlayerModalResp, PlayerModalPlayerData, PlayerModalMeta } from '@shared/playerApiTypes';
import { PlayerHistoryItem, PlayerModalResp, PlayerModalPlayerData } from '@shared/playerApiTypes';
import { DatabaseActionType } from '@core/components/PlayerDatabase/databaseTypes';
import { ServerPlayer } from '@core/playerLogic/playerClasses';
import consoleFactory from '@extras/console';
Expand Down Expand Up @@ -43,20 +43,6 @@ export default async function PlayerModal(ctx: AuthedCtx) {
const { mutex, netid, license } = ctx.query;
const sendTypedResp = (data: PlayerModalResp) => ctx.send(data);

//Prepping meta fields
const tsNow = now();
const metaFields: PlayerModalMeta = {
//FIXME: this should not come from the route itself, but for now it is required by the web frontend
tmpPerms: {
message: ctx.admin.hasPermission('players.message'),
whitelist: ctx.admin.hasPermission('players.whitelist'),
warn: ctx.admin.hasPermission('players.warn'),
kick: ctx.admin.hasPermission('players.kick'),
ban: ctx.admin.hasPermission('players.ban'),
},
serverTime: tsNow,
};

//Finding the player
let player;
try {
Expand Down Expand Up @@ -103,7 +89,7 @@ export default async function PlayerModal(ctx: AuthedCtx) {
// console.dir(metaFields);
// console.dir(playerData);
return sendTypedResp({
meta: metaFields,
serverTime: now(),
player: playerData
});
};
4 changes: 2 additions & 2 deletions core/webroutes/setup/get.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@ export default async function SetupGet(ctx) {

// Check if this is the correct state for the setup page
if (globals.deployer !== null) {
return ctx.response.redirect('/deployer');
return ctx.utils.legacyNavigateToPage('/server/deployer');
}
if (globals.fxRunner.config.serverDataPath && globals.fxRunner.config.cfgPath) {
return ctx.response.redirect('/');
return ctx.utils.legacyNavigateToPage('/');
}

const globalConfig = globals.configVault.getScopedStructure('global');
Expand Down
15 changes: 7 additions & 8 deletions docs/dev_notes.md
Original file line number Diff line number Diff line change
Expand Up @@ -193,8 +193,8 @@ setTimeout(() => {
- [x] when logging out, create an effect to close all sheets and dialogs
- [x] disable menu links based on permissions
- [x] flow to refresh the permissions on the client side
- [ ][2d] full setup flow (legacy)
- [ ][1d] full deployer flow (legacy)
- [x][2d] full setup flow (legacy)
- [x][1d] full deployer flow (legacy)
- [ ][1d] add the new logos to shell+auth pages
> BETA RELEASE
Expand All @@ -211,14 +211,13 @@ setTimeout(() => {
- [ ][2h] fine tune `panel/vite.config.ts`

Quickies
- [ ] mudar todos os cfx.response.redirect das rotas de dashboard, setup, deployer e talvez mais alguma que faça redirect quando o sv não está configurado
- [ ] ver se da pra melhorar o visual da setup e deployer, o upelo menos deixar mais largo
- [ ] move the socket.io stuff from mainshell to a dedicated component child of mainshell
- [ ] fix the console bg on light mode
- [x] fix all legacy cfx.response.redirect (dashboard, setup, deployer, maybe more)
- [x] move the socket.io stuff from mainshell to a dedicated component child of mainshell
- [x] disable testing page in prod build
- [x] check if strict mode is indeed disabled in prod build
- [ ] fix the console bg on light mode + command input
- [ ] commit the fixes for the player ids and god mode issues
- [ ] fix the tsc build
- [ ] disable testing page in prod build
- [ ] check if strict mode is indeed disabled in prod build
> BETA RELEASE
- [ ] do i need to add a input type hidden with the username in the add master and account modal so vaults can save it both?
Expand Down
4 changes: 2 additions & 2 deletions nui/src/components/MainPage/MenuListItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ export const MenuListItem: React.FC<MenuListItemProps> = memo(

useEffect(() => {
if (selected && divRef) {
divRef.current.scrollIntoView({
divRef.current?.scrollIntoView({
behavior: "smooth",
block: "nearest",
inline: "start",
Expand Down Expand Up @@ -176,7 +176,7 @@ export const MenuListItemMulti: React.FC<MenuListItemMultiProps> = memo(

useEffect(() => {
if (selected && divRef) {
divRef.current.scrollIntoView({
divRef.current?.scrollIntoView({
behavior: "smooth",
block: "nearest",
inline: "start",
Expand Down
22 changes: 13 additions & 9 deletions nui/src/components/PlayerModal/Tabs/DialogHistoryView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ import { useSnackbar } from "notistack";
import { fetchWebPipe } from "@nui/src/utils/fetchWebPipe";
import { GenericApiErrorResp, GenericApiResp } from "@shared/genericApiTypes";
import { ButtonXS } from "../../misc/ButtonXS";
import { tsToLocaleDateTime } from "@nui/src/utils/miscUtils";
import { tsToLocaleDateTime, userHasPerm } from "@nui/src/utils/miscUtils";
import { usePermissionsValue } from "@nui/src/state/permissions.state";

// TODO: Make the styling on this nicer
const NoHistoryBox = () => (
Expand Down Expand Up @@ -73,11 +74,11 @@ const ActionCard: React.FC<ActionCardProps> = ({
footerNote =
action.exp < serverTime
? t("nui_menu.player_modal.history.expired_at", {
date: expirationDate,
})
date: expirationDate,
})
: t("nui_menu.player_modal.history.expires_at", {
date: expirationDate,
});
date: expirationDate,
});
}

return (
Expand Down Expand Up @@ -134,10 +135,10 @@ const DialogHistoryView: React.FC = () => {
const { enqueueSnackbar } = useSnackbar();
const playerDetails = usePlayerDetailsValue();
const forceRefresh = useForcePlayerRefresh();
const userPerms = usePermissionsValue();
const t = useTranslate();
if ("error" in playerDetails) return <DialogLoadError />;

const meta = playerDetails.meta;
//slice is required to clone the array
const playerActionHistory = playerDetails.player.actionHistory
.slice()
Expand Down Expand Up @@ -168,6 +169,9 @@ const DialogHistoryView: React.FC = () => {
}
};

const hasWarnPerm = userHasPerm('players.warn', userPerms);
const hasBanPerm = userHasPerm('players.ban', userPerms);

return (
<Box p={2} height="100%" display="flex" flexDirection="column">
<Typography variant="h6" style={{ paddingBottom: 5 }}>
Expand All @@ -181,9 +185,9 @@ const DialogHistoryView: React.FC = () => {
<ActionCard
key={action.id}
action={action}
permsDisableWarn={!meta.tmpPerms.warn}
permsDisableBan={!meta.tmpPerms.ban}
serverTime={meta.serverTime}
permsDisableWarn={!hasWarnPerm}
permsDisableBan={!hasBanPerm}
serverTime={playerDetails.serverTime}
btnAction={() => {
handleRevoke(action.id);
}}
Expand Down
8 changes: 4 additions & 4 deletions nui/src/components/PlayerModal/Tabs/DialogInfoView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,12 @@ import { DialogLoadError } from "./DialogLoadError";
import { GenericApiErrorResp, GenericApiResp } from "@shared/genericApiTypes";
import humanizeDuration, { Unit } from "humanize-duration";
import { ButtonXS } from "../../misc/ButtonXS";
import { tsToLocaleDate } from "@nui/src/utils/miscUtils";
import { tsToLocaleDate, userHasPerm } from "@nui/src/utils/miscUtils";
import {
PlayerModalTabs,
useSetPlayerModalTab,
} from "@nui/src/state/playerModal.state";
import { usePermissionsValue } from "@nui/src/state/permissions.state";

const DialogInfoView: React.FC = () => {
const [note, setNote] = useState("");
Expand All @@ -32,9 +33,8 @@ const DialogInfoView: React.FC = () => {
const setTab = useSetPlayerModalTab();
const t = useTranslate();
const theme = useTheme();
const userPerms = usePermissionsValue();
if ("error" in playerDetails) return <DialogLoadError />;

const meta = playerDetails.meta;
const player = playerDetails.player;

//Prepare vars
Expand Down Expand Up @@ -146,7 +146,7 @@ const DialogInfoView: React.FC = () => {
color={player.tsWhitelisted ? "error" : "success"}
variant="outlined"
onClick={btnChangeWhitelistStatus as any}
disabled={!meta.tmpPerms.whitelist || !player.license}
disabled={!userHasPerm('players.whitelist', userPerms) || !player.license}
>
{player.tsWhitelisted
? t("nui_menu.player_modal.info.btn_wl_remove")
Expand Down
11 changes: 1 addition & 10 deletions nui/src/utils/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,7 @@ import { PlayerModalSuccess } from "@shared/playerApiTypes";
// export const MockedPlayerDetails: PlayerModalSuccess = {"meta":{"tmpPerms":{"message":true,"whitelist":true,"warn":true,"kick":true,"ban":true},"serverTime":1668030674},"player":{"displayName":"nobody","pureName":"nobody","isRegistered":false,"isConnected":true,"license":null,"ids":[],"actionHistory":[],"netid":101,"sessionTime":1}};

export const MockedPlayerDetails: PlayerModalSuccess = {
"meta": {
"tmpPerms": {
"message": true,
"whitelist": true,
"warn": true,
"kick": true,
"ban": true
},
"serverTime": 1667712061
},
"serverTime": 1667712061,
"player": {
"displayName": "tabby",
"pureName": "tabby",
Expand Down
2 changes: 1 addition & 1 deletion nui/src/utils/fetchNui.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export async function fetchNui<T = any>(
} catch (error) {
if (error.name === 'SyntaxError') {
throw new Error(`JSON error. Maybe the NUI Callback \'${eventName}\' is not registered. This can be caused if the file that registers it has a lua syntax error.`);
}else{
} else {
throw error;
}
}
Expand Down
3 changes: 2 additions & 1 deletion panel/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
"type": "module",
"scripts": {
"dev": "vite --port 40122 --strictPort --host",
"build": "tsc && vite build",
"build": "vite build",
"typecheck": "tsc -p tsconfig.json --noEmit",
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"preview": "vite preview"
},
Expand Down
4 changes: 3 additions & 1 deletion panel/src/global.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { InjectedTxConsts } from '@shared/otherTypes';
type LogoutNoticeMessage = { type: 'logoutNotice' }
type OpenAccountModalMessage = { type: 'openAccountModal' }
type OpenPlayerModalMessage = { type: 'openPlayerModal', ref: PlayerModalRefType }
type navigateToPageMessage = { type: 'navigateToPage', href: string }

export declare global {
interface Window {
Expand All @@ -12,5 +13,6 @@ export declare global {
}
type MessageEventFromIframe = MessageEvent<LogoutNoticeMessage>
| MessageEvent<OpenAccountModalMessage>
| MessageEvent<OpenPlayerModalMessage>;
| MessageEvent<OpenPlayerModalMessage>
| MessageEvent<navigateToPageMessage>;
}
2 changes: 1 addition & 1 deletion panel/src/hooks/useTheme.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { atom, useAtom } from 'jotai';
* Helpers
*/
const setThemeCookieValue = (value: string) => {
document.cookie = `txAdmin-theme=${value};path=/;max-age=31536000;`;
document.cookie = `txAdmin-theme=${value};path=/;SameSite=Lax;max-age=31536000;`;
}


Expand Down

0 comments on commit d71c9e3

Please sign in to comment.