feat: Added change username and mod redirect URL (#15)

* feat: Added starting point for basic web-based moderation tools. Only ban button functions currently.

* fix: Fixed custom ban date, added ban btn check

* feat: Basic login redirecting to previous page

* chore: Made modal CSS classes more reusable

* chore: Moved username validation to separate function

* feat: Added username changing to mod web tools

* fix: Fixed typos in name change dialogs
This commit is contained in:
Cyperita authored and GitHub committed 2025-02-04 11:17:34 -05:00
1 parent 0cf7fd83a1
commit 0fa445a2d0
9 files changed
+316 -91

No files matched your search

+14 -13
View File
@@ -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;
}
+5
View File
@@ -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);
});
+13 -38
View File
@@ -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);
}
+89 -14
View File
@@ -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 });
});
}
+69
View File
@@ -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 };
}
+2 -2
View File
@@ -1,9 +1,9 @@
<dialog id="modal-ban-player" class="focused-dialog">
<dialog id="modal-ban-player" class="modal focused-modal">
<div>
<h2>Are You Sure?</h2>
</div>
<form method="post">
<h3 id="modal-ban-player-username">Please select <span style="color:maroon">$USERNAME</span>'s ban length:</h3>
<h3>Please select <span id="modal-ban-player-username" style="color:maroon">$USERNAME</span>'s ban length:</h3>
<div class="modal-ban-player-time-container">
<select id="modal-ban-player-time-select" value="1">
<option value="1">1 Day</option>
@@ -0,0 +1,20 @@
<dialog id="modal-change-username" class="modal focused-modal">
<div>
<h2>Change Username</h2>
</div>
<form method="post" autocomplete="off">
<h3>Please choose <span id="modal-change-username-span" style="color:maroon">$USERNAME</span>'s new username:</h3>
<div class="modal-ban-player-time-container">
<!-- This input is to prevent FF from auto filling username because it ignores autocomplete="off"-->
<input type="text" style="display:none">
<input type="text" id="modal-change-username-input" placeholder="New username">
</div>
<div class="row">
<%- include('stones-button.ejs', { id: 'modal-cancel-change-username-btn', text: 'Cancel' }); %>
<span style="width:1rem"></span>
<%- include('stones-button.ejs', { id: 'modal-confirm-change-username-btn', text: 'Rename', shiny: true }); %>
<span style="width:1rem"></span>
<%- include('stones-button.ejs', { id: 'modal-confirm-change-unban-username-btn', text: 'Rename &amp;<br>Unban', shiny: true }); %>
</div>
</form>
</dialog>
+100 -21
View File
@@ -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();
</script>
+4 -3
View File
@@ -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: <strong><%= account.banned_until.toISOString().replace("T"," ").substring(0, 19); %></strong><br>
@@ -122,7 +123,7 @@ Muted until: <strong><%= account.muted_until.toISOString().replace("T"," ").subs
<%- include('../_partial/footer.ejs'); %>
<script>
const accountUsername = "<%- account.username %>";
const accountUserId = <%- account.id %>;
<% const { password, ...sanitizedAccount } = account %>
const account = JSON.parse(`<%- JSON.stringify(sanitizedAccount) %>`);
</script>
<%- include('../_scripts/mod/overview.ejs'); %>