From 68c374fee969c0bc12e3866d9a680959412abd8a Mon Sep 17 00:00:00 2001 From: Bauke Date: Sun, 10 Nov 2019 23:28:51 +0100 Subject: [PATCH] Refactor: Replace username validation with schema from Tildes source code. This replaces the simple >3 check with the correct min and max lengths and Regex that are in the Tildes source code. --- source/ts/scripts/user-labels.ts | 1 + source/ts/scripts/user-labels/label-form.ts | 7 ++++--- source/ts/utilities.ts | 10 ++++++++++ 3 files changed, 15 insertions(+), 3 deletions(-) diff --git a/source/ts/scripts/user-labels.ts b/source/ts/scripts/user-labels.ts index 1f58428..0d17449 100644 --- a/source/ts/scripts/user-labels.ts +++ b/source/ts/scripts/user-labels.ts @@ -192,6 +192,7 @@ function addLabelsToUsernames(settings: Settings): void { const username: string = element .textContent!.replace(/@/g, '') .toLowerCase(); + const addLabelSpan: HTMLSpanElement = createElementFromString( `[+]` ); diff --git a/source/ts/scripts/user-labels/label-form.ts b/source/ts/scripts/user-labels/label-form.ts index a4a1510..dee0610 100644 --- a/source/ts/scripts/user-labels/label-form.ts +++ b/source/ts/scripts/user-labels/label-form.ts @@ -5,7 +5,8 @@ import { log, isColorBright, getCurrentThemeKey, - querySelector + querySelector, + isValidTildesUsername } from '../../utilities'; import {themeColors, ThemeKey} from '../../theme-colors'; @@ -95,8 +96,8 @@ export function getLabelFormValues(): Except | undefined { username: usernameInput.value.toLowerCase() }; - if (data.username.length < 3) { - log('No username was provided to add a label to.', true); + if (!isValidTildesUsername(data.username)) { + log(`Invalid Tildes username detected: ${data.username}`); usernameInput.classList.add('trx-invalid'); return undefined; } diff --git a/source/ts/utilities.ts b/source/ts/utilities.ts index 7a58670..90e5ba7 100644 --- a/source/ts/utilities.ts +++ b/source/ts/utilities.ts @@ -252,3 +252,13 @@ export function flashMessage(message: string, error = false): void { } }, 5000); } + +// Validation copied from Tildes source code: +// https://gitlab.com/tildes/tildes/blob/master/tildes/tildes/schemas/user.py +export function isValidTildesUsername(username: string): boolean { + return ( + username.length > 3 && + username.length < 20 && + /^[a-z0-9]([a-z0-9]|[_-](?![_-]))*[a-z0-9]$/i.exec(username) !== null + ); +}