From 5ea2a02571ae9206e45699948339fb20219916e4 Mon Sep 17 00:00:00 2001
From: Viet Nguyen <3805254+vnugent@users.noreply.github.com>
Date: Sat, 16 Nov 2024 12:40:06 -0800
Subject: [PATCH] fix: double-check user profile in db

---
 src/js/auth/initializeUserInDb.ts | 21 +++++++++++++++++++--
 1 file changed, 19 insertions(+), 2 deletions(-)

diff --git a/src/js/auth/initializeUserInDb.ts b/src/js/auth/initializeUserInDb.ts
index d4911741a..ab0c95c53 100644
--- a/src/js/auth/initializeUserInDb.ts
+++ b/src/js/auth/initializeUserInDb.ts
@@ -1,5 +1,5 @@
 import { getClient } from '../graphql/ServerClient'
-import { MUTATION_UPDATE_PROFILE } from '../graphql/gql/users'
+import { MUTATION_UPDATE_PROFILE, QUERY_DOES_USERNAME_EXIST } from '../graphql/gql/users'
 import { updateUser } from './ManagementClient'
 
 export interface UpdateUsernameInput {
@@ -14,9 +14,15 @@ interface InitializeUserInDBParams extends UpdateUsernameInput {
   auth0UserId: string
 }
 
+const serverClient = getClient()
+
 export const initializeUserInDB = async (params: InitializeUserInDBParams): Promise<boolean> => {
   const { auth0UserId, accessToken, userUuid, username, email, avatar } = params
-  const res = await getClient().mutate<{ updateUserProfile?: boolean }, UpdateUsernameInput>({
+  const existed = await doesUserExist(username)
+  if (existed) {
+    return false
+  }
+  const res = await serverClient.mutate<{ updateUserProfile?: boolean }, UpdateUsernameInput>({
     mutation: MUTATION_UPDATE_PROFILE,
     variables: {
       userUuid,
@@ -42,3 +48,14 @@ export const initializeUserInDB = async (params: InitializeUserInDBParams): Prom
   }
   return success
 }
+
+const doesUserExist = async (username: string): Promise<boolean> => {
+  const res = await serverClient.query<{ usernameExists: boolean }, { username: string }>({
+    query: QUERY_DOES_USERNAME_EXIST,
+    variables: {
+      username
+    },
+    fetchPolicy: 'no-cache'
+  })
+  return res.data.usernameExists
+}