From 3aa27ae5972237162a09b04af60b6798c3602e8b Mon Sep 17 00:00:00 2001 From: "Lin, Hung-Shin" Date: Thu, 14 Sep 2023 17:39:26 +0800 Subject: [PATCH] feat: add username and email validation function --- server/src/utils/auth.js | 39 +++++++++++++++++++++++++++++ server/tests/utils/auth.test.js | 44 +++++++++++++++++++++++++++++++++ 2 files changed, 83 insertions(+) create mode 100644 server/tests/utils/auth.test.js diff --git a/server/src/utils/auth.js b/server/src/utils/auth.js index 3e29a82..9199286 100644 --- a/server/src/utils/auth.js +++ b/server/src/utils/auth.js @@ -59,3 +59,42 @@ export function verifyJWT(token) { }) }) } + +export function isValidUsername(username) { + // Define a regular expression pattern for a valid Linux username. + const usernamePattern = /^[a-z][a-z0-9_-]*$/ + + // Test the username against the pattern. + if (!usernamePattern.test(username)) return false + + // check if the username is between 1 and 32 characters + if (username.length < 1 || username.length > 32) { + return false + } + + const reservedWords = [ + 'root', + 'admin', + 'administrator', + 'sysadmin', + 'system', + 'daemon', + 'bin', + 'nobody', + 'nogroup', + 'guest', + 'user', + ] + if (reservedWords.includes(username)) { + return false + } + return true +} + +export function isValidEmail(email) { + // Define a regular expression pattern for a valid email address. + const emailPattern = /^[\w-.+]+@([\w][\w-]*\.)+[\w-]{2,}$/ + + // Test the email against the pattern. + return emailPattern.test(email) +} diff --git a/server/tests/utils/auth.test.js b/server/tests/utils/auth.test.js new file mode 100644 index 0000000..3df34ed --- /dev/null +++ b/server/tests/utils/auth.test.js @@ -0,0 +1,44 @@ +import { isValidEmail, isValidUsername } from '../../src/utils/auth' + +test('check valid username', () => { + const valid = ['alex', 'alex123', 'john_doe', 'john-doe', 'rudeus'] + + const invalid = ['root', 'admin', '12michael', 'Justin', 'testUser'] + + valid.forEach((username) => { + expect(isValidUsername(username)).toBe(true) + }) + + invalid.forEach((username) => { + expect(isValidUsername(username)).toBe(false) + }) +}) + +test('check valid email', () => { + const validEmails = [ + 'user@example.com', + 'user.name@example.co.uk', + 'user1234@email.domain', + 'user+tag@example.net', + 'user@subdomain.example.com', + 'user@123.45.67.89', + ] + + const invalidEmails = [ + 'user@.com', + '@example.com', + 'user@-invalid-domain.com', + 'user@.123', + 'user@.123.45.67', + ] + + validEmails.forEach((email) => { + console.log(email) + expect(isValidEmail(email)).toBe(true) + }) + + invalidEmails.forEach((email) => { + console.log(email) + expect(isValidEmail(email)).toBe(false) + }) +})