diff --git a/public/css/modals.css b/public/css/modals.css index 7120b61..8b47ca1 100644 --- a/public/css/modals.css +++ b/public/css/modals.css @@ -1,34 +1,35 @@ -.focused-dialog::backdrop { - background-color: rgba(0, 0, 0, .75); -} - -#modal-ban-player { +.modal { padding: 0; background-color: ivory; } -#modal-ban-player > div { - background-color: brown; /* "brown" */ +.modal > div { + background-color: brown; } -#modal-ban-player > div > h2 { +.modal > div > h2 { font-size: 1.25rem; color: white; margin: 0; padding: 0.5rem; } -#modal-ban-player > form { +.modal > form { padding: 1rem; margin: 0; } -#modal-ban-player > form > h3 { +.modal > form > h3 { margin-top: 0; } + +.focused-modal::backdrop { + background-color: rgba(0, 0, 0, .65); +} + #modal-ban-player .modal-ban-player-time-container > br { margin-bottom: 1rem; } #modal-ban-player > form > div:not(:last-child) { margin-bottom: 1rem; } -#modal-ban-player #modal-cancel-ban-btn, -#modal-ban-player #modal-ban-player-btn { - cursor: pointer; + +#modal-change-username .modal-ban-player-time-container { + margin-bottom: 1rem; } \ No newline at end of file diff --git a/src/routes/account/index.ts b/src/routes/account/index.ts index d9047bd..42042af 100644 --- a/src/routes/account/index.ts +++ b/src/routes/account/index.ts @@ -72,6 +72,11 @@ export default async function (app: FastifyInstance) { staffmodlevel: account.staffmodlevel }; + const redirect_uri = req.query.redirectUrl; + if (redirect_uri) { + return res.redirect(redirect_uri); + } + return res.redirect('/account', 302); }); diff --git a/src/routes/create/index.ts b/src/routes/create/index.ts index 7ed9676..89c6f79 100644 --- a/src/routes/create/index.ts +++ b/src/routes/create/index.ts @@ -1,13 +1,9 @@ import bcrypt from 'bcrypt'; -import { - RegExpMatcher, - englishDataset, - englishRecommendedTransformers, -} from 'obscenity'; import { db } from '#/db/query.js'; import { toDisplayName, toSafeName } from '#/jstring/JString.js'; +import { isUsernameExplicit, isUsernameValid } from '#/util/Username.js'; enum CreateStep { USERNAME, @@ -16,26 +12,6 @@ enum CreateStep { FINISH } -const staticBlockedUsernames = [ - // thank you all: - 'Andrew', - 'Paul', - 'Ian', - 'Ash', // always just "mod ash" but put some respect on em! - // and every other mod that contributed to the success and longevity of the game - - // extras that players want to abuse and will surely circumvent :( - 'Admin', - 'Administrator', - 'Mod', - 'Moderator' -]; - -const blockedUsernames = new RegExpMatcher({ - ...englishDataset.build(), - ...englishRecommendedTransformers, -}); - export default function (f: any, opts: any, next: any) { f.get('/', async (req: any, res: any) => { if (typeof req.query.reset !== 'undefined' || typeof req.session.createStep === 'undefined') { @@ -96,21 +72,23 @@ export default function (f: any, opts: any, next: any) { const { createStep } = req.session; const { username, password, password2, terms } = req.body; - if (typeof username !== 'undefined') { - const name = toSafeName(username); + const name = toSafeName(username); - if (name === 'invalid_name' || name.length < 1 || name.length > 12) { + if (typeof username !== 'undefined') { + const nameCheck = isUsernameValid(username); + + if (!nameCheck.success) { req.session.createStep = CreateStep.USERNAME; - req.session.createError = 'You must enter a valid username.'; + req.session.createError = nameCheck.message; delete req.session.createUsername; return res.redirect('/create', 302); } const displayName = toDisplayName(username); - const blocked = blockedUsernames.hasMatch(displayName) || staticBlockedUsernames.includes(displayName); - if (blocked || name.startsWith(' ') || name.endsWith(' ') || name.startsWith('mod_') || name.startsWith('m0d_')) { + const displayNameCheck = isUsernameExplicit(displayName); + if (!displayNameCheck.success) { req.session.createStep = CreateStep.USERNAME; - req.session.createError = 'That username is not available.'; + req.session.createError = displayNameCheck.message; delete req.session.createUsername; return res.redirect('/create', 302); } @@ -155,13 +133,10 @@ export default function (f: any, opts: any, next: any) { return res.redirect('/create', 302); } - const name = toSafeName(username); - - const displayName = toDisplayName(username); - const blocked = blockedUsernames.hasMatch(displayName) || staticBlockedUsernames.includes(displayName); - if (blocked || name.startsWith(' ') || name.endsWith(' ') || name.startsWith('mod_') || name.startsWith('m0d_')) { + const displayNameCheck = isUsernameExplicit(username); + if (!displayNameCheck.success) { req.session.createStep = CreateStep.USERNAME; - req.session.createError = 'That username is not available.'; + req.session.createError = displayNameCheck.message; delete req.session.createUsername; return res.redirect('/create', 302); } diff --git a/src/routes/mod/index.ts b/src/routes/mod/index.ts index 145d0a8..c99f522 100644 --- a/src/routes/mod/index.ts +++ b/src/routes/mod/index.ts @@ -1,8 +1,11 @@ +import fs from 'fs'; + import { FastifyInstance } from 'fastify'; import { db, toDbDate } from '#/db/query.js'; -import { toDisplayName } from '#/jstring/JString.js'; +import { toDisplayName, toSafeName } from '#/jstring/JString.js'; import LoggerEventType from '#/util/LoggerEventType.js'; +import { isUsernameExplicit, isUsernameValid } from '#/util/Username.js'; function toDisplayCoord(coord: number) { const level = (coord >> 28) & 0x3; @@ -34,11 +37,11 @@ const reasons = [ export default async function (app: FastifyInstance) { app.get('/overview/:username', async (req: any, res: any) => { try { - if (!req.session.account || req.session.account.staffmodlevel < 1) { - return res.redirect('/account/login', 302); - } - const { username } = req.params; + + if (!req.session.account || req.session.account.staffmodlevel < 1) { + return res.redirect(`/account/login?redirectUrl=/mod/overview/${username}`, 302); + } const account = await db.selectFrom('account').where('username', '=', username).selectAll().executeTakeFirst(); @@ -73,7 +76,7 @@ export default async function (app: FastifyInstance) { app.get('/reports', async (req: any, res: any) => { try { if (!req.session.account || req.session.account.staffmodlevel < 1) { - return res.redirect('/account/login', 302); + return res.redirect('/account/login?redirectUrl=/mod/reports', 302); } return res.view('mod/reports', { @@ -92,12 +95,12 @@ export default async function (app: FastifyInstance) { app.get('/uid/:uid', async (req: any, res: any) => { try { - if (!req.session.account || req.session.account.staffmodlevel < 1) { - return res.redirect('/account/login', 302); - } - const { uid } = req.params; + if (!req.session.account || req.session.account.staffmodlevel < 1) { + return res.redirect(`/account/login?redirectUrl=/mod/uid/${uid}`, 302); + } + const sessions = await db.selectFrom('session').select('uid') .where('uid', '=', uid) .groupBy('account_id') @@ -116,12 +119,12 @@ export default async function (app: FastifyInstance) { app.get('/ip/:ip', async (req: any, res: any) => { try { - if (!req.session.account || req.session.account.staffmodlevel < 1) { - return res.redirect('/account/login', 302); - } - const { ip } = req.params; + if (!req.session.account || req.session.account.staffmodlevel < 1) { + return res.redirect(`/account/login?redirectUrl=/mod/ip/${ip}`, 302); + } + const sessions = await db.selectFrom('session').select('ip') .where('ip', '=', ip) .groupBy('account_id') @@ -146,6 +149,10 @@ export default async function (app: FastifyInstance) { const { id } = req.params; const { banned_until } = req.body; + if (!banned_until) { + return res.status(400).send({ error: `Missing 'banned_until' in body` }); + } + await db.updateTable('account') .set({ banned_until: toDbDate(banned_until) }) .where('id', '=', id) @@ -153,4 +160,72 @@ export default async function (app: FastifyInstance) { return res.status(200).send(); }); + + app.post('/change-name/:id', async (req: any, res: any) => { + if (!req.session.account || req.session.account.staffmodlevel < 1) { + return res.status(401).send({ error: 'Unauthorized' }); + } + + const { id } = req.params; + const { new_username, unban } = req.body; + + if (!new_username) { + return res.status(400).send({ error: `Missing 'new_username' in body` }); + } + + const nameCheck = isUsernameValid(new_username); + if (!nameCheck.success) { + return res.status(400).send({ error: nameCheck.message }); + } + + const profanityCheck = isUsernameExplicit(new_username); + if (!profanityCheck.success) { + return res.status(400).send({ error: nameCheck.message }); + } + + const account = await db.selectFrom('account') + .where('id', '=', id) + .selectAll() + .executeTakeFirst(); + + if (!account) { + return res.status(400).send({ error: `User with '${id}' does not exist.`}); + } + + const safeNewName = toSafeName(new_username); + const existingAccount = await db.selectFrom('account') + .where('username', '=', safeNewName) + .selectAll() + .executeTakeFirst(); + + if (existingAccount) { + return res.status(400).send({ error: `User with ${new_username} already exists - please select a new name.`}); + } + + if (!fs.existsSync(`data/players/${id}/${account.username}.sav`)) { + return res.status(400).send({ error: `Unable to find user ${account.username}'s save file. Please report this issue.`}); + } + + let updatePlayerModel: any = { username: safeNewName }; + if (unban === true) { + updatePlayerModel.banned_until = null; + } + + await db.updateTable('account') + .set(updatePlayerModel) + .where('id', '=', id) + .execute(); + + await db.insertInto('account') + .values({ + username: account.username, + password: '(Set from mod web tools)' + }) + .execute(); + + fs.copyFileSync(`data/players/${id}/${account.username}.sav`, `data/players/${id}/${safeNewName}.sav`); + fs.unlinkSync(`data/players/${id}/${account.username}.sav`); + + return res.status(200).send({ success: true }); + }); } diff --git a/src/util/Username.ts b/src/util/Username.ts new file mode 100644 index 0000000..480a7b1 --- /dev/null +++ b/src/util/Username.ts @@ -0,0 +1,69 @@ +import { toDisplayName, toSafeName } from '#/jstring/JString.js'; +import { + RegExpMatcher, + englishDataset, + englishRecommendedTransformers, +} from 'obscenity'; + +type UsernameCheckResult = { + success: boolean; + message?: string; +} + +const usernameCannotStartWith = [' ', 'mod_', 'm0d_']; +const usernameCannotEndWith = [' ']; + +const staticBlockedUsernames = [ + // thank you all: + 'Andrew', + 'Paul', + 'Ian', + 'Ash', // always just "mod ash" but put some respect on em! + // and every other mod that contributed to the success and longevity of the game + + // extras that players want to abuse and will surely circumvent :( + 'Admin', + 'Administrator', + 'Mod', + 'Moderator' +]; + +const blockedUsernames = new RegExpMatcher({ + ...englishDataset.build(), + ...englishRecommendedTransformers, +}); + +export function isUsernameValid(username: string): UsernameCheckResult { + const name = toSafeName(username); + if (name ==='invalid_name' || name.length < 1 || name.length > 12) { + return { + success: false, + message: 'You must enter a valid username.' + }; + } + + return { success: true }; +} + +export function isUsernameExplicit(username: string): UsernameCheckResult { + const name = toSafeName(username); + const displayName = toDisplayName(username); + + let passPrefixSuffixTest = true; + + usernameCannotStartWith.forEach(prefix => { + if (name.startsWith(prefix)) passPrefixSuffixTest = false; + }); + usernameCannotEndWith.forEach(suffix => { + if (name.endsWith(suffix)) passPrefixSuffixTest = false; + }); + + if (blockedUsernames.hasMatch(username) || staticBlockedUsernames.includes(username) || !passPrefixSuffixTest) { + return { + success: false, + message: 'That username is not available.' + }; + } + + return { success: true }; +} \ No newline at end of file diff --git a/view/_components/modal-ban-player.ejs b/view/_components/modal-ban-player.ejs index c087e7f..9904535 100644 --- a/view/_components/modal-ban-player.ejs +++ b/view/_components/modal-ban-player.ejs @@ -1,9 +1,9 @@ - +

