Skip to content

Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.

♻️ Switch to better-auth anonymous users (#1985)

Luke Vellae221665ccf9e
diff --git a/apps/landing/src/components/home/bonus.tsx b/apps/landing/src/components/home/bonus.tsx
index 6350bb6aa..efb5225ae 100644
--- a/apps/landing/src/components/home/bonus.tsx
+++ b/apps/landing/src/components/home/bonus.tsx
@@ -12,7 +12,11 @@ import { getTranslation } from "@/i18n/server";
export async function Bonus() {
const { t } = await getTranslation();
- const userCount = await prisma.user.count();
+ const userCount = await prisma.user.count({
+ where: {
+ isAnonymous: false,
+ },
+ });
const roundedUserCount =
userCount > 100000 ? Math.floor(userCount / 10000) * 10000 : userCount;
return (
diff --git a/apps/web/declarations/next-auth.d.ts b/apps/web/declarations/next-auth.d.ts
index e0e5a5c1a..fdb8cd18b 100644
--- a/apps/web/declarations/next-auth.d.ts
+++ b/apps/web/declarations/next-auth.d.ts
@@ -15,6 +15,7 @@ declare module "next-auth" {
timeFormat?: TimeFormat | null;
weekStart?: number | null;
} & DefaultSession["user"];
+ legacy?: boolean;
}
interface User extends DefaultUser {
diff --git a/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/guest-poll-alert.tsx b/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/guest-poll-alert.tsx
index b11f93baf..0cc9a0021 100644
--- a/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/guest-poll-alert.tsx
+++ b/apps/web/src/app/[locale]/(optional-space)/poll/[urlId]/guest-poll-alert.tsx
@@ -6,16 +6,10 @@ import { LoginLink } from "@/components/login-link";
import { RegisterLink } from "@/components/register-link";
import { Trans } from "@/components/trans";
import { useUser } from "@/components/user-provider";
-import { usePoll } from "@/contexts/poll";
export const GuestPollAlert = () => {
- const poll = usePoll();
const { user } = useUser();
- if (poll.user) {
- return null;
- }
-
if (user?.isGuest === false) {
return null;
}
diff --git a/apps/web/src/app/api/trpc/[trpc]/route.ts b/apps/web/src/app/api/trpc/[trpc]/route.ts
index 9c6eedac9..8f0a7323e 100644
--- a/apps/web/src/app/api/trpc/[trpc]/route.ts
+++ b/apps/web/src/app/api/trpc/[trpc]/route.ts
@@ -25,11 +25,12 @@ const handler = async (req: NextRequest) => {
const user = session?.user
? {
id: session.user.id,
- isGuest: !session.user.email,
+ isGuest: session.user.isGuest,
locale: session.user.locale ?? undefined,
image: session.user.image ?? undefined,
getEmailClient: () =>
getEmailClient(session.user?.locale ?? undefined),
+ isLegacyGuest: session.legacy && session.user.isGuest,
}
: undefined;
diff --git a/apps/web/src/app/api/user/verify-email-change/route.ts b/apps/web/src/app/api/user/verify-email-change/route.ts
index fc59b4bbb..805a65625 100644
--- a/apps/web/src/app/api/user/verify-email-change/route.ts
+++ b/apps/web/src/app/api/user/verify-email-change/route.ts
@@ -79,7 +79,7 @@ export const GET = async (request: NextRequest) => {
const session = await getSession();
- if (!session?.user || !session.user.email) {
+ if (!session?.user || session.user.isGuest) {
return NextResponse.redirect(
new URL(`/login?redirectTo=${request.url}`, request.url),
);
diff --git a/apps/web/src/auth/helpers/merge-user.ts b/apps/web/src/auth/helpers/merge-user.ts
index 67e0b0046..703e19db4 100644
--- a/apps/web/src/auth/helpers/merge-user.ts
+++ b/apps/web/src/auth/helpers/merge-user.ts
@@ -73,3 +73,62 @@ export const mergeGuestsIntoUser = async (
Sentry.captureException(error);
}
};
+
+export const linkAnonymousUser = async (
+ authenticatedUserId: string,
+ anonymousUserId: string,
+) => {
+ const spaceId = await getActiveSpaceForUser({ userId: authenticatedUserId });
+
+ if (!spaceId) {
+ console.error(`User ${authenticatedUserId} has no active space`);
+ return;
+ }
+
+ try {
+ await prisma.$transaction(async (tx) => {
+ // Transfer all data from anonymous user to authenticated user
+ await Promise.all([
+ // Transfer polls
+ tx.poll.updateMany({
+ where: {
+ userId: anonymousUserId,
+ },
+ data: {
+ userId: authenticatedUserId,
+ spaceId,
+ },
+ }),
+
+ // Transfer participants
+ tx.participant.updateMany({
+ where: {
+ userId: anonymousUserId,
+ },
+ data: {
+ userId: authenticatedUserId,
+ },
+ }),
+
+ // Transfer comments
+ tx.comment.updateMany({
+ where: {
+ userId: anonymousUserId,
+ },
+ data: {
+ userId: authenticatedUserId,
+ },
+ }),
+ ]);
+ });
+
+ // Merge user identities in PostHog
+ posthog?.capture({
+ distinctId: authenticatedUserId,
+ event: "$merge_dangerously",
+ properties: { alias: anonymousUserId },
+ });
+ } catch (error) {
+ Sentry.captureException(error);
+ }
+};
diff --git a/apps/web/src/components/user-provider.tsx b/apps/web/src/components/user-provider.tsx
index 8b5b075a8..cae4378c4 100644
--- a/apps/web/src/components/user-provider.tsx
+++ b/apps/web/src/components/user-provider.tsx
@@ -1,10 +1,10 @@
"use client";
import { useRouter } from "next/navigation";
-import { signIn } from "next-auth/react";
import React from "react";
import type { UserAbility } from "@/features/user/ability";
import { defineAbilityFor } from "@/features/user/ability";
import type { UserDTO } from "@/features/user/schema";
+import { authClient } from "@/lib/auth-client";
import { isOwner } from "@/utils/permissions";
import { useRequiredContext } from "./use-required-context";
@@ -51,9 +51,7 @@ export const UserProvider = ({
user,
createGuestIfNeeded: async () => {
if (!user) {
- await signIn("guest", {
- redirect: false,
- });
+ await authClient.signIn.anonymous();
router.refresh();
}
},
diff --git a/apps/web/src/features/poll/helpers.ts b/apps/web/src/features/poll/helpers.ts
index 0164f88de..350e7cf55 100644
--- a/apps/web/src/features/poll/helpers.ts
+++ b/apps/web/src/features/poll/helpers.ts
@@ -5,6 +5,7 @@ export async function canUserManagePoll(
user: {
id: string;
isGuest: boolean;
+ isLegacyGuest: boolean;
},
poll: {
userId?: string | null;
@@ -12,17 +13,17 @@ export async function canUserManagePoll(
spaceId?: string | null;
},
) {
- if (user.isGuest) {
+ if (user.isLegacyGuest) {
// guest user is owner
return poll.guestId === user.id;
}
- if (poll.userId && !user.isGuest && poll.userId === user.id) {
+ if (poll.userId && poll.userId === user.id) {
// user is owner
return true;
}
- if (poll.spaceId && !user.isGuest) {
+ if (poll.spaceId) {
const space = await prisma.spaceMember.findUnique({
where: {
spaceId_userId: {
diff --git a/apps/web/src/features/quick-create/lib/get-guest-polls.ts b/apps/web/src/features/quick-create/lib/get-guest-polls.ts
index 5c8446da2..2848e2485 100644
--- a/apps/web/src/features/quick-create/lib/get-guest-polls.ts
+++ b/apps/web/src/features/quick-create/lib/get-guest-polls.ts
@@ -4,16 +4,15 @@ import { getSession } from "@/lib/auth";
export async function getGuestPolls() {
const session = await getSession();
- const user = session?.user;
- const guestId = !user?.email ? user?.id : null;
- if (!guestId) {
+ if (session?.user?.isGuest !== true) {
return [];
}
const recentlyCreatedPolls = await prisma.poll.findMany({
where: {
- guestId,
+ guestId: session.legacy ? session.user.id : undefined,
+ userId: session.legacy ? undefined : session.user.id,
deleted: false,
},
select: {
diff --git a/apps/web/src/lib/auth-client.ts b/apps/web/src/lib/auth-client.ts
index c05d14309..ae5194750 100644
--- a/apps/web/src/lib/auth-client.ts
+++ b/apps/web/src/lib/auth-client.ts
@@ -1,5 +1,6 @@
import { absoluteUrl } from "@rallly/utils/absolute-url";
import {
+ anonymousClient,
emailOTPClient,
genericOAuthClient,
inferAdditionalFields,
@@ -16,6 +17,7 @@ export const authClient = createAuthClient({
emailOTPClient(),
genericOAuthClient(),
lastLoginMethodClient(),
+ anonymousClient(),
],
});
diff --git a/apps/web/src/lib/auth.ts b/apps/web/src/lib/auth.ts
index faa2948f0..a12b0e328 100644
--- a/apps/web/src/lib/auth.ts
+++ b/apps/web/src/lib/auth.ts
@@ -15,10 +15,14 @@ import {
import { headers } from "next/headers";
import { cache } from "react";
import { isEmailBlocked } from "@/auth/helpers/is-email-blocked";
-import { mergeGuestsIntoUser } from "@/auth/helpers/merge-user";
+import {
+ linkAnonymousUser,
+ mergeGuestsIntoUser,
+} from "@/auth/helpers/merge-user";
import { isTemporaryEmail } from "@/auth/helpers/temp-email-domains";
import { env } from "@/env";
import { createSpace } from "@/features/space/mutations";
+import { getTranslation } from "@/i18n/server";
import { getLocale } from "@/i18n/server/get-locale";
import { isKvEnabled, kv } from "@/lib/kv";
import { auth as legacyAuth, signOut as legacySignOut } from "@/next-auth";
@@ -97,7 +101,16 @@ export const authLib = betterAuth({
plugins: [
...plugins,
admin(),
- anonymous(),
+ anonymous({
+ emailDomainName: "rallly.co",
+ generateName: async () => {
+ const { t } = await getTranslation();
+ return t("guest");
+ },
+ onLinkAccount: async ({ anonymousUser, newUser }) => {
+ await linkAnonymousUser(newUser.user.id, anonymousUser.user.id);
+ },
+ }),
lastLoginMethod({
storeInDatabase: true,
}),
@@ -219,6 +232,9 @@ export const authLib = betterAuth({
user: {
create: {
after: async (user) => {
+ if (user.isAnonymous) {
+ return;
+ }
// check if user exists in prisma
const existingUser = await prisma.user.findUnique({
where: {
@@ -295,10 +311,11 @@ export const getSession = cache(async () => {
id: session.user.id,
email: session.user.email,
name: session.user.name,
- isGuest: !session.user.email,
+ isGuest: !!session.user.isAnonymous,
image: session.user.image,
},
expires: session.session.expiresAt.toISOString(),
+ legacy: false,
};
}
} catch (e) {
@@ -309,11 +326,19 @@ export const getSession = cache(async () => {
// Fallback to legacy auth
// TODO: Remove this once we have fully migrated to better-auth and there are no active legacy sessions left
try {
- return await legacyAuth();
+ const legacySession = await legacyAuth();
+ if (legacySession) {
+ return {
+ ...legacySession,
+ legacy: true,
+ };
+ }
} catch (e) {
console.error("FAILED TO GET LEGACY SESSION", e);
return null;
}
+
+ return null;
});
export const signOut = async () => {
diff --git a/apps/web/src/trpc/context.ts b/apps/web/src/trpc/context.ts
index f0959568b..59ef49f89 100644
--- a/apps/web/src/trpc/context.ts
+++ b/apps/web/src/trpc/context.ts
@@ -3,6 +3,7 @@ type User = {
isGuest: boolean;
locale?: string;
image?: string;
+ isLegacyGuest: boolean;
};
export type TRPCContext = {
diff --git a/apps/web/src/trpc/routers/polls.ts b/apps/web/src/trpc/routers/polls.ts
index 460672d7d..3158ed7ad 100644
--- a/apps/web/src/trpc/routers/polls.ts
+++ b/apps/web/src/trpc/routers/polls.ts
@@ -99,6 +99,7 @@ export const polls = router({
{} as Record<PollStatus, number>,
);
}),
+ /** @deprecated */
infiniteList: privateProcedure
.input(
z.object({
@@ -111,7 +112,7 @@ export const polls = router({
const { cursor, limit, status } = input;
const polls = await prisma.poll.findMany({
where: {
- ...(ctx.user.isGuest
+ ...(ctx.user.isLegacyGuest
? { guestId: ctx.user.id }
: { userId: ctx.user.id }),
deletedAt: null,
@@ -242,7 +243,7 @@ export const polls = router({
description: input.description,
adminUrlId: adminToken,
participantUrlId,
- ...(ctx.user.isGuest
+ ...(ctx.user.isLegacyGuest
? { guestId: ctx.user.id }
: { userId: ctx.user.id }),
watchers: !ctx.user.isGuest
diff --git a/apps/web/src/trpc/routers/polls/comments.ts b/apps/web/src/trpc/routers/polls/comments.ts
index 4cd19f237..2e6d5e61a 100644
--- a/apps/web/src/trpc/routers/polls/comments.ts
+++ b/apps/web/src/trpc/routers/polls/comments.ts
@@ -32,7 +32,7 @@ export const comments = router({
},
});
- const isOwner = ctx.user?.isGuest
+ const isOwner = ctx.user?.isLegacyGuest
? poll?.guestId === ctx.user.id
: poll?.userId === ctx.user?.id;
@@ -48,7 +48,7 @@ export const comments = router({
return await prisma.comment.findMany({
where: {
pollId,
- ...(ctx.user.isGuest
+ ...(ctx.user.isLegacyGuest
? { guestId: ctx.user.id }
: { userId: ctx.user.id }),
},
@@ -86,9 +86,7 @@ export const comments = router({
content,
pollId,
authorName,
- ...(ctx.user.isGuest
- ? { guestId: ctx.user.id }
- : { userId: ctx.user.id }),
+ userId: ctx.user.id,
},
select: {
id: true,
diff --git a/apps/web/src/trpc/routers/polls/participants.ts b/apps/web/src/trpc/routers/polls/participants.ts
index 8b818c4c2..84ac68e3c 100644
--- a/apps/web/src/trpc/routers/polls/participants.ts
+++ b/apps/web/src/trpc/routers/polls/participants.ts
@@ -176,7 +176,9 @@ export const participants = router({
name: name,
email,
timeZone,
- ...(user.isGuest ? { guestId: user.id } : { userId: user.id }),
+ ...(user.isLegacyGuest
+ ? { guestId: user.id }
+ : { userId: user.id }),
locale: user.locale ?? undefined,
},
include: {
@@ -260,7 +262,7 @@ export const participants = router({
participantId: participant.id,
hasEmail: !!email,
totalResponses,
- isCreator: ctx.user.isGuest
+ isCreator: ctx.user.isLegacyGuest
? participant.poll.guestId === ctx.user.id
: participant.poll.userId === ctx.user.id,
},
diff --git a/apps/web/src/trpc/server/create-ssr-helper.ts b/apps/web/src/trpc/server/create-ssr-helper.ts
index 73ee6ba40..d31d0c0a2 100644
--- a/apps/web/src/trpc/server/create-ssr-helper.ts
+++ b/apps/web/src/trpc/server/create-ssr-helper.ts
@@ -16,6 +16,7 @@ async function createContext(): Promise<TRPCContext> {
isGuest: session.user.isGuest,
locale: session.user.locale ?? undefined,
image: session.user.image ?? undefined,
+ isLegacyGuest: session.legacy && session.user.isGuest,
}
: undefined,
};
diff --git a/apps/web/src/utils/permissions.ts b/apps/web/src/utils/permissions.ts
index 32ba9381f..06e3455e5 100644
--- a/apps/web/src/utils/permissions.ts
+++ b/apps/web/src/utils/permissions.ts
@@ -3,7 +3,7 @@ export function isOwner(
user: { id: string; isGuest: boolean },
) {
if (user.isGuest) {
- return resource.guestId === user.id;
+ return resource.userId === user.id || resource.guestId === user.id;
}
return resource.userId === user.id;
diff --git a/packages/database/prisma/migrations/20251027170830_anonymous_user/migration.sql b/packages/database/prisma/migrations/20251027170830_anonymous_user/migration.sql
new file mode 100644
index 000000000..dc1c18928
--- /dev/null
+++ b/packages/database/prisma/migrations/20251027170830_anonymous_user/migration.sql
@@ -0,0 +1,2 @@
+-- AlterTable
+ALTER TABLE "users" ADD COLUMN "anonymous" BOOLEAN NOT NULL DEFAULT false;
diff --git a/packages/database/prisma/models/user.prisma b/packages/database/prisma/models/user.prisma
index 6c03173b8..673c3a356 100644
--- a/packages/database/prisma/models/user.prisma
+++ b/packages/database/prisma/models/user.prisma
@@ -54,6 +54,7 @@ model User {
banExpires DateTime? @map("ban_expires")
role UserRole @default(user)
lastLoginMethod String? @map("last_login_method")
+ isAnonymous Boolean @default(false) @map("anonymous")
comments Comment[]
polls Poll[]