Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add frontend code to merge users #3488

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
32 changes: 16 additions & 16 deletions website/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions website/package.json
Expand Up @@ -46,7 +46,7 @@
"@next-auth/prisma-adapter": "^1.0.6",
"@next/bundle-analyzer": "^13.4.4",
"@nikolovlazar/chakra-ui-prose": "^1.2.1",
"@prisma/client": "^4.13.0",
"@prisma/client": "^4.15.0",
"@tailwindcss/forms": "^0.5.3",
"@tanstack/react-table": "^8.9.1",
"autoprefixer": "^10.4.14",
Expand Down Expand Up @@ -122,7 +122,7 @@
"path-browserify": "^1.0.1",
"pino-pretty": "^10.0.0",
"prettier": "^2.8.8",
"prisma": "^4.14.0",
"prisma": "^4.15.0",
"storybook": "^7.0.9",
"ts-essentials": "^9.3.2",
"ts-node": "^10.9.1",
Expand Down
@@ -0,0 +1,17 @@
-- CreateTable
CREATE TABLE "BackendInfo" (
"id" TEXT NOT NULL,
"frontendUserId" TEXT NOT NULL,
"backendUserId" TEXT NOT NULL,

CONSTRAINT "BackendInfo_pkey" PRIMARY KEY ("id")
);

-- CreateIndex
CREATE UNIQUE INDEX "BackendInfo_frontendUserId_key" ON "BackendInfo"("frontendUserId");

-- CreateIndex
CREATE UNIQUE INDEX "BackendInfo_backendUserId_key" ON "BackendInfo"("backendUserId");

-- AddForeignKey
ALTER TABLE "BackendInfo" ADD CONSTRAINT "BackendInfo_frontendUserId_fkey" FOREIGN KEY ("frontendUserId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
15 changes: 12 additions & 3 deletions website/prisma/schema.prisma
Expand Up @@ -44,9 +44,18 @@ model User {
isNew Boolean @default(true)
role String @default("general")

accounts Account[]
sessions Session[]
tasks RegisteredTask[]
accounts Account[]
sessions Session[]
tasks RegisteredTask[]
backendInfo BackendInfo?
}

model BackendInfo {
id String @id @default(cuid())
frontendUserId String @unique
backendUserId String @unique

user User @relation(fields: [frontendUserId], references: [id], onDelete: Cascade)
}

model VerificationToken {
Expand Down
6 changes: 5 additions & 1 deletion website/src/lib/oasst_api_client.ts
Expand Up @@ -434,7 +434,7 @@ export class OasstApiClient {
});
}

fetch_frontend_user(user: BackendUserCore) {
fetch_frontend_user(user: Omit<BackendUserCore, "display_name">) {
return this.get<BackendUser>(`/api/v1/frontend_users/${user.auth_method}/${user.id}`);
}

Expand Down Expand Up @@ -481,4 +481,8 @@ export class OasstApiClient {
const backendUser = await this.fetch_frontend_user(user);
return this.delete<void>(`/api/v1/users/${backendUser.user_id}`);
}

merge_backend_users(destination_user_id: string, source_user_ids: string[]) {
return this.post<void>("/api/v1/admin/merge_users", { destination_user_id, source_user_ids });
}
}
74 changes: 74 additions & 0 deletions website/src/lib/users.ts
Expand Up @@ -4,6 +4,8 @@ import { AuthMethod } from "src/types/Providers";
import type { BackendUserCore } from "src/types/Users";

import { logger } from "./logger";
import { OasstError } from "./oasst_api_client";
import { userlessApiClient } from "./oasst_client_factory";

/**
* Returns a `BackendUserCore` that can be used for interacting with the Backend service.
Expand Down Expand Up @@ -111,3 +113,75 @@ export const getBatchFrontendUserIdFromBackendUser = async (users: { username: s

return outputIds;
};

/**
* merges all backend users into one, and saves the value in the database
*
* This function is currently unused
*
* TODO: do we need to make this idempotent? should we check if the user is already merged
* before we continue with the merging?
*/
export const mergeUserAccountsInBackend = async (frontendId: string): Promise<string | null> => {
const user = await prisma.user.findUnique({
where: { id: frontendId },
select: { id: true, name: true, emailVerified: true, accounts: true },
});

const accounts = user.accounts
.map((x) => ({
auth_method: x.provider as AuthMethod,
id: x.providerAccountId,
}))
.concat([{ auth_method: "local", id: frontendId }]);

const backendUsers = await Promise.all(
accounts.map((account) =>
userlessApiClient.fetch_frontend_user(account).catch<null>((err) => {
// if 404, thats okay
if (!(err instanceof OasstError) || err.httpStatusCode !== 404) {
console.error(err);
}
return null;
})
)
);

const backendIds = backendUsers.filter(Boolean).map((user) => user.user_id);
if (backendIds.length === 0) {
logger.error({ message: `Wanted to merge user accounts but found none.`, frontendId, accounts });
return null;
}

// id after merge
let backendId: string;

if (backendIds.length === 1) {
backendId = backendIds[0];
logger.info({ message: `Wanted to merge user accounts, but found only one, skipping.`, frontendId, backendId });
} else {
logger.info({ message: "Merging user accounts", frontendId, accounts, backendIds });
let remainingIds: string[];

[backendId, ...remainingIds] = backendIds;
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

here I am just taking the first, maybe there is a better idea.


await userlessApiClient.merge_backend_users(backendId, remainingIds);
logger.info({ message: "Merging successful", frontendId, accounts, backendIds });
}

// write to database
await prisma.backendInfo.upsert({
where: {
frontendUserId: frontendId,
},
create: {
frontendUserId: frontendId,
backendUserId: backendId,
},
update: {
backendUserId: backendId,
},
});

return backendId;
};
12 changes: 3 additions & 9 deletions website/wait-for-postgres.sh
Expand Up @@ -8,23 +8,17 @@
set -e

# validate schema
npx prisma validate
npx --yes prisma validate

# wait until the db is available
until echo 'SELECT version();' | npx prisma db execute --stdin; do
echo >&2 "Postgres is unavailable - sleeping"
sleep 1
done

echo >&2 "Postgres is up - executing command"
echo >&2 "Postgres is up - applying migrations"

# TODO: replace this command with applying migrations: npx prisma migrate deploy
# NOTE: because of our previous setup where we just synced the database, we have to "simulate"
# the initial migration with this command:
# npx prisma migrate resolve --applied 20230326131923_initial_migration
# prisma will fail with the above command if resolve is already applied,
# we might need to run the command with set +e
npx prisma db push --skip-generate
npx prisma migrate deploy

# Print and execute all other arguments starting with `$1`
# So `exec "$1" "$2" "$3" ...`
Expand Down