diff --git a/package.json b/package.json index 028f18a55..73c5c2fc4 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@staart/manager", - "version": "1.3.26", + "version": "1.3.27", "main": "index.js", "repository": "git@github.com:staart/api.git", "author": "Anand Chowdhary ", @@ -125,5 +125,5 @@ "setup" ], "snyk": true, - "staart-version": "1.3.26" + "staart-version": "1.3.27" } \ No newline at end of file diff --git a/src/crud/user.ts b/src/crud/user.ts index d93d3a789..5d6358250 100644 --- a/src/crud/user.ts +++ b/src/crud/user.ts @@ -15,7 +15,12 @@ import { } from "../interfaces/tables/user"; import { decode } from "jsonwebtoken"; import { deleteSensitiveInfoUser } from "../helpers/utils"; -import { capitalizeFirstAndLastLetter, anonymizeIpAddress } from "@staart/text"; +import { + capitalizeFirstAndLastLetter, + anonymizeIpAddress, + slugify, + createSlug +} from "@staart/text"; import { hash } from "bcryptjs"; import { KeyValue } from "../interfaces/general"; import { NotificationEmails, CacheCategories } from "../interfaces/enum"; @@ -49,6 +54,23 @@ import ClientOAuth2 from "client-oauth2"; import Axios from "axios"; import { createHash } from "crypto"; +export const getBestUsernameForUser = async (name: string) => { + let result: string; + if (name.split(" ")[0].length) { + result = slugify(name.split(" ")[0]); + if (checkUsernameAvailability(result)) return result; + } + result = slugify(name); + if (checkUsernameAvailability(result)) return result; + + let available = false; + while (!available) { + result = createSlug(name); + if (checkUsernameAvailability(result)) available = true; + } + return result; +}; + /** * Get a list of all ${tableName("users")} */ diff --git a/src/rest/auth.ts b/src/rest/auth.ts index 79ecfedd7..8cbf57211 100644 --- a/src/rest/auth.ts +++ b/src/rest/auth.ts @@ -9,7 +9,8 @@ import { getUserBackupCode, updateBackupCode, checkUsernameAvailability, - deleteSessionByJwt + deleteSessionByJwt, + getBestUsernameForUser } from "../crud/user"; import { InsertResult } from "../interfaces/mysql"; import { @@ -125,9 +126,9 @@ export const register = async ( await checkIfNewEmail(email); if (!ALLOW_DISPOSABLE_EMAILS) checkIfDisposableEmail(email); } - if (!user.username) user.username = createSlug(user.name); - if (!(await checkUsernameAvailability(user.username))) + if (user.username && !(await checkUsernameAvailability(user.username))) throw new Error(USERNAME_EXISTS); + user.username = user.username || (await getBestUsernameForUser(user.name)); const result = await createUser(user); const userId = result.insertId; // Set email