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 legacy user migration flow #174

Merged
merged 21 commits into from
Nov 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/curvy-starfishes-change.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@treasure-dev/tdk-core": patch
---

Added API client helper for legacy user migration
5 changes: 5 additions & 0 deletions .changeset/ninety-shirts-pay.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@treasure-dev/tdk-react": minor
---

Added legacy user migration flow to connect modal
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- CreateIndex
CREATE INDEX "user_smart_account_address_idx" ON "public"."user_smart_account"("address");
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
-- AddForeignKey
ALTER TABLE "public"."user_social_account" ADD CONSTRAINT "user_social_account_legacy_user_profile_id_fkey" FOREIGN KEY ("legacy_user_profile_id") REFERENCES "public"."user_profile"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "public"."user_notification_settings" ADD CONSTRAINT "user_notification_settings_legacy_user_profile_id_fkey" FOREIGN KEY ("legacy_user_profile_id") REFERENCES "public"."user_profile"("id") ON DELETE CASCADE ON UPDATE CASCADE;
13 changes: 9 additions & 4 deletions apps/api/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ model UserSmartAccount {
updatedAt DateTime @updatedAt @map("updated_at")

@@unique([chainId, address])
@@index([address])
@@index([userId])
@@map("user_smart_account")
@@schema("public")
Expand Down Expand Up @@ -102,8 +103,10 @@ model UserProfile {
testnetFaucetLastUsedAt DateTime? @map("testnet_faucet_last_used_at")

// Relations
userId String? @unique @map("user_id")
user User? @relation(fields: [userId], references: [id])
userId String? @unique @map("user_id")
user User? @relation(fields: [userId], references: [id])
legacySocialAccounts UserSocialAccount[]
legacyNotificationSettings UserNotificationSettings[]

// Computed
createdAt DateTime @default(now()) @map("created_at")
Expand Down Expand Up @@ -138,7 +141,8 @@ model UserSocialAccount {
isPublic Boolean @default(false) @map("is_public")

// Migration
legacyUserProfileId String? @map("legacy_user_profile_id")
legacyUserProfileId String? @map("legacy_user_profile_id")
legacyUserProfile UserProfile? @relation(fields: [legacyUserProfileId], references: [id], onDelete: Cascade)

// Relations
userId String? @map("user_id")
Expand Down Expand Up @@ -176,7 +180,8 @@ model UserNotificationSettings {
isEnabledInApp Boolean @default(true) @map("is_enabled_in_app")

// Migration
legacyUserProfileId String? @map("legacy_user_profile_id")
legacyUserProfileId String? @map("legacy_user_profile_id")
legacyUserProfile UserProfile? @relation(fields: [legacyUserProfileId], references: [id], onDelete: Cascade)

// Relations
userId String? @map("user_id")
Expand Down
40 changes: 25 additions & 15 deletions apps/api/src/routes/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ import type { TdkApiContext } from "../types";
import {
USER_NOTIFICATION_SETTINGS_SELECT_FIELDS,
USER_PROFILE_SELECT_FIELDS,
USER_PUBLIC_PROFILE_SELECT_FIELDS,
USER_SELECT_FIELDS,
USER_SMART_ACCOUNT_SELECT_FIELDS,
USER_SOCIAL_ACCOUNT_SELECT_FIELDS,
Expand All @@ -37,6 +36,7 @@ import { throwUnauthorizedError, throwUserNotFoundError } from "../utils/error";
import { log } from "../utils/log";
import {
getThirdwebUser,
migrateLegacyUser,
parseThirdwebUserEmail,
transformUserProfileResponseFields,
} from "../utils/user";
Expand Down Expand Up @@ -173,7 +173,7 @@ export const authRoutes =
});
}

const [user, profile, legacyUserProfiles] = await Promise.all([
const [user, profile, legacyProfiles] = await Promise.all([
// Fetch user
db.user.findUnique({
where: { id: userSmartAccount.userId },
Expand Down Expand Up @@ -207,17 +207,12 @@ export const authRoutes =
legacyEmail: userSmartAccount.initialEmail,
legacyEmailVerifiedAt: { not: null },
},
select: {
...USER_PUBLIC_PROFILE_SELECT_FIELDS,
id: true,
},
})
: userSmartAccount.initialWalletAddress
? db.userProfile.findUnique({
? db.userProfile.findMany({
where: {
legacyAddress: userSmartAccount.initialWalletAddress,
},
select: { ...USER_PUBLIC_PROFILE_SELECT_FIELDS, id: true },
})
: [],
]);
Expand Down Expand Up @@ -268,20 +263,35 @@ export const authRoutes =
endTimestamp: session.endTimestamp.toString(),
}));

let updatedProfile: typeof profile | undefined;

if (env.USER_MIGRATION_ENABLED) {
// Automatically migrate legacy profile if only one exists
if (legacyProfiles.length === 1 && !!legacyProfiles[0]) {
const result = await migrateLegacyUser({
db,
userId: user.id,
userProfileId: profile.id,
legacyProfile: legacyProfiles[0],
});
updatedProfile = result.updatedProfile;
}
}

const finalProfile = updatedProfile ?? profile;
reply.send({
token: authTokenResult.value,
user: {
...user,
...profile,
...transformUserProfileResponseFields(profile),
...finalProfile,
...transformUserProfileResponseFields(finalProfile),
address,
sessions,
},
legacyProfiles: legacyUserProfiles
? Array.isArray(legacyUserProfiles)
? legacyUserProfiles
: [legacyUserProfiles]
: [],
legacyProfiles:
env.USER_MIGRATION_ENABLED && legacyProfiles.length > 1
? legacyProfiles
: [],
});
},
);
Expand Down
Loading