Are You Sure?

- +

Please select $USERNAME's ban length:

+
+ <%- include('stones-button.ejs', { id: 'modal-cancel-change-username-btn', text: 'Cancel' }); %> + + <%- include('stones-button.ejs', { id: 'modal-confirm-change-username-btn', text: 'Rename', shiny: true }); %> + + <%- include('stones-button.ejs', { id: 'modal-confirm-change-unban-username-btn', text: 'Rename &
Unban', shiny: true }); %> +
+
+
\ No newline at end of file diff --git a/view/_scripts/mod/overview.ejs b/view/_scripts/mod/overview.ejs index 7abefc6..af04d4d 100644 --- a/view/_scripts/mod/overview.ejs +++ b/view/_scripts/mod/overview.ejs @@ -3,17 +3,36 @@ muteButton = document.getElementById('mute-btn'), changeUsernameButton = document.getElementById('name-change-btn'); - const banModal = document.getElementById('modal-ban-player'); - - const banModalUsername = document.querySelector('#modal-ban-player-username > span'), + const banModal = document.getElementById('modal-ban-player'), + banModalUsername = document.getElementById('modal-ban-player-username'), banModalTimePeriodSelect = document.getElementById('modal-ban-player-time-select'), - banModalCustomTimePeriod = document.getElementById('modal-ban-player-time-custom'); - const banModalBanButton = document.getElementById('modal-ban-player-btn'), + banModalCustomTimePeriod = document.getElementById('modal-ban-player-time-custom'), + banModalBanButton = document.getElementById('modal-ban-player-btn'), banModalMercyButton = document.getElementById('modal-cancel-ban-btn'); + + const changeUsernameModal = document.getElementById('modal-change-username'), + changeUsernameConfirmButton = document.getElementById('modal-confirm-change-username-btn'), + changeUsernameUnbanConfirmButton = document.getElementById('modal-confirm-change-unban-username-btn'), + changeUsernameCancelButton = document.getElementById('modal-cancel-change-username-btn'), + changeUsernameTitle = document.getElementById('modal-change-username-span'), + changeUsernameInput = document.getElementById('modal-change-username-input'); - banModalUsername.textContent = accountUsername; + function addDaysToCurrentDate(days) { + const currentDate = new Date(); + + // Get the current timestamp, and add days converted to milliseconds because .setDate()/.getDate() + // give wildly inaccurate results for some reason + const futureTime = currentDate.getTime() + (days * 24 * 60 * 60 * 1000); + return new Date(futureTime); + } - async function banUser() { + function resetModalInputs() { + banModalTimePeriodSelect.value = 1; + banModalCustomTimePeriod.value = ""; + changeUsernameInput.value = ""; + } + + async function submitBanUserRequest() { if (banModalTimePeriodSelect.value === -1) { if (banModalCustomTimePeriod.value == "" || banModalCustomTimePeriod.value == null) { alert('Please enter amount of days for custom ban time length'); @@ -22,13 +41,10 @@ } let numberOfDays = banModalTimePeriodSelect.value == -1 ? banModalCustomTimePeriod.value : banModalTimePeriodSelect.value; - let banDate = new Date(); - console.log(`Adding ${numberOfDays} to ${banDate.toISOString()}`); - banDate.setUTCDate(banDate.getUTCDate() + numberOfDays); - console.log(`Added ${numberOfDays} (${banDate.toISOString()})`); + let banDate = addDaysToCurrentDate(numberOfDays); - if (confirm(`Are you sure you want to ban ${accountUsername} for ${numberOfDays} day(s)?`)) { - fetch(`/mod/ban/${accountUserId}`, { + if (confirm(`Are you sure you want to ban ${account.username} for ${numberOfDays} day(s)?`)) { + fetch(`/mod/ban/${account.id}`, { method: 'POST', body: JSON.stringify({ banned_until: banDate.toISOString() @@ -39,30 +55,76 @@ }).then(res => { if (res.status == 200) { banModal.close(); - alert(`Successfully banned ${accountUsername} for ${numberOfDays} day(s).`); + alert(`Successfully banned ${account.username} for ${numberOfDays} day(s).`); window.location.reload(); } else { alert('Something went wrong. Please signout and back in, then try again.'); } + }).catch(err => { + alert(`An unknown error occurred. Please report this issue.\n\n${err}`); + console.log(err); }); } } - // TEMPORARY - function nyi() { + async function muteUser() { alert('Not yet implemented! Please try again on another date.'); } - muteButton.addEventListener('click', nyi); - changeUsernameButton.addEventListener('click', nyi); + + async function submitChangeUsernameRequest(unban = false) { + const newUsername = changeUsernameInput.value; + if (newUsername === "") { + alert('Please enter new username before submitting!'); + return; + } + + if (confirm(`Are you sure you want to ${unban ? 'unban and ' : ''}rename ${account.username} to '${newUsername}?'`)) { + let body = { + new_username: newUsername + }; + + if (unban) { + body.unban = true; + } + + fetch(`/mod/change-name/${account.id}`, { + method: 'POST', + body: JSON.stringify(body), + headers: { + 'Content-Type': 'application/json' + } + }) + .then(res => res.json()) + .then(json => { + if (json.error) { + alert(json.error); + } else { + changeUsernameModal.close(); + alert(`Successfully unbanned and changed ${account.username}'s username to '${newUsername}'.`); + location.href = `/mod/overview/${newUsername}` + } + }).catch(err => { + alert(`An unknown error occurred. Please report this issue.\n\n${err}`); + console.log(err); + }); + } + } + + muteButton.addEventListener('click', muteUser); banButton.addEventListener('click', (event) => { + if (account.banned_until) { + alert(`${account.username} is already banned!`); + return; + } + + resetModalInputs(); banModal.showModal(); }); banModalMercyButton.addEventListener('click', (event) => { banModal.close(); }); - banModalBanButton.addEventListener('click', banUser); - + banModalBanButton.addEventListener('click', submitBanUserRequest); banModalTimePeriodSelect.addEventListener('change', (event) => { const newValue = event.target.value; if (newValue == -1) { @@ -71,5 +133,22 @@ banModalCustomTimePeriod.classList.add('hidden'); } }); - + + changeUsernameButton.addEventListener('click', (event) => { + resetModalInputs(); + changeUsernameModal.showModal(); + }); + changeUsernameConfirmButton.addEventListener('click', (event) => { + submitChangeUsernameRequest(); + }); + changeUsernameUnbanConfirmButton.addEventListener('click', (event) => { + submitChangeUsernameRequest(true); + }); + changeUsernameCancelButton.addEventListener('click', (event) => { + changeUsernameModal.close(); + }); + + banModalUsername.textContent = account.username; + changeUsernameTitle.textContent = account.username; + resetModalInputs(); \ No newline at end of file diff --git a/view/mod/overview.ejs b/view/mod/overview.ejs index 8765150..a77724c 100644 --- a/view/mod/overview.ejs +++ b/view/mod/overview.ejs @@ -5,7 +5,8 @@ <%- include('../_components/content-body-start.ejs'); %> -<%- include('../_components/modal-ban-player.ejs', { username: account.username }); %> +<%- include('../_components/modal-ban-player.ejs'); %> +<%- include('../_components/modal-change-username.ejs'); %> <% if (account.banned_until) { %> Banned until: <%= account.banned_until.toISOString().replace("T"," ").substring(0, 19); %>
@@ -122,7 +123,7 @@ Muted until: <%= account.muted_until.toISOString().replace("T"," ").subs <%- include('../_partial/footer.ejs'); %> <%- include('../_scripts/mod/overview.ejs'); %> \ No newline at end of file