Skip to content

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

✨ Add support for password-based login (#1977)

Luke Vella61b3451dd5c1
diff --git a/apps/web/package.json b/apps/web/package.json
index 34f8a83b2..d246c4ac7 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -58,6 +58,7 @@
"ai": "^5.0.41",
"arctic": "^3.7.0",
"autoprefixer": "^10.4.13",
+ "better-auth": "^1.3.27",
"calendar-link": "^2.6.0",
"class-variance-authority": "^0.7.1",
"color-hash": "^2.0.2",
@@ -102,7 +103,8 @@
"superjson": "^2.0.0",
"tailwindcss": "^3.4.17",
"timezone-soft": "^1.5.1",
- "zod": "^4.1.8"
+ "zod": "^4.1.8",
+ "zxcvbn": "^4.4.2"
},
"devDependencies": {
"@babel/core": "^7.26.10",
@@ -120,6 +122,7 @@
"@types/react-big-calendar": "^1.8.8",
"@types/react-dom": "19.1.2",
"@types/smoothscroll-polyfill": "^0.3.1",
+ "@types/zxcvbn": "^4.4.5",
"@vitejs/plugin-react": "^5.0.0",
"cheerio": "^1.0.0-rc.12",
"cross-env": "^7.0.3",
diff --git a/apps/web/public/locales/en/app.json b/apps/web/public/locales/en/app.json
index 1e89d5636..3564371a9 100644
--- a/apps/web/public/locales/en/app.json
+++ b/apps/web/public/locales/en/app.json
@@ -219,7 +219,6 @@
"profileEmailAddress": "Email Address",
"profileEmailAddressDescription": "Your email address is used to log in to your account",
"emailAlreadyInUse": "This email address is already associated with another account. Please use a different email address.",
- "continueWith": "Continue with {provider}",
"continueWithProvider": "Continue with {provider}",
"loginFooter": "Don't have an account? <a>Sign up</a>",
"back": "Back",
@@ -245,7 +244,6 @@
"createAccount": "Create Account",
"tooManyRequests": "Too many requests",
"tooManyRequestsDescription": "Please try again later.",
- "loginMagicLinkError": "This link is invalid or expired. Please request a new link.",
"billingSubscriptionDescription": "Manage your current subscription plan.",
"subscriptionStatusActive": "Active",
"subscriptionStatusTrialing": "Trialing",
@@ -296,8 +294,6 @@
"giveFeedback": "Give feedback",
"homeActionsTitle": "Actions",
"dismissFeedback": "Don't show again",
- "tooManyAttempts": "Too many attempts, please try again later.",
- "unknownError": "Something went wrong",
"livePollCount": "{count} live",
"upcomingEventCount": "{count} upcoming",
"adminSetupCta": "Make me an admin",
@@ -524,5 +520,49 @@
"connectMicrosoftCalendar": "Microsoft Calendar",
"settingDefaultCalendar": "Setting default calendar...",
"defaultCalendarSetSuccess": "Default calendar set successfully",
- "defaultCalendarSetError": "Failed to set default calendar"
+ "defaultCalendarSetError": "Failed to set default calendar",
+ "authErrorsOAuthSignInFailed": "An error occurred while signing in. Please try again or contact the system administrator.",
+ "password": "Password",
+ "forgotPasswordSubmitted": "Check your email",
+ "forgotPasswordSubmittedMessage": "If an account exists with this email address, we've sent a password reset link to your inbox. Please check your email and follow the link to reset your password.",
+ "sendResetLink": "Send reset link",
+ "forgotPasswordTitle": "Forgot Password",
+ "forgotPasswordDescription": "Enter your email address and we'll send you a link to reset your password.",
+ "forgotPasswordFooter": "Remember your password? <a>Back to login</a>",
+ "forgotPassword": "Forgot Password?",
+ "resetPasswordInvalidTokenMessage": "The password reset link is invalid or has expired. Please request a new one.",
+ "newPassword": "New Password",
+ "resetPasswordTitle": "Reset Password",
+ "resetPasswordDescription": "Enter your new password below",
+ "resetPasswordFooter": "Don't need to reset? <a>Back to login</a>",
+ "passwordOrEmailIncorrect": "Invalid email or password",
+ "security": "Security",
+ "currentPassword": "Current Password",
+ "changePassword": "Change Password",
+ "passwordRequired": "Password is required",
+ "passwordChangedSuccess": "Your password has been changed successfully",
+ "securityDescription": "Manage your account security and password settings",
+ "changePasswordDescription": "Update your password to keep your account secure",
+ "passwordIncorrect": "Current password is incorrect",
+ "passwordSetupSuccess": "A password reset link has been sent to your email. Follow the link to set your password.",
+ "loginWithPassword": "Login with password",
+ "continueWithEmail": "Continue with email",
+ "loginWithEmail": "Login with email",
+ "passwordSetupSuccessful": "Password setup successful. You can now login with your email and password.",
+ "setupPasswordDescription": "Your account doesn't have a password yet. Click the button below to send a secure link to your email to set a password.",
+ "setupPasswordAlertTitle": "Login quicker with a password",
+ "setupPasswordAlertDesc": "Set up a password to make logging in faster and more convenient.",
+ "dismissPasswordSetup": "Don't show again",
+ "setupPasswordButton": "Set up password",
+ "invalidName": "Please enter a valid name, not a URL, email, or phone number",
+ "invalidEmail": "Please enter a valid email address",
+ "passwordsMustBeDifferent": "New password must be different from current password",
+ "passwordStrengthVeryWeak": "Very weak",
+ "passwordStrengthWeak": "Weak",
+ "passwordStrengthFair": "Fair",
+ "passwordStrengthGood": "Good",
+ "passwordStrengthStrong": "Strong",
+ "passwordTooWeak": "Password is too weak. Please use a stronger password.",
+ "resetPasswordButton": "Reset password",
+ "passwordStrength": "Password Strength"
}
diff --git a/apps/web/src/actions/track-poll-view.ts b/apps/web/src/actions/track-poll-view.ts
index 0cf6b527d..a74970f91 100644
--- a/apps/web/src/actions/track-poll-view.ts
+++ b/apps/web/src/actions/track-poll-view.ts
@@ -2,8 +2,7 @@
import { prisma } from "@rallly/database";
import { headers } from "next/headers";
-
-import { getUserId } from "@/next-auth";
+import { getUserIdIfLoggedIn } from "@/lib/auth";
/**
* Server action to track a poll view
@@ -15,7 +14,8 @@ export async function trackPollView(pollId: string) {
const userAgent = headersList.get("user-agent");
const ip = headersList.get("x-forwarded-for") || "unknown";
- const userId = await getUserId();
+ const userId = await getUserIdIfLoggedIn();
+
await prisma.pollView.create({
data: {
pollId,
diff --git a/apps/web/src/app/[locale]/(auth)/auth/login/components/login-page.tsx b/apps/web/src/app/[locale]/(auth)/auth/login/components/login-page.tsx
index 60d1cf360..66ab50c59 100644
--- a/apps/web/src/app/[locale]/(auth)/auth/login/components/login-page.tsx
+++ b/apps/web/src/app/[locale]/(auth)/auth/login/components/login-page.tsx
@@ -1,6 +1,5 @@
"use client";
import { Button } from "@rallly/ui/button";
-import { useMutation } from "@tanstack/react-query";
import { useRouter } from "next/navigation";
import React from "react";
@@ -8,33 +7,13 @@ import { Logo } from "@/components/logo";
import { OptimizedAvatarImage } from "@/components/optimized-avatar-image";
import { Skeleton } from "@/components/skeleton";
import { Trans } from "@/components/trans";
-import { useTranslation } from "@/i18n/client";
+import { authClient } from "@/lib/auth-client";
import { trpc } from "@/trpc/client";
-type PageProps = { magicLink: string; email: string };
-
-export const LoginPage = ({ magicLink, email }: PageProps) => {
- const { t } = useTranslation();
+export const LoginPage = ({ email, code }: { email: string; code: string }) => {
const [error, setError] = React.useState<string | null>(null);
+ const [isLoading, setLoading] = React.useState(false);
- const magicLinkFetch = useMutation({
- mutationFn: async () => {
- const res = await fetch(magicLink);
- return res;
- },
- onSuccess: async (data) => {
- if (!data.url.includes("auth/error")) {
- router.push(data.url);
- } else {
- setError(
- t("loginMagicLinkError", {
- defaultValue:
- "This link is invalid or expired. Please request a new link.",
- }),
- );
- }
- },
- });
const { data } = trpc.user.getByEmail.useQuery({ email });
const router = useRouter();
return (
@@ -64,9 +43,24 @@ export const LoginPage = ({ magicLink, email }: PageProps) => {
<div>
<Button
size="lg"
- loading={magicLinkFetch.isPending}
+ loading={isLoading}
onClick={async () => {
- await magicLinkFetch.mutateAsync();
+ setLoading(true);
+ setError(null);
+
+ try {
+ const res = await authClient.signIn.emailOtp({
+ email,
+ otp: code,
+ });
+ if (res.error) {
+ setError(res.error.message ?? "An error occurred");
+ } else {
+ router.push("/");
+ }
+ } finally {
+ setLoading(false);
+ }
}}
variant="primary"
className="w-full"
diff --git a/apps/web/src/app/[locale]/(auth)/auth/login/page.tsx b/apps/web/src/app/[locale]/(auth)/auth/login/page.tsx
index 23c078261..6107b0ba1 100644
--- a/apps/web/src/app/[locale]/(auth)/auth/login/page.tsx
+++ b/apps/web/src/app/[locale]/(auth)/auth/login/page.tsx
@@ -9,16 +9,12 @@ import { LoginPage } from "./components/login-page";
export const dynamic = "force-dynamic";
const searchParamsSchema = z.object({
- magicLink: z.url(),
+ email: z.email(),
+ code: z.string(),
});
type SearchParams = z.infer<typeof searchParamsSchema>;
-const magicLinkParams = z.object({
- email: z.email(),
- token: z.string(),
-});
-
export default async function Page(props: {
searchParams: Promise<SearchParams>;
}) {
@@ -29,21 +25,9 @@ export default async function Page(props: {
return notFound();
}
- const { magicLink } = parse.data;
-
- const url = new URL(magicLink);
-
- const parseMagicLink = magicLinkParams.safeParse(
- Object.fromEntries(url.searchParams),
- );
-
- if (!parseMagicLink.success) {
- return notFound();
- }
-
- const { email } = parseMagicLink.data;
+ const { email, code } = parse.data;
- return <LoginPage magicLink={magicLink} email={email} />;
+ return <LoginPage email={email} code={code} />;
}
export async function generateMetadata(props: {
diff --git a/apps/web/src/app/[locale]/(auth)/components/link-with-redirect-to.tsx b/apps/web/src/app/[locale]/(auth)/components/link-with-redirect-to.tsx
index d31264423..aeee3a0e8 100644
--- a/apps/web/src/app/[locale]/(auth)/components/link-with-redirect-to.tsx
+++ b/apps/web/src/app/[locale]/(auth)/components/link-with-redirect-to.tsx
@@ -2,6 +2,7 @@
import Link from "next/link";
import { useSearchParams } from "next/navigation";
+import { validateRedirectUrl } from "@/utils/redirect";
export function LinkWithRedirectTo({
href,
@@ -13,14 +14,16 @@ export function LinkWithRedirectTo({
children?: React.ReactNode;
}) {
const searchParams = useSearchParams();
- const redirectTo = searchParams.get("redirectTo");
+ const validatedRedirectTo = validateRedirectUrl(
+ searchParams.get("redirectTo"),
+ );
return (
<Link
className={className}
href={
- redirectTo
- ? `${href}?redirectTo=${encodeURIComponent(redirectTo)}`
+ validatedRedirectTo
+ ? `${href}?redirectTo=${encodeURIComponent(validatedRedirectTo)}`
: href
}
>
diff --git a/apps/web/src/app/[locale]/(auth)/forgot-password/components/forgot-password-form.tsx b/apps/web/src/app/[locale]/(auth)/forgot-password/components/forgot-password-form.tsx
new file mode 100644
index 000000000..6a11979a6
--- /dev/null
+++ b/apps/web/src/app/[locale]/(auth)/forgot-password/components/forgot-password-form.tsx
@@ -0,0 +1,121 @@
+"use client";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { Button } from "@rallly/ui/button";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@rallly/ui/form";
+import { Input } from "@rallly/ui/input";
+import { useSearchParams } from "next/navigation";
+import React from "react";
+import { useForm } from "react-hook-form";
+import { useTranslation } from "react-i18next";
+import { z } from "zod";
+
+import { Trans } from "@/components/trans";
+import { authClient } from "@/lib/auth-client";
+
+function useForgotPasswordSchema() {
+ const { t } = useTranslation();
+ return React.useMemo(() => {
+ return z.object({
+ email: z.email(t("validEmail")),
+ });
+ }, [t]);
+}
+
+type ForgotPasswordValues = z.infer<ReturnType<typeof useForgotPasswordSchema>>;
+
+export function ForgotPasswordForm() {
+ const searchParams = useSearchParams();
+ const emailFromUrl = searchParams?.get("email") || "";
+ const forgotPasswordSchema = useForgotPasswordSchema();
+ const [submitted, setSubmitted] = React.useState(false);
+ const form = useForm<ForgotPasswordValues>({
+ defaultValues: {
+ email: emailFromUrl,
+ },
+ resolver: zodResolver(forgotPasswordSchema),
+ });
+ const { handleSubmit, formState } = form;
+ const { t } = useTranslation();
+
+ if (submitted) {
+ return (
+ <div className="rounded-lg border border-border bg-muted/50 p-4 text-muted-foreground text-sm">
+ <p className="font-medium text-foreground">
+ <Trans
+ i18nKey="forgotPasswordSubmitted"
+ defaults="Check your email"
+ />
+ </p>
+ <p className="mt-2">
+ <Trans
+ i18nKey="forgotPasswordSubmittedMessage"
+ defaults="If an account exists with this email address, we've sent a password reset link to your inbox. Please check your email and follow the link to reset your password."
+ />
+ </p>
+ </div>
+ );
+ }
+
+ return (
+ <Form {...form}>
+ <form
+ className="space-y-4"
+ onSubmit={handleSubmit(async ({ email }) => {
+ const res = await authClient.requestPasswordReset({
+ email,
+ redirectTo: "/reset-password",
+ });
+
+ if (res.error) {
+ form.setError("email", {
+ message: res.error.message,
+ });
+ return;
+ }
+
+ setSubmitted(true);
+ })}
+ >
+ <FormField
+ control={form.control}
+ name="email"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>{t("email")}</FormLabel>
+ <FormControl>
+ <Input
+ {...field}
+ size="lg"
+ type="email"
+ disabled={formState.isSubmitting}
+ autoFocus={true}
+ placeholder={t("emailPlaceholder")}
+ error={!!formState.errors.email}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <div>
+ <Button
+ size="lg"
+ loading={form.formState.isSubmitting}
+ type="submit"
+ className="w-full"
+ variant="primary"
+ >
+ <Trans i18nKey="sendResetLink" defaults="Send reset link" />
+ </Button>
+ </div>
+ </form>
+ </Form>
+ );
+}
diff --git a/apps/web/src/app/[locale]/(auth)/forgot-password/page.tsx b/apps/web/src/app/[locale]/(auth)/forgot-password/page.tsx
new file mode 100644
index 000000000..71c4fd162
--- /dev/null
+++ b/apps/web/src/app/[locale]/(auth)/forgot-password/page.tsx
@@ -0,0 +1,64 @@
+import type { Metadata } from "next";
+import { notFound, redirect } from "next/navigation";
+import { Trans } from "@/components/trans";
+import { env } from "@/env";
+import { getTranslation } from "@/i18n/server";
+import { getSession } from "@/lib/auth";
+import {
+ AuthPageContainer,
+ AuthPageContent,
+ AuthPageDescription,
+ AuthPageExternal,
+ AuthPageHeader,
+ AuthPageTitle,
+} from "../components/auth-page";
+import { LinkWithRedirectTo } from "../components/link-with-redirect-to";
+import { ForgotPasswordForm } from "./components/forgot-password-form";
+
+export default async function ForgotPasswordPage() {
+ if (env.EMAIL_LOGIN_ENABLED === "false") {
+ notFound();
+ }
+ const session = await getSession();
+ if (session && !session.user?.isGuest) {
+ return redirect("/");
+ }
+
+ return (
+ <AuthPageContainer>
+ <AuthPageHeader>
+ <AuthPageTitle>
+ <Trans i18nKey="forgotPasswordTitle" defaults="Forgot Password" />
+ </AuthPageTitle>
+ <AuthPageDescription>
+ <Trans
+ i18nKey="forgotPasswordDescription"
+ defaults="Enter your email address and we'll send you a link to reset your password."
+ />
+ </AuthPageDescription>
+ </AuthPageHeader>
+ <AuthPageContent>
+ <ForgotPasswordForm />
+ </AuthPageContent>
+ <AuthPageExternal>
+ <Trans
+ i18nKey="forgotPasswordFooter"
+ defaults="Remember your password? <a>Back to login</a>"
+ components={{
+ a: <LinkWithRedirectTo className="text-link" href="/login" />,
+ }}
+ />
+ </AuthPageExternal>
+ </AuthPageContainer>
+ );
+}
+
+export async function generateMetadata(props: {
+ params: Promise<{ locale: string }>;
+}): Promise<Metadata> {
+ const params = await props.params;
+ const { t } = await getTranslation(params.locale);
+ return {
+ title: t("forgotPassword", { defaultValue: "Forgot Password" }),
+ };
+}
diff --git a/apps/web/src/app/[locale]/(auth)/login/actions.ts b/apps/web/src/app/[locale]/(auth)/login/actions.ts
index 733b2ee10..9c6822597 100644
--- a/apps/web/src/app/[locale]/(auth)/login/actions.ts
+++ b/apps/web/src/app/[locale]/(auth)/login/actions.ts
@@ -1,6 +1,12 @@
"use server";
+import { prisma } from "@rallly/database";
import { cookies } from "next/headers";
+import z from "zod";
+import {
+ actionClient,
+ createRateLimitMiddleware,
+} from "@/lib/safe-action/server";
export async function setVerificationEmail(email: string) {
const cookieStore = await cookies();
@@ -12,3 +18,30 @@ export async function setVerificationEmail(email: string) {
maxAge: 15 * 60,
});
}
+
+export const getLoginMethodAction = actionClient
+ .metadata({ actionName: "get_login_method" })
+ .inputSchema(z.object({ email: z.email() }))
+ .use(createRateLimitMiddleware(100, "1m"))
+ .action(async ({ parsedInput: { email } }) => {
+ const user = await prisma.user.findUnique({
+ where: { email },
+ select: {
+ emailVerified: true,
+ accounts: {
+ select: {
+ provider: true,
+ },
+ },
+ },
+ });
+
+ if (
+ user?.emailVerified &&
+ user?.accounts.some((account) => account.provider === "credential")
+ ) {
+ return { method: "credential" as const };
+ }
+
+ return { method: "email" as const };
+ });
diff --git a/apps/web/src/app/[locale]/(auth)/login/components/auth-errors.tsx b/apps/web/src/app/[locale]/(auth)/login/components/auth-errors.tsx
index 6198a5cda..a3e5a2a8f 100644
--- a/apps/web/src/app/[locale]/(auth)/login/components/auth-errors.tsx
+++ b/apps/web/src/app/[locale]/(auth)/login/components/auth-errors.tsx
@@ -52,6 +52,15 @@ export function AuthErrors() {
})}
</p>
);
+ case "OAuthSignInFailed":
+ return (
+ <p className="text-destructive text-sm">
+ {t("authErrorsOAuthSignInFailed", {
+ defaultValue:
+ "An error occurred while signing in. Please try again or contact the system administrator.",
+ })}
+ </p>
+ );
default:
return null;
}
diff --git a/apps/web/src/app/[locale]/(auth)/login/components/login-email-form.tsx b/apps/web/src/app/[locale]/(auth)/login/components/login-email-form.tsx
index 7f6aed4bd..5d060f34e 100644
--- a/apps/web/src/app/[locale]/(auth)/login/components/login-email-form.tsx
+++ b/apps/web/src/app/[locale]/(auth)/login/components/login-email-form.tsx
@@ -10,21 +10,28 @@ import {
FormMessage,
} from "@rallly/ui/form";
import { Input } from "@rallly/ui/input";
+import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
-import { signIn } from "next-auth/react";
import React from "react";
import { useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { z } from "zod";
-import { setVerificationEmail } from "@/app/[locale]/(auth)/login/actions";
+import {
+ getLoginMethodAction,
+ setVerificationEmail,
+} from "@/app/[locale]/(auth)/login/actions";
import { Trans } from "@/components/trans";
+import { authClient } from "@/lib/auth-client";
+import { useSafeAction } from "@/lib/safe-action/client";
+import { validateRedirectUrl } from "@/utils/redirect";
function useLoginWithEmailSchema() {
const { t } = useTranslation();
return React.useMemo(() => {
return z.object({
identifier: z.email(t("validEmail")),
+ password: z.string().optional(),
});
}, [t]);
}
@@ -35,47 +42,106 @@ export function LoginWithEmailForm() {
const router = useRouter();
const loginWithEmailSchema = useLoginWithEmailSchema();
const searchParams = useSearchParams();
+ const [showPasswordField, setShowPasswordField] = React.useState(false);
const form = useForm<LoginWithEmailValues>({
defaultValues: {
identifier: "",
+ password: "",
},
resolver: zodResolver(loginWithEmailSchema),
});
const { handleSubmit, formState } = form;
const { t } = useTranslation();
+ const { executeAsync: getLoginMethod } = useSafeAction(getLoginMethodAction);
+
+ const isPasswordLogin = showPasswordField && !!form.watch("password");
+
return (
<Form {...form}>
<form
className="space-y-4"
- onSubmit={handleSubmit(async ({ identifier }) => {
- try {
- const res = await signIn("email", {
+ onSubmit={handleSubmit(async ({ identifier, password }) => {
+ const validatedRedirectTo = validateRedirectUrl(
+ searchParams?.get("redirectTo"),
+ );
+
+ if (password) {
+ const res = await authClient.signIn.email({
+ email: identifier,
+ password,
+ });
+
+ if (res.error) {
+ switch (res.error.code) {
+ case "INVALID_EMAIL_OR_PASSWORD":
+ form.setError("password", {
+ message: t("passwordOrEmailIncorrect", {
+ defaultValue: "Invalid email or password",
+ }),
+ });
+ break;
+ default:
+ form.setError("password", {
+ message: res.error.message,
+ });
+ break;
+ }
+ return;
+ }
+
+ router.push(validatedRedirectTo ?? "/");
+
+ return;
+ } else {
+ if (!showPasswordField) {
+ const res = await getLoginMethod({
+ email: identifier,
+ });
+
+ if (res.data?.method === "credential") {
+ // show password field
+ setShowPasswordField(true);
+ return;
+ }
+ }
+
+ const res = await authClient.emailOtp.sendVerificationOtp({
email: identifier,
- redirectTo: searchParams?.get("redirectTo") ?? undefined,
- redirect: false,
+ type: "email-verification",
});
- if (res?.error) {
- throw new Error(res.error);
+ if (res.error) {
+ switch (res.error.code) {
+ case "USER_NOT_FOUND":
+ form.setError("identifier", {
+ message: t("userNotFound"),
+ });
+ break;
+ case "EMAIL_BLOCKED":
+ form.setError("identifier", {
+ message: t("authErrorsEmailBlocked"),
+ });
+ break;
+ default:
+ form.setError("identifier", {
+ message: res.error.message,
+ });
+ break;
+ }
+ return;
}
await setVerificationEmail(identifier);
// redirect to verify page with redirectTo
- const redirectTo = searchParams?.get("redirectTo");
+
router.push(
`/login/verify${
- redirectTo
- ? `?redirectTo=${encodeURIComponent(redirectTo)}`
+ validatedRedirectTo
+ ? `?redirectTo=${encodeURIComponent(validatedRedirectTo)}`
: ""
}`,
);
- } catch (_e) {
- form.setError("identifier", {
- message: t("userNotFound", {
- defaultValue: "A user with that email doesn't exist",
- }),
- });
}
})}
>
@@ -84,19 +150,15 @@ export function LoginWithEmailForm() {
name="identifier"
render={({ field }) => (
<FormItem>
- <FormLabel className="sr-only">{t("email")}</FormLabel>
+ <FormLabel>{t("email")}</FormLabel>
<FormControl>
<Input
{...field}
size="lg"
type="text"
- data-1p-ignore
- disabled={
- formState.isSubmitting || formState.isSubmitSuccessful
- }
+ disabled={formState.isSubmitting}
autoFocus={true}
placeholder={t("emailPlaceholder")}
- autoComplete="false"
error={!!formState.errors.identifier}
/>
</FormControl>
@@ -104,21 +166,73 @@ export function LoginWithEmailForm() {
</FormItem>
)}
/>
+ {showPasswordField ? (
+ <FormField
+ control={form.control}
+ name="password"
+ render={({ field }) => (
+ <FormItem>
+ <div className="flex items-center justify-between">
+ <FormLabel>
+ <Trans i18nKey="password" defaults="Password" />
+ <span className="ml-1 text-muted-foreground text-xs">
+ <Trans i18nKey="optionalLabel" defaults="(Optional)" />
+ </span>
+ </FormLabel>
+ <Link
+ href={`/forgot-password?email=${encodeURIComponent(
+ form.watch("identifier"),
+ )}`}
+ className="text-muted-foreground text-sm hover:underline"
+ >
+ <Trans
+ i18nKey="forgotPassword"
+ defaults="Forgot password?"
+ />
+ </Link>
+ </div>
+
+ <FormControl>
+ <Input
+ autoFocus={true}
+ size="lg"
+ type="password"
+ disabled={form.formState.isSubmitting}
+ placeholder="••••••••"
+ {...field}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ ) : null}
+ {form.formState.errors.root?.message ? (
+ <FormMessage>{form.formState.errors.root.message}</FormMessage>
+ ) : null}
<div>
<Button
size="lg"
- loading={
- form.formState.isSubmitting || formState.isSubmitSuccessful
- }
+ loading={form.formState.isSubmitting}
type="submit"
className="w-full"
variant="primary"
>
- <Trans
- i18nKey="continueWith"
- defaults="Continue with {provider}"
- values={{ provider: t("email") }}
- />
+ {showPasswordField ? (
+ isPasswordLogin ? (
+ <Trans
+ i18nKey="loginWithPassword"
+ defaults="Login with password"
+ />
+ ) : (
+ <Trans i18nKey="loginWithEmail" defaults="Login with email" />
+ )
+ ) : (
+ <Trans
+ i18nKey="continueWithEmail"
+ defaults="Continue with email"
+ />
+ )}
</Button>
</div>
</form>
diff --git a/apps/web/src/app/[locale]/(auth)/login/components/login-with-oidc.tsx b/apps/web/src/app/[locale]/(auth)/login/components/login-with-oidc.tsx
index 7e74d6ad8..08514d528 100644
--- a/apps/web/src/app/[locale]/(auth)/login/components/login-with-oidc.tsx
+++ b/apps/web/src/app/[locale]/(auth)/login/components/login-with-oidc.tsx
@@ -1,8 +1,9 @@
"use client";
import { Button } from "@rallly/ui/button";
-import { signIn } from "next-auth/react";
import { Trans } from "@/components/trans";
+import { authClient } from "@/lib/auth-client";
+import { validateRedirectUrl } from "@/utils/redirect";
export function LoginWithOIDC({
name,
@@ -14,8 +15,10 @@ export function LoginWithOIDC({
return (
<Button
onClick={() => {
- signIn("oidc", {
- redirectTo,
+ authClient.signIn.oauth2({
+ providerId: "oidc",
+ callbackURL: validateRedirectUrl(redirectTo) || "/",
+ errorCallbackURL: "/login?error=OAuthSignInFailed",
});
}}
className="w-full"
diff --git a/apps/web/src/app/[locale]/(auth)/login/components/sso-provider.tsx b/apps/web/src/app/[locale]/(auth)/login/components/sso-provider.tsx
index 7c7c3e84c..b1e5b54c5 100644
--- a/apps/web/src/app/[locale]/(auth)/login/components/sso-provider.tsx
+++ b/apps/web/src/app/[locale]/(auth)/login/components/sso-provider.tsx
@@ -3,10 +3,11 @@ import { Button } from "@rallly/ui/button";
import { Icon } from "@rallly/ui/icon";
import { UserIcon } from "lucide-react";
import Image from "next/image";
-import { signIn } from "next-auth/react";
import { Trans } from "@/components/trans";
import { useTranslation } from "@/i18n/client";
+import { authClient } from "@/lib/auth-client";
+import { validateRedirectUrl } from "@/utils/redirect";
function SSOImage({ provider }: { provider: string }) {
if (provider === "google") {
@@ -15,7 +16,7 @@ function SSOImage({ provider }: { provider: string }) {
);
}
- if (provider === "microsoft-entra-id") {
+ if (provider === "microsoft-entra-id" || provider === "microsoft") {
return (
<Image
src="/static/microsoft.svg"
@@ -57,8 +58,9 @@ export function SSOProvider({
})}
key={providerId}
onClick={() => {
- signIn(providerId, {
- redirectTo,
+ authClient.signIn.social({
+ provider: providerId,
+ callbackURL: validateRedirectUrl(redirectTo) || "/",
});
}}
>
diff --git a/apps/web/src/app/[locale]/(auth)/login/page.tsx b/apps/web/src/app/[locale]/(auth)/login/page.tsx
index 9ac740cb4..a421646f3 100644
--- a/apps/web/src/app/[locale]/(auth)/login/page.tsx
+++ b/apps/web/src/app/[locale]/(auth)/login/page.tsx
@@ -1,10 +1,9 @@
import type { Metadata } from "next";
+import { redirect } from "next/navigation";
import { Trans } from "react-i18next/TransWithoutContext";
-
-import { GoogleProvider } from "@/auth/providers/google";
-import { MicrosoftProvider } from "@/auth/providers/microsoft";
-import { OIDCProvider } from "@/auth/providers/oidc";
+import { env } from "@/env";
import { getTranslation } from "@/i18n/server";
+import { authLib, getSession } from "@/lib/auth";
import { isFeatureEnabled } from "@/lib/feature-flags/server";
import { getRegistrationEnabled } from "@/utils/get-registration-enabled";
import {
@@ -40,16 +39,20 @@ export default async function LoginPage(props: {
}>;
}) {
const searchParams = await props.searchParams;
-
+ const session = await getSession();
+ if (session && !session.user?.isGuest) {
+ return redirect("/");
+ }
const { isRegistrationEnabled, t } = await loadData();
const isEmailLoginEnabled = isFeatureEnabled("emailLogin");
- const oidcProvider = OIDCProvider();
- const socialProviders = [GoogleProvider(), MicrosoftProvider()].filter(
- Boolean,
- );
- const hasAlternateLoginMethods = [...socialProviders, oidcProvider].some(
- Boolean,
+
+ const hasGoogleProvider = !!authLib.options.socialProviders.google;
+ const hasMicrosoftProvider = !!authLib.options.socialProviders.microsoft;
+ const hasOidc = !!authLib.options.plugins.find(
+ (plugin) => plugin.id === "generic-oauth",
);
+ const hasAlternateLoginMethods =
+ hasGoogleProvider || hasMicrosoftProvider || hasOidc;
return (
<AuthPageContainer>
@@ -78,26 +81,28 @@ export default async function LoginPage(props: {
<AuthPageContent>
{isEmailLoginEnabled && <LoginWithEmailForm />}
{isEmailLoginEnabled && hasAlternateLoginMethods ? <OrDivider /> : null}
- {oidcProvider ? (
- <LoginWithOIDC
- name={oidcProvider.name}
- redirectTo={searchParams?.redirectTo}
- />
- ) : null}
- {socialProviders ? (
- <div className="grid gap-4">
- {socialProviders.map((provider) =>
- provider ? (
- <SSOProvider
- key={provider.id}
- providerId={provider.id}
- name={provider.options?.name || provider.name}
- redirectTo={searchParams?.redirectTo}
- />
- ) : null,
- )}
- </div>
- ) : null}
+ <div className="grid gap-3">
+ {hasOidc ? (
+ <LoginWithOIDC
+ name={env.OIDC_NAME}
+ redirectTo={searchParams?.redirectTo}
+ />
+ ) : null}
+ {hasGoogleProvider ? (
+ <SSOProvider
+ providerId="google"
+ name="Google"
+ redirectTo={searchParams?.redirectTo}
+ />
+ ) : null}
+ {hasMicrosoftProvider ? (
+ <SSOProvider
+ providerId="microsoft"
+ name="Microsoft"
+ redirectTo={searchParams?.redirectTo}
+ />
+ ) : null}
+ </div>
</AuthPageContent>
<AuthErrors />
{isRegistrationEnabled ? (
diff --git a/apps/web/src/app/[locale]/(auth)/login/verify/components/otp-form.tsx b/apps/web/src/app/[locale]/(auth)/login/verify/components/otp-form.tsx
index b29ccfcdb..b600a7b7c 100644
--- a/apps/web/src/app/[locale]/(auth)/login/verify/components/otp-form.tsx
+++ b/apps/web/src/app/[locale]/(auth)/login/verify/components/otp-form.tsx
@@ -16,7 +16,8 @@ import { z } from "zod";
import { Trans } from "@/components/trans";
import { useTranslation } from "@/i18n/client";
-
+import { authClient } from "@/lib/auth-client";
+import { validateRedirectUrl } from "@/utils/redirect";
import { InputOTP } from "../../../../../../components/input-otp";
const otpFormSchema = z.object({
@@ -36,41 +37,26 @@ export function OTPForm({ email }: { email: string }) {
const searchParams = useSearchParams();
const handleSubmit = form.handleSubmit(async (data) => {
- const url = `${
- window.location.origin
- }/api/auth/callback/email?email=${encodeURIComponent(email.toLowerCase())}&token=${data.otp}`;
-
- const res = await fetch(url);
+ const res = await authClient.emailOtp.verifyEmail({
+ email,
+ otp: data.otp,
+ });
- if (!res.ok) {
- switch (res.status) {
- case 429:
+ if (res.error) {
+ switch (res.error.code) {
+ case "INVALID_OTP":
form.setError("otp", {
- message: t("tooManyAttempts", {
- defaultValue: "Too many attempts, please try again later.",
- }),
+ message: t("wrongVerificationCode"),
});
- break;
+ return;
default:
form.setError("otp", {
- message: t("unknownError", {
- defaultValue: "Something went wrong",
- }),
+ message: res.error.message,
});
- break;
}
} else {
- const resUrl = new URL(res.url);
- const hasError = !!resUrl.searchParams.get("error");
- if (hasError) {
- form.setError("otp", {
- message: t("wrongVerificationCode", {
- defaultValue: "The code you entered is incorrect",
- }),
- });
- } else {
- window.location.href = searchParams?.get("redirectTo") ?? "/";
- }
+ window.location.href =
+ validateRedirectUrl(searchParams?.get("redirectTo")) ?? "/";
}
});
diff --git a/apps/web/src/app/[locale]/(auth)/register/components/register-name-form.tsx b/apps/web/src/app/[locale]/(auth)/register/components/register-name-form.tsx
index a834f9a84..6cbc0da3f 100644
--- a/apps/web/src/app/[locale]/(auth)/register/components/register-name-form.tsx
+++ b/apps/web/src/app/[locale]/(auth)/register/components/register-name-form.tsx
@@ -10,65 +10,95 @@ import {
FormMessage,
} from "@rallly/ui/form";
import { Input } from "@rallly/ui/input";
+import { PasswordInput } from "@rallly/ui/password-input";
+import { absoluteUrl } from "@rallly/utils/absolute-url";
import { useRouter, useSearchParams } from "next/navigation";
import { useForm } from "react-hook-form";
-import type { z } from "zod";
-
+import { setVerificationEmail } from "@/app/[locale]/(auth)/login/actions";
import { Trans } from "@/components/trans";
+import { PasswordStrengthMeter } from "@/features/password/components/password-strength-meter";
import { useTranslation } from "@/i18n/client";
-import { trpc } from "@/trpc/client";
-
-import { setToken } from "../actions";
-import { registerNameFormSchema } from "./schema";
-
-type RegisterNameFormValues = z.infer<typeof registerNameFormSchema>;
+import { authClient } from "@/lib/auth-client";
+import { getBrowserTimeZone } from "@/utils/date-time-utils";
+import { validateRedirectUrl } from "@/utils/redirect";
+import { useRegisterNameFormSchema } from "./schema";
export function RegisterNameForm() {
- const { t } = useTranslation();
+ const schema = useRegisterNameFormSchema();
+ const { t, i18n } = useTranslation();
const searchParams = useSearchParams();
- const form = useForm<RegisterNameFormValues>({
+ const router = useRouter();
+ const form = useForm({
defaultValues: {
name: "",
email: "",
+ password: "",
},
- resolver: zodResolver(registerNameFormSchema),
+ resolver: zodResolver(schema),
});
- const registerUser = trpc.auth.requestRegistration.useMutation();
- const router = useRouter();
return (
<Form {...form}>
<form
onSubmit={form.handleSubmit(async (data) => {
- const res = await registerUser.mutateAsync(data);
+ const validatedRedirectTo = validateRedirectUrl(
+ searchParams.get("redirectTo"),
+ );
+
+ const verifyURL = absoluteUrl(
+ `/login/verify${
+ validatedRedirectTo
+ ? `?redirectTo=${encodeURIComponent(validatedRedirectTo)}`
+ : ""
+ }`,
+ );
+
+ try {
+ const res = await authClient.signUp.email({
+ email: data.email,
+ password: data.password,
+ name: data.name,
+ timeZone: getBrowserTimeZone(),
+ locale: i18n.language,
+ callbackURL: verifyURL,
+ });
- if (res.ok) {
- await setToken(res.token);
- const redirectTo = searchParams.get("redirectTo");
- router.push(
- `/register/verify${redirectTo ? `?redirectTo=${redirectTo}` : ""}`,
- );
- } else {
- switch (res.reason) {
- case "emailNotAllowed":
- form.setError("email", {
- message: t("emailNotAllowed"),
- });
- break;
- case "temporaryEmailNotAllowed":
- form.setError("email", {
- message: t("temporaryEmailNotAllowed", {
- defaultValue:
- "Temporary or disposable email addresses are not allowed.",
- }),
- });
- break;
- case "userAlreadyExists":
- form.setError("email", {
- message: t("userAlreadyExists"),
- });
- break;
+ if (res.error) {
+ switch (res.error.code) {
+ case "USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL":
+ form.setError("email", {
+ message: t("userAlreadyExists"),
+ });
+ break;
+ case "EMAIL_BLOCKED":
+ form.setError("email", {
+ message: t("emailNotAllowed"),
+ });
+ break;
+ case "TEMPORARY_EMAIL_NOT_ALLOWED":
+ form.setError("email", {
+ message: t("temporaryEmailNotAllowed"),
+ });
+ break;
+ default:
+ form.setError("email", {
+ message: res.error.message,
+ });
+ break;
+ }
}
+
+ if (res.data?.user?.email) {
+ await setVerificationEmail(res.data.user.email);
+ router.push(verifyURL);
+ }
+ } catch (error) {
+ if (error instanceof Error) {
+ form.setError("root", {
+ message: error.message,
+ });
+ }
+ console.error(error);
}
})}
>
@@ -117,12 +147,38 @@ export function RegisterNameForm() {
</FormItem>
)}
/>
+ <FormField
+ control={form.control}
+ name="password"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>
+ <Trans i18nKey="password" defaults="Password" />
+ </FormLabel>
+ <FormControl>
+ <PasswordInput
+ size="lg"
+ placeholder="••••••••"
+ disabled={form.formState.isSubmitting}
+ {...field}
+ type="password"
+ />
+ </FormControl>
+ <PasswordStrengthMeter
+ password={field.value}
+ className="mt-2"
+ />
+ <FormMessage />
+ </FormItem>
+ )}
+ />
</div>
+ {form.formState.errors.root?.message ? (
+ <FormMessage>{form.formState.errors.root.message}</FormMessage>
+ ) : null}
<div className="mt-6">
<Button
- loading={
- form.formState.isSubmitting || form.formState.isSubmitSuccessful
- }
+ loading={form.formState.isSubmitting}
className="w-full"
variant="primary"
type="submit"
diff --git a/apps/web/src/app/[locale]/(auth)/register/components/schema.ts b/apps/web/src/app/[locale]/(auth)/register/components/schema.ts
index 6f44b7287..ba1119d00 100644
--- a/apps/web/src/app/[locale]/(auth)/register/components/schema.ts
+++ b/apps/web/src/app/[locale]/(auth)/register/components/schema.ts
@@ -1,12 +1,29 @@
import { z } from "zod";
-
+import { usePasswordValidationSchema } from "@/features/password/schema";
+import { useTranslation } from "@/i18n/client";
import { isValidName } from "@/utils/is-valid-name";
-export const registerNameFormSchema = z.object({
- name: z.string().trim().min(1).max(100).refine(isValidName, {
- error: "Please enter a valid name, not a URL, email, or phone number",
- }),
- email: z.email(),
-});
-
-export type RegisterNameFormValues = z.infer<typeof registerNameFormSchema>;
+export const useRegisterNameFormSchema = () => {
+ const { t } = useTranslation();
+ const passwordValidation = usePasswordValidationSchema();
+ return z.object({
+ name: z
+ .string()
+ .trim()
+ .min(1)
+ .max(100)
+ .refine(
+ isValidName,
+ t("invalidName", {
+ defaultValue:
+ "Please enter a valid name, not a URL, email, or phone number",
+ }),
+ ),
+ email: z.email(
+ t("invalidEmail", {
+ defaultValue: "Please enter a valid email address",
+ }),
+ ),
+ password: passwordValidation,
+ });
+};
diff --git a/apps/web/src/app/[locale]/(auth)/reset-password/components/reset-password-form.tsx b/apps/web/src/app/[locale]/(auth)/reset-password/components/reset-password-form.tsx
new file mode 100644
index 000000000..cbaae5654
--- /dev/null
+++ b/apps/web/src/app/[locale]/(auth)/reset-password/components/reset-password-form.tsx
@@ -0,0 +1,130 @@
+"use client";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { Alert, AlertDescription } from "@rallly/ui/alert";
+import { Button } from "@rallly/ui/button";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@rallly/ui/form";
+import { PasswordInput } from "@rallly/ui/password-input";
+import { useRouter, useSearchParams } from "next/navigation";
+import { useForm } from "react-hook-form";
+import { z } from "zod";
+import { Trans } from "@/components/trans";
+import { PasswordStrengthMeter } from "@/features/password/components/password-strength-meter";
+import { usePasswordValidationSchema } from "@/features/password/schema";
+import { authClient } from "@/lib/auth-client";
+
+function useResetPasswordSchema() {
+ const passwordValidation = usePasswordValidationSchema();
+ return z.object({
+ password: passwordValidation,
+ });
+}
+
+export function ResetPasswordForm() {
+ const router = useRouter();
+ const searchParams = useSearchParams();
+ const resetPasswordSchema = useResetPasswordSchema();
+ const form = useForm({
+ defaultValues: {
+ password: "",
+ },
+ resolver: zodResolver(resetPasswordSchema),
+ });
+ const { handleSubmit, formState } = form;
+
+ const token = searchParams?.get("token");
+
+ if (!token) {
+ return (
+ <Alert variant="destructive">
+ <AlertDescription>
+ <p>
+ <Trans
+ i18nKey="resetPasswordInvalidTokenMessage"
+ defaults="The password reset link is invalid or has expired. Please request a new one."
+ />
+ </p>
+ </AlertDescription>
+ </Alert>
+ );
+ }
+
+ return (
+ <Form {...form}>
+ <form
+ onSubmit={handleSubmit(async ({ password }) => {
+ const res = await authClient.resetPassword({
+ newPassword: password,
+ token,
+ });
+
+ if (res.error) {
+ form.setError("root", {
+ message: res.error.message,
+ });
+ return;
+ }
+
+ // Check if this came from password setup (redirectTo contains settings)
+ const redirectTo = searchParams?.get("redirectTo");
+ if (redirectTo?.includes("/settings/security")) {
+ // For password setup, redirect back to settings
+ router.push(redirectTo);
+ } else {
+ // For password reset, redirect to login
+ router.push("/login");
+ }
+ })}
+ >
+ <div className="space-y-4">
+ <FormField
+ control={form.control}
+ name="password"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>
+ <Trans i18nKey="password" defaults="Password" />
+ </FormLabel>
+ <FormControl>
+ <PasswordInput
+ {...field}
+ size="lg"
+ disabled={formState.isSubmitting}
+ autoFocus={true}
+ placeholder="••••••••"
+ error={!!formState.errors.password}
+ />
+ </FormControl>
+ <PasswordStrengthMeter
+ password={field.value}
+ className="mt-2"
+ />
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ {form.formState.errors.root?.message ? (
+ <FormMessage>{form.formState.errors.root.message}</FormMessage>
+ ) : null}
+ </div>
+ <div className="mt-6">
+ <Button
+ size="lg"
+ loading={form.formState.isSubmitting}
+ type="submit"
+ className="w-full"
+ variant="primary"
+ >
+ <Trans i18nKey="resetPasswordButton" defaults="Reset password" />
+ </Button>
+ </div>
+ </form>
+ </Form>
+ );
+}
diff --git a/apps/web/src/app/[locale]/(auth)/reset-password/page.tsx b/apps/web/src/app/[locale]/(auth)/reset-password/page.tsx
new file mode 100644
index 000000000..6ac4da521
--- /dev/null
+++ b/apps/web/src/app/[locale]/(auth)/reset-password/page.tsx
@@ -0,0 +1,58 @@
+import type { Metadata } from "next";
+import { notFound } from "next/navigation";
+import { Trans } from "@/components/trans";
+import { env } from "@/env";
+import { getTranslation } from "@/i18n/server";
+import {
+ AuthPageContainer,
+ AuthPageContent,
+ AuthPageDescription,
+ AuthPageExternal,
+ AuthPageHeader,
+ AuthPageTitle,
+} from "../components/auth-page";
+import { LinkWithRedirectTo } from "../components/link-with-redirect-to";
+import { ResetPasswordForm } from "./components/reset-password-form";
+
+export default async function ResetPasswordPage() {
+ if (env.EMAIL_LOGIN_ENABLED === "false") {
+ notFound();
+ }
+ return (
+ <AuthPageContainer>
+ <AuthPageHeader>
+ <AuthPageTitle>
+ <Trans i18nKey="resetPasswordTitle" defaults="Reset Password" />
+ </AuthPageTitle>
+ <AuthPageDescription>
+ <Trans
+ i18nKey="resetPasswordDescription"
+ defaults="Enter your new password below"
+ />
+ </AuthPageDescription>
+ </AuthPageHeader>
+ <AuthPageContent>
+ <ResetPasswordForm />
+ </AuthPageContent>
+ <AuthPageExternal>
+ <Trans
+ i18nKey="resetPasswordFooter"
+ defaults="<a>Back to login</a>"
+ components={{
+ a: <LinkWithRedirectTo className="text-link" href="/login" />,
+ }}
+ />
+ </AuthPageExternal>
+ </AuthPageContainer>
+ );
+}
+
+export async function generateMetadata(props: {
+ params: Promise<{ locale: string }>;
+}): Promise<Metadata> {
+ const params = await props.params;
+ const { t } = await getTranslation(params.locale);
+ return {
+ title: t("resetPasswordTitle", { defaultValue: "Reset Password" }),
+ };
+}
diff --git a/apps/web/src/app/[locale]/(optional-space)/layout.tsx b/apps/web/src/app/[locale]/(optional-space)/layout.tsx
index 19d76250b..cc910b8d0 100644
--- a/apps/web/src/app/[locale]/(optional-space)/layout.tsx
+++ b/apps/web/src/app/[locale]/(optional-space)/layout.tsx
@@ -1,14 +1,14 @@
import { requireSpace } from "@/auth/data";
import { BillingProvider } from "@/features/billing/client";
import { SpaceProvider } from "@/features/space/client";
-import { auth } from "@/next-auth";
+import { getSession } from "@/lib/auth";
export default async function Layout({
children,
}: {
children: React.ReactNode;
}) {
- const session = await auth();
+ const session = await getSession();
if (session?.user && !session.user.isGuest) {
const space = await requireSpace();
diff --git a/apps/web/src/app/[locale]/(optional-space)/new/page.tsx b/apps/web/src/app/[locale]/(optional-space)/new/page.tsx
index 2c2ecf173..a6536f1ad 100644
--- a/apps/web/src/app/[locale]/(optional-space)/new/page.tsx
+++ b/apps/web/src/app/[locale]/(optional-space)/new/page.tsx
@@ -7,16 +7,18 @@ import { CreatePoll } from "@/components/create-poll";
import { Trans } from "@/components/trans";
import { UserDropdown } from "@/components/user-dropdown";
import { getTranslation } from "@/i18n/server";
-import { getLoggedIn } from "@/next-auth";
+import { getUserIdIfLoggedIn } from "@/lib/auth";
import { getRegistrationEnabled } from "@/utils/get-registration-enabled";
import { BackButton } from "./back-button";
export default async function Page() {
- const [isLoggedIn, isRegistrationEnabled] = await Promise.all([
- getLoggedIn(),
+ const [userId, isRegistrationEnabled] = await Promise.all([
+ getUserIdIfLoggedIn(),
getRegistrationEnabled(),
]);
+ const isLoggedIn = !!userId;
+
return (
<div className="absolute inset-0 h-dvh overflow-auto bg-gray-100">
<div className="sticky top-0 z-20 border-b bg-gray-100/90 p-3 backdrop-blur-md sm:grid-cols-3">
diff --git a/apps/web/src/app/[locale]/(space)/(dashboard)/components/nav-user.tsx b/apps/web/src/app/[locale]/(space)/(dashboard)/components/nav-user.tsx
index 43d742862..a77d93268 100644
--- a/apps/web/src/app/[locale]/(space)/(dashboard)/components/nav-user.tsx
+++ b/apps/web/src/app/[locale]/(space)/(dashboard)/components/nav-user.tsx
@@ -17,11 +17,11 @@ import {
UserIcon,
} from "lucide-react";
import Link from "next/link";
-import { signOut } from "next-auth/react";
import React from "react";
import { OptimizedAvatarImage } from "@/components/optimized-avatar-image";
import { RouterLoadingIndicator } from "@/components/router-loading-indicator";
import { Trans } from "@/components/trans";
+import { signOut } from "@/lib/auth-client";
export function NavUser({
name,
@@ -32,8 +32,7 @@ export function NavUser({
image?: string;
email: string;
}) {
- const [isPending, startTransition] = React.useTransition();
-
+ const [isPending, setIsPending] = React.useState(false);
return (
<>
{isPending && <RouterLoadingIndicator />}
@@ -78,12 +77,9 @@ export function NavUser({
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
- onClick={() => {
- startTransition(async () => {
- await signOut({
- redirectTo: "/",
- });
- });
+ onClick={async () => {
+ setIsPending(true);
+ await signOut();
}}
>
<Icon>
diff --git a/apps/web/src/app/[locale]/(space)/(dashboard)/page.tsx b/apps/web/src/app/[locale]/(space)/(dashboard)/page.tsx
index c9fc7e901..b392a06cb 100644
--- a/apps/web/src/app/[locale]/(space)/(dashboard)/page.tsx
+++ b/apps/web/src/app/[locale]/(space)/(dashboard)/page.tsx
@@ -23,26 +23,34 @@ import { getUpcomingEventsCount } from "@/features/scheduled-event/data";
import { loadMembers } from "@/features/space/data";
import { defineAbilityForMember } from "@/features/space/member/ability";
import { getTotalSeatsForSpace } from "@/features/space/utils";
+import { getUserHasNoAccounts } from "@/features/user/queries";
import { getTranslation } from "@/i18n/server";
import { IfFeatureEnabled } from "@/lib/feature-flags/client";
import { FeedbackAlert } from "./feedback-alert";
+import { PasswordSetupAlert } from "./password-setup-alert";
async function loadData() {
const [space, user] = await Promise.all([requireSpace(), requireUser()]);
- const [livePollCount, upcomingEventCount, memberCount, seatCount] =
- await Promise.all([
- prisma.poll.count({
- where: {
- spaceId: space.id,
- status: "live",
- deleted: false,
- },
- }),
- getUpcomingEventsCount(),
- loadMembers().then((members) => members.total),
- getTotalSeatsForSpace(space.id),
- ]);
+ const [
+ livePollCount,
+ upcomingEventCount,
+ { total: memberCount },
+ seatCount,
+ hasNoAccounts,
+ ] = await Promise.all([
+ prisma.poll.count({
+ where: {
+ spaceId: space.id,
+ status: "live",
+ deleted: false,
+ },
+ }),
+ getUpcomingEventsCount(),
+ loadMembers(),
+ getTotalSeatsForSpace(space.id),
+ getUserHasNoAccounts(user.id),
+ ]);
const ability = defineAbilityForMember({ space, user });
const canManageBilling = ability.can("manage", "Billing");
@@ -53,6 +61,7 @@ async function loadData() {
memberCount,
seatCount,
canManageBilling,
+ hasNoAccounts,
};
}
@@ -63,6 +72,7 @@ export default async function Page() {
memberCount,
seatCount,
canManageBilling,
+ hasNoAccounts,
} = await loadData();
return (
@@ -73,9 +83,12 @@ export default async function Page() {
</PageTitle>
</PageHeader>
<PageContent className="space-y-8">
- <IfCloudHosted>
- <FeedbackAlert />
- </IfCloudHosted>
+ <div className="space-y-4">
+ {hasNoAccounts ? <PasswordSetupAlert /> : null}
+ <IfCloudHosted>
+ <FeedbackAlert />
+ </IfCloudHosted>
+ </div>
<div className="space-y-4">
<h2 className="text-muted-foreground text-sm">
<Trans i18nKey="homeActionsTitle" defaults="Actions" />
diff --git a/apps/web/src/app/[locale]/(space)/(dashboard)/password-setup-alert.tsx b/apps/web/src/app/[locale]/(space)/(dashboard)/password-setup-alert.tsx
new file mode 100644
index 000000000..2ba685188
--- /dev/null
+++ b/apps/web/src/app/[locale]/(space)/(dashboard)/password-setup-alert.tsx
@@ -0,0 +1,60 @@
+"use client";
+import { usePostHog } from "@rallly/posthog/client";
+import { Button } from "@rallly/ui/button";
+import { KeyRoundIcon } from "lucide-react";
+import Link from "next/link";
+import { useLocalStorage } from "react-use";
+import { Trans } from "@/components/trans";
+
+export function PasswordSetupAlert() {
+ const [value, setValue] = useLocalStorage<string>("password_setup_dismissed");
+ const posthog = usePostHog();
+
+ if (value) {
+ return null;
+ }
+
+ return (
+ <div className="flex flex-col items-start gap-4 rounded-xl border border-gray-200 bg-gray-50 p-4 text-sm sm:flex-row">
+ <div className="hidden sm:block">
+ <KeyRoundIcon className="size-4 text-indigo-600" />
+ </div>
+ <div className="flex-1">
+ <h2 className="font-semibold leading-none">
+ <Trans
+ i18nKey="setupPasswordAlertTitle"
+ defaults="Login quicker with a password"
+ />
+ </h2>
+ <p className="mt-1.5 opacity-75">
+ <Trans
+ i18nKey="setupPasswordAlertDesc"
+ defaults="Set up a password to make logging in faster and more convenient."
+ />
+ </p>
+ </div>
+ <div className="flex flex-row-reverse items-center gap-2 sm:flex-row">
+ <Button
+ variant="ghost"
+ onClick={() => {
+ setValue("1");
+ posthog.capture("space_dashboard:password_setup_dismissed");
+ }}
+ >
+ <Trans i18nKey="dismissPasswordSetup" defaults="Don't show again" />
+ </Button>
+ <Button
+ variant="primary"
+ onClick={() => {
+ posthog.capture("space_dashboard:password_setup_button_click");
+ }}
+ asChild
+ >
+ <Link href="/settings/security">
+ <Trans i18nKey="setupPasswordButton" defaults="Set up password" />
+ </Link>
+ </Button>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/app/[locale]/(space)/settings/components/sidebar.tsx b/apps/web/src/app/[locale]/(space)/settings/components/sidebar.tsx
index d4cebc7b1..f0b8b8135 100644
--- a/apps/web/src/app/[locale]/(space)/settings/components/sidebar.tsx
+++ b/apps/web/src/app/[locale]/(space)/settings/components/sidebar.tsx
@@ -10,6 +10,7 @@ import {
BoltIcon,
CalendarIcon,
CreditCardIcon,
+ LockIcon,
PanelsTopLeftIcon,
Settings2Icon,
UserIcon,
@@ -30,6 +31,12 @@ export function AccountSidebarMenu() {
icon: <UserIcon />,
href: "/settings/profile",
},
+ {
+ id: "security",
+ label: t("security", { defaultValue: "Security" }),
+ icon: <LockIcon />,
+ href: "/settings/security",
+ },
{
id: "preferences",
label: t("preferences", { defaultValue: "Preferences" }),
diff --git a/apps/web/src/app/[locale]/(space)/settings/components/sign-out-button.tsx b/apps/web/src/app/[locale]/(space)/settings/components/sign-out-button.tsx
deleted file mode 100644
index bb117af3c..000000000
--- a/apps/web/src/app/[locale]/(space)/settings/components/sign-out-button.tsx
+++ /dev/null
@@ -1,35 +0,0 @@
-"use client";
-
-import { usePostHog } from "@rallly/posthog/client";
-import { Icon } from "@rallly/ui/icon";
-import { SidebarMenuButton } from "@rallly/ui/sidebar";
-import { LogOutIcon } from "lucide-react";
-import { signOut } from "next-auth/react";
-import React from "react";
-import { RouterLoadingIndicator } from "@/components/router-loading-indicator";
-import { Trans } from "@/components/trans";
-
-export const SignOutButton = () => {
- const posthog = usePostHog();
- const [isPending, startTransition] = React.useTransition();
- return (
- <>
- {isPending && <RouterLoadingIndicator />}
- <SidebarMenuButton
- onClick={() => {
- startTransition(async () => {
- await signOut({
- redirectTo: "/",
- });
- posthog?.reset();
- });
- }}
- >
- <Icon>
- <LogOutIcon />
- </Icon>
- <Trans i18nKey="signOut" defaults="Sign Out" />
- </SidebarMenuButton>
- </>
- );
-};
diff --git a/apps/web/src/app/[locale]/(space)/settings/preferences/actions.ts b/apps/web/src/app/[locale]/(space)/settings/preferences/actions.ts
index c7e8934b5..c8af73b19 100644
--- a/apps/web/src/app/[locale]/(space)/settings/preferences/actions.ts
+++ b/apps/web/src/app/[locale]/(space)/settings/preferences/actions.ts
@@ -2,10 +2,13 @@
import { prisma } from "@rallly/database";
-import { getUserId } from "@/next-auth";
+import { getUserIdIfLoggedIn } from "@/lib/auth";
export async function updateLocale(locale: string) {
- const userId = await getUserId();
+ const userId = await getUserIdIfLoggedIn();
+ if (!userId) {
+ throw new Error("User not found");
+ }
await prisma.user.update({
where: {
id: userId,
diff --git a/apps/web/src/app/[locale]/(space)/settings/profile/actions.ts b/apps/web/src/app/[locale]/(space)/settings/profile/actions.ts
index 4a2ed9339..8e5e7d185 100644
--- a/apps/web/src/app/[locale]/(space)/settings/profile/actions.ts
+++ b/apps/web/src/app/[locale]/(space)/settings/profile/actions.ts
@@ -2,9 +2,9 @@
import { subject } from "@casl/ability";
import { prisma } from "@rallly/database";
+import { signOut } from "@/lib/auth";
import { AppError } from "@/lib/errors";
import { authActionClient } from "@/lib/safe-action/server";
-import { signOut } from "@/next-auth";
export const deleteCurrentUserAction = authActionClient
.metadata({ actionName: "delete_current_user" })
diff --git a/apps/web/src/app/[locale]/(space)/settings/profile/logout-button.tsx b/apps/web/src/app/[locale]/(space)/settings/profile/logout-button.tsx
deleted file mode 100644
index 6342212db..000000000
--- a/apps/web/src/app/[locale]/(space)/settings/profile/logout-button.tsx
+++ /dev/null
@@ -1,23 +0,0 @@
-"use client";
-
-import { Button } from "@rallly/ui/button";
-import { Icon } from "@rallly/ui/icon";
-import { LogOutIcon } from "lucide-react";
-import { signOut } from "next-auth/react";
-import { Trans } from "@/components/trans";
-
-export function LogoutButton() {
- return (
- <Button
- onClick={async () => {
- await signOut();
- }}
- variant="default"
- >
- <Icon>
- <LogOutIcon />
- </Icon>
- <Trans i18nKey="signOut" defaults="Sign Out" />
- </Button>
- );
-}
diff --git a/apps/web/src/app/[locale]/(space)/settings/security/components/change-password-form.tsx b/apps/web/src/app/[locale]/(space)/settings/security/components/change-password-form.tsx
new file mode 100644
index 000000000..7bb628bcc
--- /dev/null
+++ b/apps/web/src/app/[locale]/(space)/settings/security/components/change-password-form.tsx
@@ -0,0 +1,161 @@
+"use client";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { Button } from "@rallly/ui/button";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@rallly/ui/form";
+import { PasswordInput } from "@rallly/ui/password-input";
+import { toast } from "@rallly/ui/sonner";
+import { useForm } from "react-hook-form";
+import { useTranslation } from "react-i18next";
+import { z } from "zod";
+import { Trans } from "@/components/trans";
+import { PasswordStrengthMeter } from "@/features/password/components/password-strength-meter";
+import { usePasswordValidationSchema } from "@/features/password/schema";
+import { authClient } from "@/lib/auth-client";
+
+function useChangePasswordSchema() {
+ const { t } = useTranslation();
+ const passwordValidation = usePasswordValidationSchema();
+
+ return z
+ .object({
+ currentPassword: z
+ .string()
+ .min(
+ 1,
+ t("passwordRequired", { defaultValue: "Password is required" }),
+ ),
+ newPassword: passwordValidation,
+ })
+ .refine((data) => data.currentPassword !== data.newPassword, {
+ message: t("passwordsMustBeDifferent", {
+ defaultValue: "New password must be different from current password",
+ }),
+ path: ["newPassword"],
+ });
+}
+
+type ChangePasswordValues = z.infer<ReturnType<typeof useChangePasswordSchema>>;
+
+export function ChangePasswordForm() {
+ const changePasswordSchema = useChangePasswordSchema();
+ const form = useForm<ChangePasswordValues>({
+ defaultValues: {
+ currentPassword: "",
+ newPassword: "",
+ },
+ resolver: zodResolver(changePasswordSchema),
+ });
+ const { handleSubmit, formState } = form;
+ const { t } = useTranslation();
+
+ const onSubmit = async (data: ChangePasswordValues) => {
+ const res = await authClient.changePassword({
+ currentPassword: data.currentPassword,
+ newPassword: data.newPassword,
+ revokeOtherSessions: true,
+ });
+
+ if (res.error) {
+ switch (res.error.code) {
+ case "INVALID_PASSWORD":
+ form.setError("currentPassword", {
+ message: t("passwordIncorrect", {
+ defaultValue: "Current password is incorrect",
+ }),
+ });
+ break;
+ default:
+ form.setError("root", {
+ message: res.error.message,
+ });
+ break;
+ }
+ return;
+ }
+
+ form.reset();
+ toast.success(
+ t("passwordChangedSuccess", {
+ defaultValue: "Your password has been changed successfully",
+ }),
+ );
+ };
+
+ return (
+ <Form {...form}>
+ <form onSubmit={handleSubmit(onSubmit)}>
+ {form.formState.errors.root?.message && (
+ <FormMessage>{form.formState.errors.root.message}</FormMessage>
+ )}
+
+ <div className="grid grid-cols-1 gap-4">
+ <FormField
+ control={form.control}
+ name="currentPassword"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>
+ <Trans
+ i18nKey="currentPassword"
+ defaults="Current Password"
+ />
+ </FormLabel>
+ <FormControl>
+ <PasswordInput
+ {...field}
+ disabled={formState.isSubmitting}
+ placeholder="••••••••"
+ error={!!formState.errors.currentPassword}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="newPassword"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>
+ <Trans i18nKey="newPassword" defaults="New Password" />
+ </FormLabel>
+ <FormControl>
+ <PasswordInput
+ {...field}
+ disabled={formState.isSubmitting}
+ placeholder="••••••••"
+ error={!!formState.errors.newPassword}
+ />
+ </FormControl>
+ <PasswordStrengthMeter
+ password={field.value}
+ className="mt-2"
+ />
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ </div>
+
+ <div className="mt-6">
+ <Button
+ type="submit"
+ loading={formState.isSubmitting}
+ variant="primary"
+ >
+ <Trans i18nKey="changePassword" defaults="Change Password" />
+ </Button>
+ </div>
+ </form>
+ </Form>
+ );
+}
diff --git a/apps/web/src/app/[locale]/(space)/settings/security/components/setup-password-form.tsx b/apps/web/src/app/[locale]/(space)/settings/security/components/setup-password-form.tsx
new file mode 100644
index 000000000..93094554d
--- /dev/null
+++ b/apps/web/src/app/[locale]/(space)/settings/security/components/setup-password-form.tsx
@@ -0,0 +1,61 @@
+"use client";
+import { Alert, AlertDescription } from "@rallly/ui/alert";
+import { Button } from "@rallly/ui/button";
+import { toast } from "@rallly/ui/sonner";
+import { MailWarningIcon } from "lucide-react";
+import React from "react";
+import { Trans } from "@/components/trans";
+import { useAuthenticatedUser } from "@/components/user-provider";
+import { authClient } from "@/lib/auth-client";
+
+export function SetupPasswordForm() {
+ const { user } = useAuthenticatedUser();
+ const [isLoading, setIsLoading] = React.useState(false);
+ const [isSuccess, setIsSuccess] = React.useState(false);
+
+ const onSubmit = async () => {
+ setIsLoading(true);
+
+ // For users without passwords, we need to use the password reset flow
+ // First request a password reset
+ const resetRes = await authClient.requestPasswordReset({
+ email: user.email,
+ redirectTo: `/reset-password?redirectTo=${encodeURIComponent("/settings/security?setupPassword=true")}`,
+ });
+
+ setIsLoading(false);
+
+ if (resetRes.error) {
+ toast.error(resetRes.error.message);
+ return;
+ }
+
+ setIsSuccess(true);
+ };
+
+ return (
+ <div className="space-y-4">
+ <Button
+ onClick={onSubmit}
+ loading={isLoading}
+ variant="primary"
+ disabled={isSuccess}
+ >
+ <Trans i18nKey="sendResetLink" defaults="Send reset link" />
+ </Button>
+ {isSuccess ? (
+ <Alert variant="info">
+ <MailWarningIcon />
+ <AlertDescription>
+ <p>
+ <Trans
+ i18nKey="passwordSetupSuccess"
+ defaults="A password reset link has been sent to your email. Follow the link to set your password."
+ />
+ </p>
+ </AlertDescription>
+ </Alert>
+ ) : null}
+ </div>
+ );
+}
diff --git a/apps/web/src/app/[locale]/(space)/settings/security/page.tsx b/apps/web/src/app/[locale]/(space)/settings/security/page.tsx
new file mode 100644
index 000000000..0b34582dd
--- /dev/null
+++ b/apps/web/src/app/[locale]/(space)/settings/security/page.tsx
@@ -0,0 +1,116 @@
+import { Alert, AlertDescription } from "@rallly/ui/alert";
+import { ShieldCheckIcon } from "lucide-react";
+import type { Metadata } from "next";
+import type { Params } from "@/app/[locale]/types";
+import {
+ PageSection,
+ PageSectionContent,
+ PageSectionDescription,
+ PageSectionGroup,
+ PageSectionHeader,
+ PageSectionTitle,
+} from "@/app/components/page-layout";
+import {
+ SettingsPage,
+ SettingsPageContent,
+ SettingsPageDescription,
+ SettingsPageHeader,
+ SettingsPageTitle,
+} from "@/app/components/settings-layout";
+import { requireUser } from "@/auth/data";
+import { Trans } from "@/components/trans";
+import { getUserHasPassword } from "@/features/user/queries";
+import { getTranslation } from "@/i18n/server";
+import { ChangePasswordForm } from "./components/change-password-form";
+import { SetupPasswordForm } from "./components/setup-password-form";
+
+export default async function SecurityPage({
+ searchParams,
+}: {
+ searchParams: Promise<{ setupPassword?: string }>;
+}) {
+ const { setupPassword } = await searchParams;
+ const user = await requireUser();
+ const hasPassword = await getUserHasPassword(user.id);
+
+ return (
+ <SettingsPage>
+ <SettingsPageHeader>
+ <SettingsPageTitle>
+ <Trans i18nKey="security" defaults="Security" />
+ </SettingsPageTitle>
+ <SettingsPageDescription>
+ <Trans
+ i18nKey="securityDescription"
+ defaults="Manage your account security and password settings"
+ />
+ </SettingsPageDescription>
+ </SettingsPageHeader>
+ <SettingsPageContent>
+ {setupPassword ? (
+ <Alert variant="tip">
+ <ShieldCheckIcon />
+ <AlertDescription>
+ <p>
+ <Trans
+ i18nKey="passwordSetupSuccessful"
+ defaults="Password setup successful. You can now login with your email and password."
+ />
+ </p>
+ </AlertDescription>
+ </Alert>
+ ) : null}
+ <PageSectionGroup>
+ {hasPassword ? (
+ <PageSection variant="card">
+ <PageSectionHeader>
+ <PageSectionTitle>
+ <Trans i18nKey="changePassword" defaults="Change Password" />
+ </PageSectionTitle>
+ <PageSectionDescription>
+ <Trans
+ i18nKey="changePasswordDescription"
+ defaults="Update your password to keep your account secure"
+ />
+ </PageSectionDescription>
+ </PageSectionHeader>
+ <PageSectionContent>
+ <ChangePasswordForm />
+ </PageSectionContent>
+ </PageSection>
+ ) : (
+ <PageSection variant="card">
+ <PageSectionHeader>
+ <PageSectionTitle>
+ <Trans
+ i18nKey="resetPasswordTitle"
+ defaults="Reset Password"
+ />
+ </PageSectionTitle>
+ <PageSectionDescription className="max-w-lg">
+ <Trans
+ i18nKey="setupPasswordDescription"
+ defaults="Your account doesn't have a password yet. Click the button below to send a secure link to your email to set a password."
+ />
+ </PageSectionDescription>
+ </PageSectionHeader>
+ <PageSectionContent>
+ <SetupPasswordForm />
+ </PageSectionContent>
+ </PageSection>
+ )}
+ </PageSectionGroup>
+ </SettingsPageContent>
+ </SettingsPage>
+ );
+}
+
+export async function generateMetadata(props: {
+ params: Promise<Params>;
+}): Promise<Metadata> {
+ const params = await props.params;
+ const { t } = await getTranslation(params.locale);
+ return {
+ title: t("security", { defaultValue: "Security" }),
+ };
+}
diff --git a/apps/web/src/app/[locale]/accept-invite/[inviteId]/components/sign-out-button.tsx b/apps/web/src/app/[locale]/accept-invite/[inviteId]/components/sign-out-button.tsx
index eb7f8bc94..caceb9271 100644
--- a/apps/web/src/app/[locale]/accept-invite/[inviteId]/components/sign-out-button.tsx
+++ b/apps/web/src/app/[locale]/accept-invite/[inviteId]/components/sign-out-button.tsx
@@ -1,26 +1,20 @@
"use client";
import { Button } from "@rallly/ui/button";
-import { usePathname } from "next/navigation";
-import { signOut } from "next-auth/react";
import React from "react";
import { Trans } from "@/components/trans";
+import { signOut } from "@/lib/auth-client";
export function SignOutButton() {
- const pathname = usePathname();
- const [isPending, startTransition] = React.useTransition();
+ const [isPending, setIsPending] = React.useState(false);
return (
<Button
variant="link"
loading={isPending}
- onClick={() =>
- startTransition(
- async () =>
- await signOut({
- redirectTo: pathname,
- }),
- )
- }
+ onClick={async () => {
+ setIsPending(true);
+ await signOut();
+ }}
>
<Trans
i18nKey="loginWithAnotherAccount"
diff --git a/apps/web/src/app/[locale]/layout.tsx b/apps/web/src/app/[locale]/layout.tsx
index b6b2accea..668836d79 100644
--- a/apps/web/src/app/[locale]/layout.tsx
+++ b/apps/web/src/app/[locale]/layout.tsx
@@ -15,11 +15,11 @@ import { UserProvider } from "@/components/user-provider";
import { PreferencesProvider } from "@/contexts/preferences";
import type { UserDTO } from "@/features/user/schema";
import { I18nProvider } from "@/i18n/client";
+import { getSession } from "@/lib/auth";
import { FeatureFlagsProvider } from "@/lib/feature-flags/client";
import { featureFlagConfig } from "@/lib/feature-flags/config";
import { LocaleSync } from "@/lib/locale/client";
import { TimezoneProvider } from "@/lib/timezone/client/context";
-import { auth } from "@/next-auth";
import { TRPCProvider } from "@/trpc/client/provider";
import { ConnectedDayjsProvider } from "@/utils/dayjs";
import { PostHogPageView } from "../posthog-page-view";
@@ -36,7 +36,7 @@ export const viewport: Viewport = {
};
async function loadData() {
- const [session] = await Promise.all([auth()]);
+ const [session] = await Promise.all([getSession()]);
const user = session?.user
? !session.user.isGuest
diff --git a/apps/web/src/app/api/auth/invalid-session/route.ts b/apps/web/src/app/api/auth/invalid-session/route.ts
index 8db431cd7..3667dec65 100644
--- a/apps/web/src/app/api/auth/invalid-session/route.ts
+++ b/apps/web/src/app/api/auth/invalid-session/route.ts
@@ -1,12 +1,9 @@
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
-
-import { signOut } from "@/next-auth";
+import { signOut } from "@/lib/auth";
export async function GET(req: NextRequest) {
- await signOut({
- redirect: false,
- });
+ await signOut();
return NextResponse.redirect(new URL("/login", req.url));
}
diff --git a/apps/web/src/app/api/better-auth/[...all]/route.ts b/apps/web/src/app/api/better-auth/[...all]/route.ts
new file mode 100644
index 000000000..8ef245888
--- /dev/null
+++ b/apps/web/src/app/api/better-auth/[...all]/route.ts
@@ -0,0 +1,4 @@
+import { toNextJsHandler } from "better-auth/next-js";
+import { authLib } from "@/lib/auth";
+
+export const { POST, GET } = toNextJsHandler(authLib);
diff --git a/apps/web/src/app/api/integrations/[...connection]/route.ts b/apps/web/src/app/api/integrations/[...connection]/route.ts
index a3ab3317d..2a8c8dafa 100644
--- a/apps/web/src/app/api/integrations/[...connection]/route.ts
+++ b/apps/web/src/app/api/integrations/[...connection]/route.ts
@@ -4,9 +4,9 @@ import {
syncCalendars,
} from "@/features/calendars/mutations";
import { saveOAuthCredentials } from "@/features/credentials/mutations";
+import { getSession } from "@/lib/auth";
import { GoogleOAuthClient } from "@/lib/oauth/providers/google";
import { OAuthIntegration } from "@/lib/oauth/server";
-import { auth } from "@/next-auth";
type Integration = "google-calendar" | "outlook-calendar";
@@ -34,7 +34,7 @@ const { handler } = OAuthIntegration<Integration>({
providerAccountId,
userInfo,
}) => {
- const session = await auth();
+ const session = await getSession();
if (!session?.user) {
throw new Error("User not found");
}
diff --git a/apps/web/src/app/api/notifications/unsubscribe/route.ts b/apps/web/src/app/api/notifications/unsubscribe/route.ts
index 7791993a4..136c1a6f2 100644
--- a/apps/web/src/app/api/notifications/unsubscribe/route.ts
+++ b/apps/web/src/app/api/notifications/unsubscribe/route.ts
@@ -3,7 +3,7 @@ import { cookies } from "next/headers";
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
-import { auth } from "@/next-auth";
+import { getSession } from "@/lib/auth";
import type { DisableNotificationsPayload } from "@/trpc/types";
import { decryptToken } from "@/utils/session";
@@ -14,7 +14,7 @@ export const GET = async (req: NextRequest) => {
return NextResponse.redirect(new URL("/login", req.url));
}
- const session = await auth();
+ const session = await getSession();
if (!session || !session.user?.email) {
return NextResponse.redirect(new URL("/login", req.url));
diff --git a/apps/web/src/app/api/stripe/portal/helpers/create-portal-session.ts b/apps/web/src/app/api/stripe/portal/helpers/create-portal-session.ts
index a996c76dc..f879c7fe3 100644
--- a/apps/web/src/app/api/stripe/portal/helpers/create-portal-session.ts
+++ b/apps/web/src/app/api/stripe/portal/helpers/create-portal-session.ts
@@ -5,7 +5,7 @@ import * as Sentry from "@sentry/nextjs";
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
-import { auth } from "@/next-auth";
+import { getSession } from "@/lib/auth";
export function createStripePortalSessionHandler(path = "") {
return async (request: NextRequest) => {
@@ -34,7 +34,7 @@ export function createStripePortalSessionHandler(path = "") {
);
}
} else {
- const userSession = await auth();
+ const userSession = await getSession();
if (!userSession?.user || userSession.user.email === null) {
const url = new URL("/login", request.url);
url.searchParams.set("redirectTo", request.nextUrl.pathname);
diff --git a/apps/web/src/app/api/trpc/[trpc]/route.ts b/apps/web/src/app/api/trpc/[trpc]/route.ts
index b3eee5a4e..9c6eedac9 100644
--- a/apps/web/src/app/api/trpc/[trpc]/route.ts
+++ b/apps/web/src/app/api/trpc/[trpc]/route.ts
@@ -4,13 +4,13 @@ import { fetchRequestHandler } from "@trpc/server/adapters/fetch";
import { ipAddress } from "@vercel/functions";
import type { NextRequest } from "next/server";
-import { auth } from "@/next-auth";
+import { getSession } from "@/lib/auth";
import type { TRPCContext } from "@/trpc/context";
import { appRouter } from "@/trpc/routers";
import { getEmailClient } from "@/utils/emails";
const handler = async (req: NextRequest) => {
- const session = await auth();
+ const session = await getSession();
const ip = ipAddress(req);
const ja4Digest = req.headers.get("x-vercel-ja4-digest");
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 d034dc888..fc59b4bbb 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
@@ -6,7 +6,7 @@ import { waitUntil } from "@vercel/functions";
import { cookies } from "next/headers";
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
-import { auth } from "@/next-auth";
+import { getSession } from "@/lib/auth";
import { decryptToken } from "@/utils/session";
type EmailChangePayload = {
@@ -77,7 +77,7 @@ export const GET = async (request: NextRequest) => {
return NextResponse.json({ error: "No token provided" }, { status: 400 });
}
- const session = await auth();
+ const session = await getSession();
if (!session?.user || !session.user.email) {
return NextResponse.redirect(
diff --git a/apps/web/src/app/components/logout-button.tsx b/apps/web/src/app/components/logout-button.tsx
deleted file mode 100644
index 99d425308..000000000
--- a/apps/web/src/app/components/logout-button.tsx
+++ /dev/null
@@ -1,23 +0,0 @@
-"use client";
-import type { ButtonProps } from "@rallly/ui/button";
-import { Button } from "@rallly/ui/button";
-
-import { signOut } from "next-auth/react";
-
-export function LogoutButton({
- children,
- onClick,
- ...rest
-}: React.PropsWithChildren<ButtonProps>) {
- return (
- <Button
- {...rest}
- onClick={async (e) => {
- await signOut();
- onClick?.(e);
- }}
- >
- {children}
- </Button>
- );
-}
diff --git a/apps/web/src/auth/adapters/prisma.ts b/apps/web/src/auth/adapters/prisma.ts
deleted file mode 100644
index 01bf7d5b6..000000000
--- a/apps/web/src/auth/adapters/prisma.ts
+++ /dev/null
@@ -1,64 +0,0 @@
-/**
- * This is a modified version of the default Prisma adapter that
- * ignores fields returned by the OAuth provider that are not
- * defined in the database schema when creating an account.
- *
- * This resolves issues where some OAuth providers return unexpected
- * fields in their response which cause the Prisma adapter to throw
- * an error.
- *
- * See: https://github.com/lukevella/rallly/issues/949
- */
-
-import { PrismaAdapter } from "@auth/prisma-adapter";
-import { prisma } from "@rallly/database";
-import type { Adapter } from "next-auth/adapters";
-import { trackSpaceCreated } from "@/features/space/analytics";
-import { createSpace } from "@/features/space/mutations";
-import { createUser } from "@/features/user/mutations";
-
-export function CustomPrismaAdapter(options: {
- migrateData: (userId: string) => Promise<void>;
-}) {
- const adapter = PrismaAdapter(prisma);
- return {
- ...adapter,
- linkAccount: async (account) => {
- await options.migrateData(account.userId);
- return prisma.account.create({
- data: {
- userId: account.userId,
- type: account.type,
- provider: account.provider,
- providerAccountId: account.providerAccountId,
- access_token: account.access_token as string,
- expires_at: account.expires_at as number,
- id_token: account.id_token as string,
- token_type: account.token_type as string,
- refresh_token: account.refresh_token as string,
- scope: account.scope as string,
- session_state: account.session_state as string,
- },
- });
- },
- createUser: async (user) => {
- const newUser = await createUser({
- name: user.name ?? "Unknown",
- email: user.email,
- emailVerified: user.emailVerified ?? undefined,
- image: user.image ?? undefined,
- timeZone: user.timeZone ?? undefined,
- timeFormat: user.timeFormat ?? undefined,
- locale: user.locale ?? undefined,
- });
-
- const space = await createSpace({
- ownerId: newUser.id,
- });
-
- trackSpaceCreated({ space, userId: newUser.id });
-
- return newUser;
- },
- } as Adapter;
-}
diff --git a/apps/web/src/auth/data.ts b/apps/web/src/auth/data.ts
index 7a1ba1c6c..b136afc5f 100644
--- a/apps/web/src/auth/data.ts
+++ b/apps/web/src/auth/data.ts
@@ -6,12 +6,12 @@ import { notFound, redirect } from "next/navigation";
import { cache } from "react";
import { createSpaceDTO } from "@/features/space/data";
import { getUser } from "@/features/user/data";
+import { getSession } from "@/lib/auth";
import { AppError } from "@/lib/errors";
-import { auth } from "@/next-auth";
import { isInitialAdmin } from "@/utils/is-initial-admin";
export const getCurrentUser = async () => {
- const session = await auth();
+ const session = await getSession();
if (!session?.user) {
return null;
@@ -89,11 +89,11 @@ export const requireAdmin = cache(async () => {
});
export const requireUser = cache(async () => {
- const session = await auth();
+ const session = await getSession();
const headersList = await headers();
const pathname = headersList.get("x-pathname") ?? "/";
- if (!session?.user) {
+ if (!session?.user || session.user.isGuest) {
const searchParams = new URLSearchParams();
searchParams.set("redirectTo", pathname);
redirect(`/login?${searchParams.toString()}`);
diff --git a/apps/web/src/auth/edge/index.ts b/apps/web/src/auth/edge/index.ts
deleted file mode 100644
index 349f48458..000000000
--- a/apps/web/src/auth/edge/index.ts
+++ /dev/null
@@ -1 +0,0 @@
-export * from "./with-auth";
diff --git a/apps/web/src/auth/edge/with-auth.ts b/apps/web/src/auth/edge/with-auth.ts
deleted file mode 100644
index eabc4c706..000000000
--- a/apps/web/src/auth/edge/with-auth.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-import type { NextResponse } from "next/server";
-import type { NextAuthRequest, Session } from "next-auth";
-import NextAuth from "next-auth";
-
-import { nextAuthConfig } from "@/next-auth.config";
-
-const { auth } = NextAuth(nextAuthConfig);
-
-export const withAuth = (
- middleware: (request: NextAuthRequest) => Promise<NextResponse>,
-) => {
- return async (request: NextAuthRequest) => {
- let session: Session | null = null;
-
- try {
- session = await auth();
- } catch (e) {
- console.error(e);
- }
-
- try {
- const res = await nextAuthConfig.callbacks.authorized({
- request,
- auth: session,
- });
-
- if (res !== true) {
- return res;
- }
- } catch (e) {
- console.error(e);
- }
-
- request.auth = session;
-
- const middlewareRes = await middleware(request);
-
- return middlewareRes;
- };
-};
diff --git a/apps/web/src/auth/helpers/get-optional-providers.ts b/apps/web/src/auth/helpers/get-optional-providers.ts
deleted file mode 100644
index cf2eec83f..000000000
--- a/apps/web/src/auth/helpers/get-optional-providers.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-import type { Provider } from "next-auth/providers/index";
-
-import { GoogleProvider } from "../providers/google";
-import { MicrosoftProvider } from "../providers/microsoft";
-import { OIDCProvider } from "../providers/oidc";
-
-export function getOptionalProviders() {
- return [OIDCProvider(), GoogleProvider(), MicrosoftProvider()].filter(
- Boolean,
- ) as Provider[];
-}
diff --git a/apps/web/src/components/create-poll.tsx b/apps/web/src/components/create-poll.tsx
index f0c42ea8a..c01b99a28 100644
--- a/apps/web/src/components/create-poll.tsx
+++ b/apps/web/src/components/create-poll.tsx
@@ -121,7 +121,7 @@ export const CreatePoll: React.FunctionComponent = () => {
<PollSettingsForm />
<hr />
<Button
- loading={createPoll.isPending || createPoll.isSuccess}
+ loading={form.formState.isSubmitting || createPoll.isSuccess}
size="lg"
type="submit"
className="w-full"
diff --git a/apps/web/src/components/poll/notifications-toggle.tsx b/apps/web/src/components/poll/notifications-toggle.tsx
index b5e1a8e46..b4237c394 100644
--- a/apps/web/src/components/poll/notifications-toggle.tsx
+++ b/apps/web/src/components/poll/notifications-toggle.tsx
@@ -2,19 +2,19 @@ import { Button } from "@rallly/ui/button";
import { Icon } from "@rallly/ui/icon";
import { Tooltip, TooltipContent, TooltipTrigger } from "@rallly/ui/tooltip";
import { BellOffIcon, BellRingIcon } from "lucide-react";
-import { signIn } from "next-auth/react";
+import { usePathname, useRouter } from "next/navigation";
import type * as React from "react";
-
import { Skeleton } from "@/components/skeleton";
import { Trans } from "@/components/trans";
import { useUser } from "@/components/user-provider";
import { useTranslation } from "@/i18n/client";
import { trpc } from "@/trpc/client";
-
import { usePoll } from "../poll-context";
const NotificationsToggle: React.FunctionComponent = () => {
const { poll } = usePoll();
+ const pathname = usePathname();
+ const router = useRouter();
const { data: watchers } = trpc.polls.getWatchers.useQuery(
{
@@ -73,7 +73,7 @@ const NotificationsToggle: React.FunctionComponent = () => {
variant="ghost"
onClick={async () => {
if (!user || user.isGuest) {
- signIn();
+ router.push(`/login?redirectTo=${encodeURIComponent(pathname)}`);
return;
}
// toggle
diff --git a/apps/web/src/components/user-dropdown.tsx b/apps/web/src/components/user-dropdown.tsx
index e10e78c70..f8012fd2f 100644
--- a/apps/web/src/components/user-dropdown.tsx
+++ b/apps/web/src/components/user-dropdown.tsx
@@ -22,10 +22,10 @@ import {
UserIcon,
} from "lucide-react";
import Link from "next/link";
-import { signOut } from "next-auth/react";
import { OptimizedAvatarImage } from "@/components/optimized-avatar-image";
import { Trans } from "@/components/trans";
import { IfCloudHosted, IfSelfHosted } from "@/contexts/environment";
+import { signOut } from "@/lib/auth-client";
import { useAuthenticatedUser } from "./user-provider";
export const UserDropdown = ({ className }: { className?: string }) => {
diff --git a/apps/web/src/features/password/components/password-strength-meter.tsx b/apps/web/src/features/password/components/password-strength-meter.tsx
new file mode 100644
index 000000000..74d6af42f
--- /dev/null
+++ b/apps/web/src/features/password/components/password-strength-meter.tsx
@@ -0,0 +1,67 @@
+"use client";
+import { cn } from "@rallly/ui";
+import { Trans } from "@/components/trans";
+import type { PasswordQuality } from "../types";
+import { getPasswordQuality } from "../utils";
+
+function PasswordStrengthLabel({ quality }: { quality: PasswordQuality }) {
+ switch (quality) {
+ case "veryWeak":
+ return <Trans i18nKey="passwordStrengthVeryWeak" defaults="Very weak" />;
+ case "weak":
+ return <Trans i18nKey="passwordStrengthWeak" defaults="Weak" />;
+ case "fair":
+ return <Trans i18nKey="passwordStrengthFair" defaults="Fair" />;
+ case "good":
+ return <Trans i18nKey="passwordStrengthGood" defaults="Good" />;
+ case "strong":
+ return <Trans i18nKey="passwordStrengthStrong" defaults="Strong" />;
+ }
+}
+
+export function PasswordStrengthMeter({
+ password,
+ className,
+}: {
+ password: string;
+ className?: string;
+}) {
+ const quality = getPasswordQuality(password);
+
+ return (
+ <div className={cn("space-y-2", className)}>
+ <div className="grid grid-cols-4 gap-1">
+ {[1, 2, 3, 4].map((bar) => (
+ <div
+ key={`password-strength-bar-${bar}`}
+ className={cn(
+ "h-1 rounded-full bg-gray-200 transition-all duration-300",
+ {
+ "bg-red-500": quality === "weak" && bar === 1,
+ "bg-amber-500": quality === "fair" && bar <= 2,
+ "bg-green-500": quality === "good" && bar <= 3,
+ "bg-teal-500": quality === "strong" && bar <= 4,
+ },
+ )}
+ />
+ ))}
+ </div>
+ <div className="flex items-center justify-between text-xs">
+ <span className="text-muted-foreground text-xs">
+ <Trans i18nKey="passwordStrength" defaults="Password Strength" />
+ </span>
+ <span
+ className={cn("font-medium", {
+ "text-gray-500": quality === "veryWeak",
+ "text-red-600": quality === "weak",
+ "text-amber-600": quality === "fair",
+ "text-green-600": quality === "good",
+ "text-teal-600": quality === "strong",
+ })}
+ >
+ <PasswordStrengthLabel quality={quality} />
+ </span>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/password/schema.ts b/apps/web/src/features/password/schema.ts
new file mode 100644
index 000000000..95d21a693
--- /dev/null
+++ b/apps/web/src/features/password/schema.ts
@@ -0,0 +1,18 @@
+"use client";
+import { z } from "zod";
+import {
+ calculatePasswordStrength,
+ passwordQualityThresholds,
+} from "@/features/password/utils";
+import { useTranslation } from "@/i18n/client";
+
+export function usePasswordValidationSchema() {
+ const { t } = useTranslation();
+ return z.string().refine(
+ (password) =>
+ calculatePasswordStrength(password) >= passwordQualityThresholds.good,
+ t("passwordTooWeak", {
+ defaultValue: "Password is too weak. Please use a stronger password.",
+ }),
+ );
+}
diff --git a/apps/web/src/features/password/types.ts b/apps/web/src/features/password/types.ts
new file mode 100644
index 000000000..95b209f69
--- /dev/null
+++ b/apps/web/src/features/password/types.ts
@@ -0,0 +1 @@
+export type PasswordQuality = "veryWeak" | "weak" | "fair" | "good" | "strong";
diff --git a/apps/web/src/features/password/utils.ts b/apps/web/src/features/password/utils.ts
new file mode 100644
index 000000000..f668d8f7a
--- /dev/null
+++ b/apps/web/src/features/password/utils.ts
@@ -0,0 +1,43 @@
+import zxcvbn from "zxcvbn";
+import type { PasswordQuality } from "@/features/password/types";
+
+/**
+ * Calculate password strength using zxcvbn
+ * @returns Score from 0-4:
+ * - 0: too guessable (very weak)
+ * - 1: very guessable (weak)
+ * - 2: somewhat guessable (fair)
+ * - 3: safely unguessable (good)
+ * - 4: very unguessable (strong)
+ */
+export function calculatePasswordStrength(password: string): number {
+ if (!password) return 0;
+ const result = zxcvbn(password);
+ return result.score;
+}
+
+export function getPasswordQuality(password: string): PasswordQuality {
+ const score = calculatePasswordStrength(password);
+ switch (score) {
+ case 0:
+ return "veryWeak";
+ case 1:
+ return "weak";
+ case 2:
+ return "fair";
+ case 3:
+ return "good";
+ case 4:
+ return "strong";
+ default:
+ return "veryWeak";
+ }
+}
+
+export const passwordQualityThresholds: Record<PasswordQuality, number> = {
+ veryWeak: 0,
+ weak: 1,
+ fair: 2,
+ good: 3,
+ strong: 4,
+};
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 9d4a828f2..5c8446da2 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
@@ -1,9 +1,9 @@
import { prisma } from "@rallly/database";
-import { auth } from "@/next-auth";
+import { getSession } from "@/lib/auth";
export async function getGuestPolls() {
- const session = await auth();
+ const session = await getSession();
const user = session?.user;
const guestId = !user?.email ? user?.id : null;
diff --git a/apps/web/src/features/user/mutations.ts b/apps/web/src/features/user/mutations.ts
index 3182f8287..be40c823d 100644
--- a/apps/web/src/features/user/mutations.ts
+++ b/apps/web/src/features/user/mutations.ts
@@ -13,7 +13,7 @@ export async function createUser({
}: {
name: string;
email: string;
- emailVerified?: Date;
+ emailVerified?: boolean;
image?: string;
timeZone?: string;
timeFormat?: TimeFormat;
diff --git a/apps/web/src/features/user/queries.ts b/apps/web/src/features/user/queries.ts
index 40b53c02f..e58bddc3a 100644
--- a/apps/web/src/features/user/queries.ts
+++ b/apps/web/src/features/user/queries.ts
@@ -3,3 +3,22 @@ import { prisma } from "@rallly/database";
export const getUserCount = async () => {
return await prisma.user.count();
};
+
+export const getUserHasPassword = async (userId: string) => {
+ const account = await prisma.account.findFirst({
+ where: {
+ userId,
+ provider: "credential",
+ },
+ });
+ return !!account;
+};
+
+export const getUserHasNoAccounts = async (userId: string) => {
+ const accountCount = await prisma.account.count({
+ where: {
+ userId,
+ },
+ });
+ return accountCount === 0;
+};
diff --git a/apps/web/src/lib/auth-client.ts b/apps/web/src/lib/auth-client.ts
new file mode 100644
index 000000000..c05d14309
--- /dev/null
+++ b/apps/web/src/lib/auth-client.ts
@@ -0,0 +1,28 @@
+import { absoluteUrl } from "@rallly/utils/absolute-url";
+import {
+ emailOTPClient,
+ genericOAuthClient,
+ inferAdditionalFields,
+ lastLoginMethodClient,
+} from "better-auth/client/plugins";
+import { createAuthClient } from "better-auth/react";
+import { signOut as nextAuthSignOut } from "next-auth/react";
+import type { Auth } from "@/lib/auth";
+
+export const authClient = createAuthClient({
+ baseURL: absoluteUrl("/api/better-auth"),
+ plugins: [
+ inferAdditionalFields<Auth>(),
+ emailOTPClient(),
+ genericOAuthClient(),
+ lastLoginMethodClient(),
+ ],
+});
+
+export async function signOut() {
+ await Promise.all([
+ authClient.signOut(),
+ nextAuthSignOut({ redirect: false }),
+ ]);
+ window.location.href = "/login";
+}
diff --git a/apps/web/src/lib/auth.ts b/apps/web/src/lib/auth.ts
new file mode 100644
index 000000000..0b1123a54
--- /dev/null
+++ b/apps/web/src/lib/auth.ts
@@ -0,0 +1,328 @@
+import { prisma } from "@rallly/database";
+import { posthog } from "@rallly/posthog/server";
+import { absoluteUrl } from "@rallly/utils/absolute-url";
+import type { BetterAuthPlugin } from "better-auth";
+import { APIError, betterAuth } from "better-auth";
+import { prismaAdapter } from "better-auth/adapters/prisma";
+import {
+ admin,
+ anonymous,
+ createAuthMiddleware,
+ emailOTP,
+ genericOAuth,
+ lastLoginMethod,
+} from "better-auth/plugins";
+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 { isTemporaryEmail } from "@/auth/helpers/temp-email-domains";
+import { env } from "@/env";
+import { createSpace } from "@/features/space/mutations";
+import { getLocale } from "@/i18n/server/get-locale";
+import { isKvEnabled, kv } from "@/lib/kv";
+import { auth as legacyAuth, signOut as legacySignOut } from "@/next-auth";
+import { getEmailClient } from "@/utils/emails";
+import { getValueByPath } from "@/utils/get-value-by-path";
+
+const baseURL = absoluteUrl("/api/better-auth");
+
+const plugins: BetterAuthPlugin[] = [];
+
+if (env.OIDC_CLIENT_ID && env.OIDC_CLIENT_SECRET && env.OIDC_DISCOVERY_URL) {
+ if (env.OIDC_ISSUER_URL) {
+ console.info(
+ "OIDC_ISSUER_URL is no longer used. You can remove it from your environment variables.",
+ );
+ }
+ plugins.push(
+ genericOAuth({
+ config: [
+ {
+ providerId: "oidc",
+ discoveryUrl: env.OIDC_DISCOVERY_URL,
+ clientId: env.OIDC_CLIENT_ID,
+ clientSecret: env.OIDC_CLIENT_SECRET,
+ scopes: ["openid", "profile", "email"],
+ mapProfileToUser(profile) {
+ return {
+ name: getValueByPath(profile, env.OIDC_NAME_CLAIM_PATH) as string,
+ email: getValueByPath(
+ profile,
+ env.OIDC_EMAIL_CLAIM_PATH,
+ ) as string,
+ image: getValueByPath(
+ profile,
+ env.OIDC_PICTURE_CLAIM_PATH,
+ ) as string,
+ };
+ },
+ },
+ ],
+ }),
+ );
+}
+
+export const authLib = betterAuth({
+ appName: "Rallly",
+ secret: env.SECRET_PASSWORD,
+ emailAndPassword: {
+ enabled: env.EMAIL_LOGIN_ENABLED !== "false",
+ requireEmailVerification: true,
+ sendResetPassword: async ({ user, url }) => {
+ const locale =
+ "locale" in user ? (user.locale as string) : await getLocale();
+
+ await getEmailClient(locale).sendTemplate("ResetPasswordEmail", {
+ to: user.email,
+ props: {
+ resetLink: url,
+ },
+ });
+ },
+ onPasswordReset: async ({ user }) => {
+ posthog?.capture({
+ distinctId: user.id,
+ event: "password_reset",
+ });
+ },
+ },
+ emailVerification: {
+ autoSignInAfterVerification: true,
+ },
+ database: prismaAdapter(prisma, {
+ provider: "postgresql",
+ transaction: true,
+ }),
+ plugins: [
+ ...plugins,
+ admin(),
+ anonymous(),
+ lastLoginMethod({
+ storeInDatabase: true,
+ }),
+ emailOTP({
+ disableSignUp: true,
+ expiresIn: 15 * 60,
+ overrideDefaultEmailVerification: true,
+ async sendVerificationOTP({ email, otp, type }) {
+ const locale = await getLocale(); // TODO: Get locale from email
+ const emailClient = getEmailClient(locale);
+ switch (type) {
+ // We're not actually using the sign-in type anymore since we just we have `autoSignInAfterVerification` enabled.
+ // This lets us keep things a bit simpler since we share the same verification flow for both login and registration.
+ case "sign-in":
+ await emailClient.sendTemplate("LoginEmail", {
+ to: email,
+ props: {
+ magicLink: absoluteUrl("/auth/login", {
+ code: otp,
+ email,
+ }),
+ code: otp,
+ },
+ });
+ break;
+ case "email-verification":
+ await emailClient.sendTemplate("RegisterEmail", {
+ to: email,
+ props: { code: otp },
+ });
+ break;
+ }
+ },
+ }),
+ ],
+ socialProviders: {
+ google:
+ env.GOOGLE_CLIENT_ID && env.GOOGLE_CLIENT_SECRET
+ ? {
+ clientId: env.GOOGLE_CLIENT_ID,
+ clientSecret: env.GOOGLE_CLIENT_SECRET,
+ }
+ : undefined,
+ microsoft:
+ env.MICROSOFT_CLIENT_ID && env.MICROSOFT_CLIENT_SECRET
+ ? {
+ tenantId: env.MICROSOFT_TENANT_ID,
+ clientId: env.MICROSOFT_CLIENT_ID,
+ clientSecret: env.MICROSOFT_CLIENT_SECRET,
+ }
+ : undefined,
+ },
+ user: {
+ additionalFields: {
+ timeZone: {
+ type: "string",
+ input: true,
+ },
+ locale: {
+ type: "string",
+ input: true,
+ },
+ },
+ },
+ secondaryStorage: isKvEnabled
+ ? {
+ set: async (key: string, value: string, ttl?: number) => {
+ if (ttl) {
+ await kv.set(key, value, {
+ ex: ttl,
+ });
+ } else {
+ await kv.set(key, value);
+ }
+ },
+ get: async (key: string) => {
+ return await kv.get(key);
+ },
+ delete: async (key: string) => {
+ await kv.del(key);
+ },
+ }
+ : undefined,
+ rateLimit: {
+ storage: isKvEnabled ? "secondary-storage" : "memory",
+ },
+ account: {
+ fields: {
+ providerId: "provider",
+ accountId: "providerAccountId",
+ refreshToken: "refresh_token",
+ accessToken: "access_token",
+ idToken: "id_token",
+ },
+ },
+ hooks: {
+ before: createAuthMiddleware(async (ctx) => {
+ if (
+ ctx.path.startsWith("/sign-in") ||
+ ctx.path.startsWith("/sign-up") ||
+ ctx.path.startsWith("/email-otp")
+ ) {
+ if (ctx.body?.email) {
+ if (isEmailBlocked(ctx.body.email as string)) {
+ throw new APIError("BAD_REQUEST", {
+ code: "EMAIL_BLOCKED",
+ message:
+ "This email address is not allowed. Please use a different email or contact support.",
+ });
+ }
+ if (isTemporaryEmail(ctx.body.email as string)) {
+ throw new APIError("BAD_REQUEST", {
+ code: "TEMPORARY_EMAIL_NOT_ALLOWED",
+ message:
+ "Temporary email addresses are not allowed. Please use a different email.",
+ });
+ }
+ }
+ }
+ }),
+ },
+ databaseHooks: {
+ user: {
+ create: {
+ after: async (user) => {
+ // create a space for the user
+ await createSpace({ name: "Personal", ownerId: user.id });
+
+ posthog?.capture({
+ distinctId: user.id,
+ event: "register",
+ properties: {
+ method: "sso",
+ $set: {
+ name: user.name,
+ email: user.email,
+ tier: "hobby",
+ timeZone: user.timeZone ?? undefined,
+ locale: user.locale ?? undefined,
+ },
+ },
+ });
+ },
+ },
+ },
+ session: {
+ create: {
+ after: async (session) => {
+ // Merge legacy guest users into new user
+ const legacySession = await legacyAuth();
+
+ if (legacySession) {
+ if (legacySession.user?.isGuest) {
+ await mergeGuestsIntoUser(session.userId, [
+ legacySession.user.id,
+ ]);
+ }
+ // Delete legacy session
+ await legacySignOut({
+ redirect: false,
+ });
+ }
+
+ posthog?.capture({
+ distinctId: session.userId,
+ event: "login",
+ });
+ },
+ },
+ },
+ },
+ session: {
+ expiresIn: 60 * 60 * 24 * 60, // 60 days
+ updateAge: 60 * 60 * 24, // 1 day
+ },
+ baseURL,
+});
+
+export type Auth = typeof authLib;
+
+export const getSession = cache(async () => {
+ try {
+ const session = await authLib.api.getSession({
+ headers: await headers(),
+ });
+
+ if (session) {
+ return {
+ user: {
+ id: session.user.id,
+ email: session.user.email,
+ name: session.user.name,
+ isGuest: !session.user.email,
+ image: session.user.image,
+ },
+ expires: session.session.expiresAt.toISOString(),
+ };
+ }
+ } catch (e) {
+ console.error("FAILED TO GET SESSION", e);
+ return null;
+ }
+
+ // 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();
+ } catch (e) {
+ console.error("FAILED TO GET LEGACY SESSION", e);
+ return null;
+ }
+});
+
+export const signOut = async () => {
+ await Promise.all([
+ authLib.api.signOut({
+ headers: await headers(),
+ }),
+ legacySignOut({
+ redirect: false,
+ }),
+ ]);
+};
+
+export const getUserIdIfLoggedIn = async () => {
+ const session = await getSession();
+ return session?.user?.isGuest ? undefined : session?.user?.id;
+};
diff --git a/apps/web/src/lib/kv.ts b/apps/web/src/lib/kv.ts
new file mode 100644
index 000000000..7df75eb64
--- /dev/null
+++ b/apps/web/src/lib/kv.ts
@@ -0,0 +1,5 @@
+import { kv } from "@vercel/kv";
+
+const isKvEnabled = !!process.env.KV_REST_API_URL;
+
+export { kv, isKvEnabled };
diff --git a/apps/web/src/lib/oauth/server.ts b/apps/web/src/lib/oauth/server.ts
index 2bea74716..79ee1b8b4 100644
--- a/apps/web/src/lib/oauth/server.ts
+++ b/apps/web/src/lib/oauth/server.ts
@@ -6,6 +6,7 @@ import { Hono } from "hono";
import { getCookie, setCookie } from "hono/cookie";
import { handle } from "hono/vercel";
import { z } from "zod";
+import { validateRedirectUrl } from "@/utils/redirect";
import type { CreateOAuthOptions } from "./types";
export function OAuthIntegration<T extends string>(
@@ -55,7 +56,7 @@ export function OAuthIntegration<T extends string>(
const state = generateState();
const codeVerifier = generateCodeVerifier();
- const redirectTo = c.req.query("redirect") || "/";
+ const redirectTo = validateRedirectUrl(c.req.query("redirect")) || "/";
const authorizationUrl = integration.getAuthorizationUrl(
state,
@@ -117,10 +118,7 @@ export function OAuthIntegration<T extends string>(
const codeVerifier = getCookie(c, CODE_VERIFIER);
const storedRedirect = getCookie(c, REDIRECT_TO) || "/";
- const redirectTo =
- storedRedirect.startsWith("/") && !storedRedirect.startsWith("//")
- ? storedRedirect
- : "/";
+ const redirectTo = validateRedirectUrl(storedRedirect) || "/";
// Validate OAuth callback parameters
if (
diff --git a/apps/web/src/lib/rate-limit/index.ts b/apps/web/src/lib/rate-limit/index.ts
index d616f4093..2dd8b7546 100644
--- a/apps/web/src/lib/rate-limit/index.ts
+++ b/apps/web/src/lib/rate-limit/index.ts
@@ -4,7 +4,7 @@ import { Ratelimit } from "@upstash/ratelimit";
import { kv } from "@vercel/kv";
import { headers } from "next/headers";
-import { auth } from "@/next-auth";
+import { getSession } from "@/lib/auth";
import { isRateLimitEnabled } from "./constants";
@@ -26,7 +26,7 @@ export async function rateLimit(
};
}
- const session = await auth();
+ const session = await getSession();
const identifier = session?.user?.id || (await getIPAddress());
try {
const ratelimit = new Ratelimit({
diff --git a/apps/web/src/middleware.ts b/apps/web/src/middleware.ts
index 55b61ecfa..cfa1a4b7d 100644
--- a/apps/web/src/middleware.ts
+++ b/apps/web/src/middleware.ts
@@ -1,19 +1,12 @@
+import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
-import { withAuth } from "@/auth/edge";
import { getLocaleFromRequest, setLocaleCookie } from "@/lib/locale/server";
-export const middleware = withAuth(async (req) => {
+export const middleware = async (req: NextRequest) => {
const { nextUrl } = req;
const newUrl = nextUrl.clone();
const pathname = newUrl.pathname;
- const isLoggedIn = req.auth?.user?.email;
- // if the user is already logged in, don't let them access the login page
- if (/^\/(login)/.test(pathname) && isLoggedIn) {
- newUrl.pathname = "/";
- return NextResponse.redirect(newUrl);
- }
-
const locale = getLocaleFromRequest(req);
newUrl.pathname = `/${locale}${pathname}`;
@@ -26,7 +19,7 @@ export const middleware = withAuth(async (req) => {
res.headers.set("x-pathname", pathname);
return res;
-});
+};
export const config = {
matcher: ["/((?!api|_next/static|_next/image|static|.*\\.).*)"],
diff --git a/apps/web/src/next-auth.config.ts b/apps/web/src/next-auth.config.ts
index 2b93fb476..955de2ebb 100644
--- a/apps/web/src/next-auth.config.ts
+++ b/apps/web/src/next-auth.config.ts
@@ -1,14 +1,6 @@
-import { NextResponse } from "next/server";
import type { NextAuthConfig } from "next-auth";
import { env } from "@/env";
-import { isQuickCreateEnabled } from "@/features/quick-create/constants";
-
-const publicRoutes = ["/login", "/register", "/invite/", "/poll/", "/auth"];
-
-if (isQuickCreateEnabled) {
- publicRoutes.push("/quick-create", "/new");
-}
/**
* We split the next-auth config so that we can create an edge compatible instance that is
@@ -29,21 +21,5 @@ export const nextAuthConfig = {
session.user.weekStart = token.weekStart;
return session;
},
- async authorized({ request, auth }) {
- const { nextUrl } = request;
- const isLoggedIn = !!auth?.user?.email;
- const isPublicRoute = publicRoutes.some((route) =>
- nextUrl.pathname.startsWith(route),
- );
- if (isLoggedIn || isPublicRoute) {
- return true;
- }
- const redirectUrl = new URL("/login", request.url);
- if (nextUrl.pathname !== "/") {
- const redirectPath = nextUrl.pathname + nextUrl.search;
- redirectUrl.searchParams.set("redirectTo", redirectPath);
- }
- return NextResponse.redirect(redirectUrl);
- },
},
} satisfies NextAuthConfig;
diff --git a/apps/web/src/next-auth.ts b/apps/web/src/next-auth.ts
index b8ae7c0b8..1d0271b2e 100644
--- a/apps/web/src/next-auth.ts
+++ b/apps/web/src/next-auth.ts
@@ -1,10 +1,8 @@
+import { PrismaAdapter } from "@auth/prisma-adapter";
import { prisma } from "@rallly/database";
import { posthog } from "@rallly/posthog/server";
import NextAuth from "next-auth";
import type { Provider } from "next-auth/providers";
-import { cache } from "react";
-
-import { CustomPrismaAdapter } from "./auth/adapters/prisma";
import { isEmailBanned, isEmailBlocked } from "./auth/helpers/is-email-blocked";
import { mergeGuestsIntoUser } from "./auth/helpers/merge-user";
import { EmailProvider } from "./auth/providers/email";
@@ -15,21 +13,9 @@ import { OIDCProvider } from "./auth/providers/oidc";
import { RegistrationTokenProvider } from "./auth/providers/registration-token";
import { nextAuthConfig } from "./next-auth.config";
-const {
- auth: originalAuth,
- handlers,
- signIn,
- signOut,
-} = NextAuth({
+const { auth, handlers, signIn, signOut } = NextAuth({
...nextAuthConfig,
- adapter: CustomPrismaAdapter({
- migrateData: async (userId) => {
- const session = await auth();
- if (session?.user && session.user.email === null) {
- await mergeGuestsIntoUser(userId, [session.user.id]);
- }
- },
- }),
+ adapter: PrismaAdapter(prisma),
providers: [
RegistrationTokenProvider,
GuestProvider,
@@ -172,29 +158,4 @@ const {
},
});
-const auth = cache(async () => {
- try {
- const session = await originalAuth();
- if (session) {
- return session;
- }
- } catch (e) {
- console.error("FAILED TO GET SESSION", e);
- }
-});
-
-/**
- * If email is not set it means the user is a guest
- * @returns
- */
-export const getUserId = async () => {
- const session = await auth();
- return session?.user?.email ? session.user.id : undefined;
-};
-
-export const getLoggedIn = async () => {
- const session = await auth();
- return !!session?.user?.email;
-};
-
export { auth, handlers, signIn, signOut };
diff --git a/apps/web/src/trpc/client/provider.tsx b/apps/web/src/trpc/client/provider.tsx
index 70f578ce0..6e72a5106 100644
--- a/apps/web/src/trpc/client/provider.tsx
+++ b/apps/web/src/trpc/client/provider.tsx
@@ -7,10 +7,10 @@ import {
QueryClientProvider,
} from "@tanstack/react-query";
import { httpBatchLink, TRPCClientError } from "@trpc/client";
-import { signOut } from "next-auth/react";
import { useState } from "react";
import superjson from "superjson";
import { useTranslation } from "@/i18n/client";
+import { signOut } from "@/lib/auth-client";
import { trpc } from "../client";
export function TRPCProvider(props: { children: React.ReactNode }) {
@@ -50,12 +50,7 @@ export function TRPCProvider(props: { children: React.ReactNode }) {
);
break;
case "FORBIDDEN":
- signOut({
- redirect: false,
- }).then(() => {
- window.location.href = "/login";
- });
-
+ signOut();
break;
default:
console.error(error);
diff --git a/apps/web/src/trpc/routers/auth.ts b/apps/web/src/trpc/routers/auth.ts
index a677186ea..0a017d99e 100644
--- a/apps/web/src/trpc/routers/auth.ts
+++ b/apps/web/src/trpc/routers/auth.ts
@@ -130,7 +130,7 @@ export const auth = router({
const user = await createUser({
name,
email,
- emailVerified: new Date(),
+ emailVerified: true,
timeZone: input.timeZone,
timeFormat: input.timeFormat,
weekStart: input.weekStart,
diff --git a/apps/web/src/trpc/server/create-ssr-helper.ts b/apps/web/src/trpc/server/create-ssr-helper.ts
index ee362914c..73ee6ba40 100644
--- a/apps/web/src/trpc/server/create-ssr-helper.ts
+++ b/apps/web/src/trpc/server/create-ssr-helper.ts
@@ -2,18 +2,18 @@ import { createServerSideHelpers } from "@trpc/react-query/server";
import { redirect } from "next/navigation";
import superjson from "superjson";
-import { auth } from "@/next-auth";
+import { getSession } from "@/lib/auth";
import type { TRPCContext } from "../context";
import { appRouter } from "../routers";
async function createContext(): Promise<TRPCContext> {
- const session = await auth();
+ const session = await getSession();
return {
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,
}
diff --git a/apps/web/src/utils/redirect.ts b/apps/web/src/utils/redirect.ts
new file mode 100644
index 000000000..07b4c56e9
--- /dev/null
+++ b/apps/web/src/utils/redirect.ts
@@ -0,0 +1,25 @@
+/**
+ * Validates a redirect URL to prevent open redirect attacks.
+ * Only allows relative URLs starting with "/" but not "//" (protocol-relative).
+ *
+ * @param redirectTo - The redirect URL to validate
+ * @returns The valid redirect URL or undefined if invalid
+ */
+export function validateRedirectUrl(
+ redirectTo?: string | null,
+): string | undefined {
+ if (!redirectTo) {
+ return undefined;
+ }
+
+ // Trim whitespace
+ const trimmed = redirectTo.trim();
+
+ // Only allow relative URLs starting with "/" but not "//"
+ if (trimmed.startsWith("/") && !trimmed.startsWith("//")) {
+ return trimmed;
+ }
+
+ // Return undefined for invalid redirects, let caller decide the default
+ return undefined;
+}
diff --git a/apps/web/tests/authentication.spec.ts b/apps/web/tests/authentication.spec.ts
index a45b1b123..53a0d3c92 100644
--- a/apps/web/tests/authentication.spec.ts
+++ b/apps/web/tests/authentication.spec.ts
@@ -1,14 +1,15 @@
import { expect, test } from "@playwright/test";
import { prisma } from "@rallly/database";
-import { load } from "cheerio";
-import { captureEmailHTML } from "./mailpit/mailpit";
import { RegisterPage } from "./register-page";
import { createUserInDb, loginWithEmail } from "./test-utils";
-import { getCode } from "./utils";
+import { getCode, getPasswordResetLink } from "./utils";
const testUserEmail = "[email protected]";
const testExistingUserEmail = "[email protected]";
+const testPassword = "TestPassword123!";
+
+
test.describe.serial(() => {
test.afterAll(async () => {
@@ -30,7 +31,7 @@ test.describe.serial(() => {
.getByPlaceholder("[email protected]")
.fill(testUserEmail);
- await page.getByRole("button", { name: "Continue with Email" }).click();
+ await page.getByRole("button", { name: "Continue with email" }).click();
// Make sure the user doesn't exist yet and that logging in is not possible
await expect(
@@ -44,11 +45,12 @@ test.describe.serial(() => {
await registerPage.register({
name: "Test User",
email: testUserEmail,
+ password: testPassword,
});
});
});
- test.describe("existing user", () => {
+ test.describe("Existing User", () => {
test("can't register with the same email", async ({ page }) => {
await page.goto("/register");
@@ -58,6 +60,7 @@ test.describe.serial(() => {
await page
.getByPlaceholder("[email protected]")
.fill(testUserEmail);
+ await page.getByPlaceholder("••••••••").fill(testPassword);
await page.getByRole("button", { name: "Continue", exact: true }).click();
@@ -66,32 +69,24 @@ test.describe.serial(() => {
).toBeVisible();
});
- test("can login with magic link", async ({ page }) => {
+ test("can login with password", async ({ page }) => {
await page.goto("/login");
await page
.getByPlaceholder("[email protected]")
.fill(testUserEmail);
- await page.getByRole("button", { name: "Continue with Email" }).click();
-
- const html = await captureEmailHTML(testUserEmail);
-
- const $ = load(html);
-
- const magicLink = $("#magicLink").attr("href");
+ await page.getByRole("button", { name: "Continue with email" }).click();
- if (!magicLink) {
- throw new Error("Magic link not found");
- }
+ // Password field should appear since user has a credential account
+ await page.getByPlaceholder("••••••••").waitFor();
+ await page.getByPlaceholder("••••••••").fill(testPassword);
- await page.goto(magicLink);
-
- await page.getByRole("button", { name: "Login", exact: true }).click();
+ await page.getByRole("button", { name: "Login with password" }).click();
await expect(page.getByText("Test User")).toBeVisible();
});
-
+
test("shows error for invalid verification code", async ({ page }) => {
await page.goto("/login");
@@ -99,7 +94,11 @@ test.describe.serial(() => {
.getByPlaceholder("[email protected]")
.fill(testUserEmail);
- await page.getByRole("button", { name: "Continue with Email" }).click();
+ await page.getByRole("button", { name: "Continue with email" }).click();
+
+ expect(page.getByPlaceholder("••••••••")).toBeVisible();
+
+ await page.getByRole("button", { name: "Login with email" }).click();
await page.getByPlaceholder("Enter your 6-digit code").fill("000000");
@@ -115,7 +114,11 @@ test.describe.serial(() => {
.getByPlaceholder("[email protected]")
.fill(testUserEmail);
- await page.getByRole("button", { name: "Continue with Email" }).click();
+ await page.getByRole("button", { name: "Continue with email" }).click();
+
+ expect(page.getByPlaceholder("••••••••")).toBeVisible();
+
+ await page.getByRole("button", { name: "Login with email" }).click();
const code = await getCode(testUserEmail);
@@ -126,22 +129,223 @@ test.describe.serial(() => {
test("allow using different case in email", async ({ page }) => {
await page.goto("/login");
-
+ const testDifferentCaseEmail = "[email protected]"; // different case than the test user email
await page
.getByPlaceholder("[email protected]")
- .fill("[email protected]");
-
- await page.getByRole("button", { name: "Continue with Email" }).click();
+ .fill(testDifferentCaseEmail);
- const code = await getCode(testUserEmail);
+ await page.getByRole("button", { name: "Continue with email" }).click();
- await page.getByPlaceholder("Enter your 6-digit code").fill(code);
+ await page.getByPlaceholder("••••••••").fill(testPassword);
+
+ await page.getByRole("button", { name: "Login with password" }).click();
await expect(page.getByText("Test User")).toBeVisible();
});
+
+ test.describe("Password Reset", () => {
+ test("can access forgot password page from login", async ({ page }) => {
+ await page.goto("/login");
+
+ // Wait for login page to load
+ await page.getByText("Welcome").waitFor();
+
+ // Enter email to trigger password field rendering
+ await page.getByPlaceholder("[email protected]").fill(testUserEmail);
+ await page.getByRole("button", { name: "Continue with email" }).click();
+
+ // Password field should now be visible since user has a credential account
+ await page.getByPlaceholder("••••••••").waitFor();
+
+ // Now click forgot password link
+ await page.getByRole("link", { name: "Forgot password?" }).click();
+
+ // Verify we're on the forgot password page
+ await expect(page).toHaveURL(/\/forgot-password/);
+ await expect(page.getByRole("heading", { name: "Forgot Password" })).toBeVisible();
+
+ // Verify email is pre-filled as a UX improvement
+ const emailInput = page.getByPlaceholder("[email protected]");
+ await expect(emailInput).toHaveValue(testUserEmail);
+ });
+
+ test("can request password reset with email", async ({ page }) => {
+ await page.goto("/forgot-password");
+
+ // Wait for forgot password page to load
+ await page.getByRole("heading", { name: "Forgot Password" }).waitFor();
+
+ // Fill in email
+ await page.getByPlaceholder("[email protected]").fill(testUserEmail);
+
+ // Submit form
+ await page.getByRole("button", { name: "Send reset link" }).click();
+
+ // Verify success message
+ await expect(page.getByText("Check your email", {
+ exact: true,
+ })).toBeVisible();
+ await expect(
+ page.getByText(/sent a password reset link to your inbox/),
+ ).toBeVisible();
+ });
+
+ test("doesn't reveal whether email exists in system", async ({ page }) => {
+ await page.goto("/forgot-password");
+
+ // Fill in non-existent email
+ await page
+ .getByPlaceholder("[email protected]")
+ .fill("[email protected]");
+
+ // Submit form
+ await page.getByRole("button", { name: "Send reset link" }).click();
+
+ // Should show the same success message for both existing and non-existing emails
+ // This prevents email enumeration attacks
+ await expect(page.getByText("Check your email", {
+ exact: true,
+ })).toBeVisible();
+ });
+
+ test("displays back to login link on forgot password page", async ({ page }) => {
+ await page.goto("/forgot-password");
+
+ // Verify back to login link
+ await page.getByRole("link", { name: "Back to login" }).click();
+
+ // Should be redirected to login
+ await expect(page).toHaveURL(/\/login/);
+ });
+
+ test("can reset password with valid token", async ({ page }) => {
+ // Request a password reset
+ await page.goto("/forgot-password");
+ await page
+ .getByPlaceholder("[email protected]")
+ .fill(testUserEmail);
+ await page.getByRole("button", { name: "Send reset link" }).click();
+
+ // Get the reset token from email
+ const resetLink = await getPasswordResetLink(testUserEmail);
+
+ // Navigate to reset password page with token
+ await page.goto(resetLink);
+
+ // Verify we're on the reset password page
+ await expect(page.getByRole("heading", { name: "Reset Password" })).toBeVisible();
+
+ // Fill in new password
+ const newPassword = "NewPassword456!";
+ await page.getByLabel("Password").fill(newPassword);
+
+ // Submit form
+ await page.getByRole("button", { name: "Reset password" }).click();
+
+ // Should be redirected to login
+ await expect(page).toHaveURL(/\/login/);
+ });
+
+ test("shows error for invalid token", async ({ page }) => {
+ // Navigate to reset password with invalid token
+ await page.goto("/reset-password?token=invalid-token-123");
+
+ // Fill fields and submit
+ await page.getByLabel("Password").fill("NewPassword456!");
+ await page.getByRole("button", { name: "Reset password" }).click();
+
+ // Should show error message
+ await expect(page.getByText("Invalid token")).toBeVisible();
+ });
+
+ test("shows error when token is missing", async ({ page }) => {
+ // Navigate to reset password without token
+ await page.goto("/reset-password");
+
+ // Should show error message
+ await expect(page.getByText(/password reset link is invalid/i)).toBeVisible();
+ });
+
+ test("can login with new password after reset", async ({ page }) => {
+ // First, reset the password
+ await page.goto("/forgot-password");
+ await page
+ .getByPlaceholder("[email protected]")
+ .fill(testUserEmail);
+ await page.getByRole("button", { name: "Send reset link" }).click();
+
+ // Get the reset token
+ const resetLink = await getPasswordResetLink(testUserEmail);
+
+ // Reset to a new password
+ const finalPassword = "FinalPassword789!";
+ await page.goto(resetLink);
+ await page.getByLabel("Password").fill(finalPassword);
+ await page.getByRole("button", { name: "Reset password" }).click();
+
+ // Now try to login with the new password
+ await page.goto("/login");
+ await page
+ .getByPlaceholder("[email protected]")
+ .fill(testUserEmail);
+ await page.getByRole("button", { name: "Continue with email" }).click();
+
+ await page.getByLabel("Password").fill(finalPassword);
+ await page.getByRole("button", { name: "Login with password" }).click();
+
+ // Should be logged in
+ await expect(page.getByText("Test User")).toBeVisible();
+ });
+
+ test("displays back to login link on reset page", async ({ page }) => {
+ // Request a password reset to get a valid token
+ await page.goto("/forgot-password");
+ await page
+ .getByPlaceholder("[email protected]")
+ .fill(testUserEmail);
+ await page.getByRole("button", { name: "Send reset link" }).click();
+
+ const resetLink = await getPasswordResetLink(testUserEmail);
+
+ // Navigate to reset password page
+ await page.goto(resetLink);
+
+ // Verify back to login link exists
+ await page.getByRole("link", { name: "Back to login" }).click();
+
+ // Should be redirected to login
+ await expect(page).toHaveURL(/\/login/);
+ });
+
+ test("prevents redirects to external sites", async ({ page }) => {
+ // Request a password reset
+ await page.goto("/forgot-password");
+ await page
+ .getByPlaceholder("[email protected]")
+ .fill(testUserEmail);
+ await page.getByRole("button", { name: "Send reset link" }).click();
+
+ const resetLink = await getPasswordResetLink(testUserEmail);
+
+ // Try to use redirect injection
+ await page.goto(
+ `${resetLink}&redirectTo=https://evil.com`,
+ );
+
+ // Fill in password
+ const safePassword = "SafePassword123!";
+ await page.getByLabel("Password").fill(safePassword);
+
+ // Submit form
+ await page.getByRole("button", { name: "Reset password" }).click();
+
+ // Should redirect to login, not external site
+ await expect(page).toHaveURL(/\/login/);
+ });
+ });
});
- test.describe("when user registration is disabled", () => {
+ test.describe("When User Registration is Disabled", () => {
test.beforeAll(async () => {
await prisma.instanceSettings.update({
where: { id: 1 },
diff --git a/apps/web/tests/guest-to-user-migration.spec.ts b/apps/web/tests/guest-to-user-migration.spec.ts
index 313fc0b50..eaa56aa15 100644
--- a/apps/web/tests/guest-to-user-migration.spec.ts
+++ b/apps/web/tests/guest-to-user-migration.spec.ts
@@ -6,7 +6,11 @@ import { LoginPage } from "./login-page";
import { deleteAllMessages } from "./mailpit/mailpit";
import { RegisterPage } from "./register-page";
-const TEST_USER_EMAIL = "[email protected]";
+const testUser = {
+ name: "Test User",
+ email: "[email protected]",
+ password: "TestPassword456!",
+};
test.describe.serial(() => {
test.beforeAll(async () => {
@@ -17,7 +21,7 @@ test.describe.serial(() => {
// Clean up the test user
await prisma.user.delete({
where: {
- email: TEST_USER_EMAIL,
+ email: testUser.email,
},
});
});
@@ -36,10 +40,7 @@ test.describe.serial(() => {
// Step 3: Complete registration
const registerPage = new RegisterPage(page);
- await registerPage.register({
- name: "Test User",
- email: TEST_USER_EMAIL,
- });
+ await registerPage.register(testUser);
await expect(page.getByTestId("poll-title")).toHaveText("Monthly Meetup");
});
@@ -59,7 +60,8 @@ test.describe.serial(() => {
// Step 3: Complete lplogin
const loginPage = new LoginPage(page);
await loginPage.login({
- email: TEST_USER_EMAIL,
+ email: testUser.email,
+ password: testUser.password,
});
// Step 4: Navigate back to the poll
diff --git a/apps/web/tests/login-page.ts b/apps/web/tests/login-page.ts
index a8f53becc..24d35e4ab 100644
--- a/apps/web/tests/login-page.ts
+++ b/apps/web/tests/login-page.ts
@@ -10,18 +10,29 @@ export class LoginPage {
await this.page.getByText("Welcome").waitFor();
}
- async login({ email }: { email: string }) {
- // Fill in registration form
+ async login({ email, password }: { email: string; password?: string }) {
+ // Fill in email
await this.page.getByPlaceholder("[email protected]").fill(email);
await this.page
- .getByRole("button", { name: "Continue with Email", exact: true })
+ .getByRole("button", { name: "Continue with email" })
.click();
- // Handle verification code
- const code = await getCode(email);
- await this.page.getByRole("heading", { name : "Finish Logging In" }).waitFor();
- await this.page.getByPlaceholder("Enter your 6-digit code").fill(code);
+ // If password is provided and the password field appears, use password login
+ if (password) {
+ await this.page.getByLabel("Password").fill(password);
+
+ await this.page
+ .getByRole("button", { name: "Login with password" })
+ .click();
+
+ } else {
+ // Handle verification code for email OTP login
+ const code = await getCode(email);
+ await this.page.getByRole("heading", { name : "Finish Logging In" }).waitFor();
+ await this.page.getByPlaceholder("Enter your 6-digit code").fill(code);
+
+ }
// Wait for page to load
await this.page.waitForLoadState("networkidle");
diff --git a/apps/web/tests/register-page.ts b/apps/web/tests/register-page.ts
index 5b88c372d..ae291a61d 100644
--- a/apps/web/tests/register-page.ts
+++ b/apps/web/tests/register-page.ts
@@ -11,10 +11,11 @@ export class RegisterPage {
await this.page.getByText("Create Your Account").waitFor();
}
- async register({ name, email }: { name: string; email: string }) {
+ async register({ name, email, password }: { name: string; email: string; password: string }) {
// Fill in registration form
await this.page.getByPlaceholder("Jessie Smith").fill(name);
await this.page.getByPlaceholder("[email protected]").fill(email);
+ await this.page.getByPlaceholder("••••••••").fill(password);
await this.page
.getByRole("button", { name: "Continue", exact: true })
@@ -22,7 +23,7 @@ export class RegisterPage {
// Handle verification code
const code = await getCode(email);
- await this.page.getByText("Finish Registering").waitFor();
+ await this.page.getByText("Finish Logging In").waitFor();
await this.page.getByPlaceholder("Enter your 6-digit code").fill(code);
// Verify successful registration
diff --git a/apps/web/tests/test-utils.ts b/apps/web/tests/test-utils.ts
index 411e72e29..46ae14518 100644
--- a/apps/web/tests/test-utils.ts
+++ b/apps/web/tests/test-utils.ts
@@ -21,7 +21,7 @@ export async function createUserInDb({
role,
locale: "en",
timeZone: "Europe/London",
- emailVerified: new Date(),
+ emailVerified: true,
},
});
@@ -123,10 +123,11 @@ export async function createTestPoll({
});
}
-export async function loginWithEmail(page: Page, { email }: { email: string }) {
+export async function loginWithEmail(page: Page, { email, password }: { email: string; password?: string }) {
const loginPage = new LoginPage(page);
await loginPage.goto();
await loginPage.login({
email,
+ password,
});
}
diff --git a/apps/web/tests/utils.ts b/apps/web/tests/utils.ts
index 3a94ab8da..5d89e07d2 100644
--- a/apps/web/tests/utils.ts
+++ b/apps/web/tests/utils.ts
@@ -14,3 +14,18 @@ export const getCode = async (email: string) => {
return $("#code").text().trim();
};
+
+/**
+ * Extract the password reset link from the email HTML
+ */
+export async function getPasswordResetLink(email: string): Promise<string> {
+ const html = await captureEmailHTML(email);
+ const $ = load(html);
+
+ const resetLink = $("#resetLink").attr("href");
+ if (!resetLink) {
+ throw new Error("Reset link not found in email");
+ }
+
+ return resetLink;
+}
\ No newline at end of file
diff --git a/packages/database/prisma/migrations/20251014054941_better_auth/migration.sql b/packages/database/prisma/migrations/20251014054941_better_auth/migration.sql
new file mode 100644
index 000000000..cbf40d165
--- /dev/null
+++ b/packages/database/prisma/migrations/20251014054941_better_auth/migration.sql
@@ -0,0 +1,72 @@
+/*
+ Warnings:
+
+ - You are about to drop the column `session_state` on the `accounts` table. All the data in the column will be lost.
+ - You are about to drop the column `token_type` on the `accounts` table. All the data in the column will be lost.
+ - You are about to drop the column `type` on the `accounts` table. All the data in the column will be lost.
+ - The `email_verified` column on the `users` table is being converted from TIMESTAMP to BOOLEAN. Existing verification status is preserved.
+ - Added the required column `updated_at` to the `accounts` table without a default value. This is not possible if the table is not empty.
+
+*/
+-- AlterTable
+ALTER TABLE "accounts" DROP COLUMN "session_state",
+DROP COLUMN "token_type",
+DROP COLUMN "type",
+ADD COLUMN "access_token_expires_at" TIMESTAMP(3),
+ADD COLUMN "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ADD COLUMN "password" TEXT,
+ADD COLUMN "refresh_token_expires_at" TIMESTAMP(3),
+ADD COLUMN "updated_at" TIMESTAMP(3);
+
+-- Update existing accounts with updated_at
+UPDATE "accounts" SET "updated_at" = "created_at"
+WHERE "updated_at" IS NULL;
+
+-- Make updated_at not nullable
+ALTER TABLE "accounts" ALTER COLUMN "updated_at" SET NOT NULL;
+
+-- AlterTable - Preserve existing email verification status
+-- First add the new boolean column
+ALTER TABLE "users" ADD COLUMN "email_verified_boolean" BOOLEAN;
+
+-- Convert existing DateTime values to BOOLEAN (NULL stays NULL, any timestamp becomes TRUE)
+UPDATE "users" SET "email_verified_boolean" = CASE
+ WHEN "email_verified" IS NOT NULL THEN TRUE
+ ELSE NULL
+END;
+
+-- Drop the old column and rename the new one
+ALTER TABLE "users" DROP COLUMN "email_verified";
+ALTER TABLE "users" RENAME COLUMN "email_verified_boolean" TO "email_verified";
+
+-- CreateTable
+CREATE TABLE "sessions" (
+ "id" TEXT NOT NULL,
+ "expires_at" TIMESTAMP(3) NOT NULL,
+ "token" TEXT NOT NULL,
+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updated_at" TIMESTAMP(3) NOT NULL,
+ "ip_address" TEXT,
+ "user_agent" TEXT,
+ "user_id" TEXT NOT NULL,
+
+ CONSTRAINT "sessions_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateTable
+CREATE TABLE "verifications" (
+ "id" TEXT NOT NULL,
+ "identifier" TEXT NOT NULL,
+ "value" TEXT NOT NULL,
+ "expires_at" TIMESTAMP(3) NOT NULL,
+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+
+ CONSTRAINT "verifications_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateIndex
+CREATE UNIQUE INDEX "sessions_token_key" ON "sessions"("token");
+
+-- AddForeignKey
+ALTER TABLE "sessions" ADD CONSTRAINT "sessions_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
diff --git a/packages/database/prisma/migrations/20251021132911_add_better_auth_admin_fields/migration.sql b/packages/database/prisma/migrations/20251021132911_add_better_auth_admin_fields/migration.sql
new file mode 100644
index 000000000..ddec36c93
--- /dev/null
+++ b/packages/database/prisma/migrations/20251021132911_add_better_auth_admin_fields/migration.sql
@@ -0,0 +1,8 @@
+-- AlterTable
+ALTER TABLE "sessions" ADD COLUMN "impersonated_by" TEXT;
+
+-- AlterTable
+ALTER TABLE "users" ADD COLUMN "ban_expires" TIMESTAMP(3);
+
+-- AddForeignKey
+ALTER TABLE "sessions" ADD CONSTRAINT "sessions_impersonated_by_fkey" FOREIGN KEY ("impersonated_by") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;
diff --git a/packages/database/prisma/migrations/20251021160519_add_last_login_method/migration.sql b/packages/database/prisma/migrations/20251021160519_add_last_login_method/migration.sql
new file mode 100644
index 000000000..73a774eb1
--- /dev/null
+++ b/packages/database/prisma/migrations/20251021160519_add_last_login_method/migration.sql
@@ -0,0 +1,2 @@
+-- AlterTable
+ALTER TABLE "users" ADD COLUMN "last_login_method" TEXT;
diff --git a/packages/database/prisma/models/user.prisma b/packages/database/prisma/models/user.prisma
index 07ba6dcc5..6c03173b8 100644
--- a/packages/database/prisma/models/user.prisma
+++ b/packages/database/prisma/models/user.prisma
@@ -8,19 +8,22 @@ enum TimeFormat {
model Account {
id String @id @default(cuid())
userId String @map("user_id")
- type String
provider String
providerAccountId String @map("provider_account_id")
refresh_token String? @db.Text
access_token String? @db.Text
expires_at Int?
- token_type String?
scope String?
id_token String? @db.Text
- session_state String?
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
+ accessTokenExpiresAt DateTime? @map("access_token_expires_at")
+ refreshTokenExpiresAt DateTime? @map("refresh_token_expires_at")
+ password String? @map("password")
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @updatedAt @map("updated_at")
+
@@unique([provider, providerAccountId])
@@map("accounts")
}
@@ -33,22 +36,24 @@ enum UserRole {
}
model User {
- id String @id @default(cuid())
- name String
- email String @unique() @db.Citext
- emailVerified DateTime? @map("email_verified")
- image String?
- timeZone String? @map("time_zone")
- weekStart Int? @map("week_start")
- timeFormat TimeFormat? @map("time_format")
- locale String?
- createdAt DateTime @default(now()) @map("created_at")
- updatedAt DateTime? @updatedAt @map("updated_at")
- customerId String? @map("customer_id")
- banned Boolean @default(false)
- bannedAt DateTime? @map("banned_at")
- banReason String? @map("ban_reason")
- role UserRole @default(user)
+ id String @id @default(cuid())
+ name String
+ email String @unique @db.Citext
+ emailVerified Boolean? @map("email_verified")
+ image String?
+ timeZone String? @map("time_zone")
+ weekStart Int? @map("week_start")
+ timeFormat TimeFormat? @map("time_format")
+ locale String?
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime? @updatedAt @map("updated_at")
+ customerId String? @map("customer_id")
+ banned Boolean @default(false)
+ bannedAt DateTime? @map("banned_at")
+ banReason String? @map("ban_reason")
+ banExpires DateTime? @map("ban_expires")
+ role UserRole @default(user)
+ lastLoginMethod String? @map("last_login_method")
comments Comment[]
polls Poll[]
@@ -73,6 +78,9 @@ model User {
defaultDestinationCalendarId String? @map("default_destination_calendar_id")
defaultDestinationCalendar ProviderCalendar? @relation("UserDefaultDestinationCalendar", fields: [defaultDestinationCalendarId], references: [id], onDelete: SetNull)
+ sessions Session[]
+ impersonatedSessions Session[] @relation("ImpersonatedSessions")
+
@@map("users")
}
@@ -84,3 +92,32 @@ model VerificationToken {
@@unique([identifier, token])
@@map("verification_tokens")
}
+
+model Session {
+ id String @id
+ expiresAt DateTime @map("expires_at")
+ token String
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @updatedAt @map("updated_at")
+ ipAddress String? @map("ip_address")
+ userAgent String? @map("user_agent")
+ userId String @map("user_id")
+ impersonatedBy String? @map("impersonated_by")
+
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
+ impersonatedByUser User? @relation("ImpersonatedSessions", fields: [impersonatedBy], references: [id])
+
+ @@unique([token])
+ @@map("sessions")
+}
+
+model Verification {
+ id String @id
+ identifier String
+ value String
+ expiresAt DateTime @map("expires_at")
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
+
+ @@map("verifications")
+}
diff --git a/packages/emails/locales/en/emails.json b/packages/emails/locales/en/emails.json
index 5f694ead5..022e7d0cc 100644
--- a/packages/emails/locales/en/emails.json
+++ b/packages/emails/locales/en/emails.json
@@ -37,7 +37,6 @@
"newPoll_heading": "New Poll Created",
"newPoll_button": "Manage Poll",
"newPoll_subject": "Let's find a date for {title}!",
- "register_footer": "You're receiving this email because a request was made to register an account on <domain />. If this wasn't you, please ignore this email.",
"register_preview": "Your 6-digit code is: {code}",
"register_heading": "Verify your email address",
"register_text": "Please use the following 6-digit verification code to verify your email",
@@ -83,5 +82,11 @@
"spaceInvite_preview": "You've been invited to join {spaceName}",
"spaceInvite_heading": "You're invited!",
"spaceInvite_button": "Accept Invitation",
- "spaceInvite_subject": "You're invited to join {spaceName}"
+ "spaceInvite_subject": "You're invited to join {spaceName}",
+ "resetPassword_button": "Reset password",
+ "resetPassword_content2": "If you didn't request a password reset, you can ignore this email. Your password will not change unless you create a new one. If this request is suspicious, contact <a>{supportEmail}</a>.",
+ "resetPassword_preview": "Use this link to reset your password.",
+ "resetPassword_heading": "Reset your password",
+ "resetPassword_content": "We received a request to reset your password. Click the button below to create a new password.",
+ "resetPassword_subject": "Reset your password"
}
diff --git a/packages/emails/src/templates.ts b/packages/emails/src/templates.ts
index 18ef50b1c..67c04e3a4 100644
--- a/packages/emails/src/templates.ts
+++ b/packages/emails/src/templates.ts
@@ -10,6 +10,7 @@ import { NewParticipantEmail } from "./templates/new-participant";
import { NewParticipantConfirmationEmail } from "./templates/new-participant-confirmation";
import { NewPollEmail } from "./templates/new-poll";
import { RegisterEmail } from "./templates/register";
+import { ResetPasswordEmail } from "./templates/reset-password";
import { SpaceInviteEmail } from "./templates/space-invite";
import type { TemplateName } from "./types";
@@ -22,6 +23,7 @@ const templates = {
NewParticipantConfirmationEmail,
NewPollEmail,
RegisterEmail,
+ ResetPasswordEmail,
ChangeEmailRequest,
AbandonedCheckoutEmail,
LicenseKeyEmail,
diff --git a/packages/emails/src/templates/register.tsx b/packages/emails/src/templates/register.tsx
index 13a99f85e..9f39a2bdb 100644
--- a/packages/emails/src/templates/register.tsx
+++ b/packages/emails/src/templates/register.tsx
@@ -6,6 +6,7 @@ import {
Card,
Domain,
Heading,
+ Link,
Text,
trackingWide,
} from "../components/styled-components";
@@ -63,13 +64,14 @@ export const RegisterEmail = ({ code, ctx }: RegisterEmailProps) => {
<Trans
i18n={ctx.i18n}
t={ctx.t}
- i18nKey="register_footer"
- ns="emails"
- values={{ domain: ctx.domain }}
+ i18nKey="login_content2"
+ defaults="You're receiving this email because a request was made to login to <domain />. If this wasn't you contact <a>{supportEmail}</a>."
+ values={{ supportEmail: ctx.supportEmail }}
components={{
domain: <Domain ctx={ctx} />,
+ a: <Link href={`mailto:${ctx.supportEmail}`} />,
}}
- defaults="You're receiving this email because a request was made to register an account on <domain />. If this wasn't you, please ignore this email."
+ ns="emails"
/>
</Text>
</Section>
diff --git a/packages/emails/src/templates/reset-password.tsx b/packages/emails/src/templates/reset-password.tsx
new file mode 100644
index 000000000..2677703bf
--- /dev/null
+++ b/packages/emails/src/templates/reset-password.tsx
@@ -0,0 +1,76 @@
+import { Section } from "@react-email/components";
+import { Trans } from "react-i18next/TransWithoutContext";
+
+import { EmailLayout } from "../components/email-layout";
+import { Button, Heading, Link, Text } from "../components/styled-components";
+import type { EmailContext } from "../types";
+
+interface ResetPasswordEmailProps {
+ resetLink: string;
+ ctx: EmailContext;
+}
+
+export const ResetPasswordEmail = ({
+ resetLink,
+ ctx,
+}: ResetPasswordEmailProps) => {
+ return (
+ <EmailLayout
+ ctx={ctx}
+ preview={ctx.t("resetPassword_preview", {
+ defaultValue: "Use this link to reset your password.",
+ ns: "emails",
+ })}
+ >
+ <Heading>
+ {ctx.t("resetPassword_heading", {
+ defaultValue: "Reset your password",
+ ns: "emails",
+ })}
+ </Heading>
+ <Text>
+ {ctx.t("resetPassword_content", {
+ defaultValue:
+ "We received a request to reset your password. Click the button below to create a new password.",
+ ns: "emails",
+ })}
+ </Text>
+ <Section style={{ marginBottom: 32 }}>
+ <Button href={resetLink} id="resetLink">
+ <Trans
+ i18n={ctx.i18n}
+ t={ctx.t}
+ i18nKey="resetPassword_button"
+ defaults="Reset password"
+ ns="emails"
+ />
+ </Button>
+ </Section>
+ <Text light>
+ <Trans
+ i18n={ctx.i18n}
+ t={ctx.t}
+ i18nKey="resetPassword_content2"
+ defaults="If you didn't request a password reset, you can ignore this email. Your password will not change unless you create a new one. If this request is suspicious, contact <a>{supportEmail}</a>."
+ values={{ supportEmail: ctx.supportEmail }}
+ components={{
+ a: <Link href={`mailto:${ctx.supportEmail}`} />,
+ }}
+ ns="emails"
+ />
+ </Text>
+ </EmailLayout>
+ );
+};
+
+ResetPasswordEmail.getSubject = (
+ _props: ResetPasswordEmailProps,
+ ctx: EmailContext,
+) => {
+ return ctx.t("resetPassword_subject", {
+ defaultValue: "Reset your password",
+ ns: "emails",
+ });
+};
+
+export default ResetPasswordEmail;
diff --git a/packages/ui/src/alert.tsx b/packages/ui/src/alert.tsx
index 7c9e43847..a70353a3d 100644
--- a/packages/ui/src/alert.tsx
+++ b/packages/ui/src/alert.tsx
@@ -13,7 +13,7 @@ const alertVariants = cva(
primary:
"border-primary-200 bg-primary-50 has-[[data-slot=alert-description]]:text-primary-700/90 [&>svg]:text-primary-600",
destructive:
- "border-destructive/20 bg-destructive-background text-destructive-foreground has-[[data-slot=alert-description]]:opacity-50",
+ "border-destructive/20 bg-destructive-background text-destructive has-[[data-slot=alert-description]]:opacity-90",
info: "border-blue-200 bg-blue-50 text-blue-900 has-[[data-slot=alert-description]]:text-blue-800/90 [&>svg]:text-blue-600",
warning:
"border-yellow-200 bg-yellow-50 text-yellow-900 has-[[data-slot=alert-description]]:text-yellow-800/90 [&>svg]:text-yellow-600",
diff --git a/packages/ui/src/password-input.tsx b/packages/ui/src/password-input.tsx
new file mode 100644
index 000000000..8b39b8eb1
--- /dev/null
+++ b/packages/ui/src/password-input.tsx
@@ -0,0 +1,40 @@
+import { EyeIcon, EyeOffIcon } from "lucide-react";
+import * as React from "react";
+
+import type { InputProps } from "./input";
+import { Input } from "./input";
+import { cn } from "./lib/utils";
+
+export interface PasswordInputProps extends InputProps {}
+
+const PasswordInput = React.forwardRef<HTMLInputElement, PasswordInputProps>(
+ ({ className, type, ...props }, ref) => {
+ const [showPassword, setShowPassword] = React.useState(false);
+
+ return (
+ <div className="relative">
+ <Input
+ type={showPassword ? "text" : "password"}
+ className={cn("pr-10", className)}
+ ref={ref}
+ {...props}
+ />
+ <button
+ type="button"
+ className="-translate-y-1/2 absolute top-1/2 right-4"
+ onClick={() => setShowPassword(!showPassword)}
+ disabled={props.disabled}
+ >
+ {showPassword ? (
+ <EyeOffIcon className="h-4 w-4 text-muted-foreground" />
+ ) : (
+ <EyeIcon className="h-4 w-4 text-muted-foreground" />
+ )}
+ </button>
+ </div>
+ );
+ },
+);
+PasswordInput.displayName = "PasswordInput";
+
+export { PasswordInput };
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 7f1e75a6b..080d72eed 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -289,6 +289,9 @@ importers:
autoprefixer:
specifier: ^10.4.13
version: 10.4.21([email protected])
+ better-auth:
+ specifier: ^1.3.27
calendar-link:
specifier: ^2.6.0
version: 2.8.0
@@ -424,6 +427,9 @@ importers:
zod:
specifier: ^4.1.8
version: 4.1.8
+ zxcvbn:
+ specifier: ^4.4.2
+ version: 4.4.2
devDependencies:
'@babel/core':
specifier: ^7.26.10
@@ -470,6 +476,9 @@ importers:
'@types/smoothscroll-polyfill':
specifier: ^0.3.1
version: 0.3.4
+ '@types/zxcvbn':
+ specifier: ^4.4.5
+ version: 4.4.5
'@vitejs/plugin-react':
specifier: ^5.0.0
@@ -1637,6 +1646,15 @@ packages:
resolution: {integrity: sha512-ruv7Ae4J5dUYULmeXw1gmb7rYRz57OWCPM57pHojnLq/3Z1CK2lNSLTCVjxVk1F/TZHwOZZrOWi0ur95BbLxNQ==}
engines: {node: '>=6.9.0'}
+ '@better-auth/[email protected]':
+ resolution: {integrity: sha512-3Sfdax6MQyronY+znx7bOsfQHI6m1SThvJWb0RDscFEAhfqLy95k1sl+/PgGyg0cwc2cUXoEiAOSqYdFYrg3vA==}
+
+ '@better-auth/[email protected]':
+ resolution: {integrity: sha512-W+Adw6ZA6mgvnSnhOki270rwJ42t4XzSK6YWGF//BbVXL6SwCLWfyzBc1lN2m/4RM28KubdBKQ4X5VMoLRNPQw==}
+
+ '@better-fetch/[email protected]':
+ resolution: {integrity: sha512-rEFOE1MYIsBmoMJtQbl32PGHHXuG2hDxvEd7rUHE0vCBoFQVSDqaVs9hkZEtHCxRoY+CljXKFCOuJ8uxqw1LcA==}
+
'@biomejs/[email protected]':
resolution: {integrity: sha512-HFGYkxG714KzG+8tvtXCJ1t1qXQMzgWzfvQaUjxN6UeKv+KvMEuliInnbZLJm6DXFXwqVi6446EGI0sGBLIYng==}
engines: {node: '>=14.21.3'}
@@ -2219,6 +2237,9 @@ packages:
resolution: {integrity: sha512-kjotm7XJrJ6v+7knhPaRgaT6q8F8K2jiafwYdNHLzmV0uGLuZY43FK6smNSHUPrhq5kX2slCUy+RGG/xGqmIKA==}
engines: {node: '>=10.13.0'}
+ '@hexagon/[email protected]':
+ resolution: {integrity: sha512-lhqDEAvWixy3bZ+UOYbPwUbBkwBq5C1LAJ/xPC8Oi+lL54oyakv/npbA0aU2hgCsx/1NUd4IBvV03+aUBWxerw==}
+
'@hono-rate-limiter/[email protected]':
resolution: {integrity: sha512-RSrVX5N2Oo/xXApskegu667cBVHyr8RXGWnbRDGjU2py8pN4BttEKSHA0iKi3BAwh1xSkENgDRng4tpFD9DbKg==}
peerDependencies:
@@ -2635,6 +2656,9 @@ packages:
'@leichtgewicht/[email protected]':
resolution: {integrity: sha512-Vo+PSpZG2/fmgmiNzYK9qWRh8h/CHrwD0mo1h1DzL4yzHNSfWYujGTYsWGreD000gcgmZ7K4Ys6Tx9TxtsKdDw==}
+ '@levischuck/[email protected]':
+ resolution: {integrity: sha512-llBRm4dT4Z89aRsm6u2oEZ8tfwL/2l6BwpZ7JcyieouniDECM5AqNgr/y08zalEIvW3RSK4upYyybDcmjXqAow==}
+
'@mdx-js/[email protected]':
resolution: {integrity: sha512-/QxEhPAvGwbQmy1Px8F899L5Uc2KZ6JtXwlCgJmjSTBedwOZkByYcBG4GceIGPXRDsmfxhHazuS+hlOShRLeDw==}
@@ -2790,6 +2814,14 @@ packages:
cpu: [x64]
os: [win32]
+ '@noble/[email protected]':
+ resolution: {integrity: sha512-xHK3XHPUW8DTAobU+G0XT+/w+JLM7/8k1UFdB5xg/zTFPnFCobhftzw8wl4Lw2aq/Rvir5pxfZV5fEazmeCJ2g==}
+ engines: {node: '>= 20.19.0'}
+
+ '@noble/[email protected]':
+ resolution: {integrity: sha512-XlOlEbQcE9fmuXxrVTXCTlG2nlRXa9Rj3rr5Ue/+tX+nmkgbX720YHh0VR3hBF9xDvwnb8D2shVGOwNx+ulArw==}
+ engines: {node: '>= 20.19.0'}
+
'@nodelib/[email protected]':
resolution: {integrity: sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==}
engines: {node: '>= 8'}
@@ -3020,9 +3052,42 @@ packages:
resolution: {integrity: sha512-6oclG6Y3PiDFcoyk8srjLfVKyMfVCKJ27JwNPViuXziFpmdz+MZnZN/aKY0JGXgYuO/VghU0jcOAZgWXZ1Dmrw==}
+ '@peculiar/[email protected]':
+ resolution: {integrity: sha512-t8A83hgghWQkcneRsgGs2ebAlRe54ns88p7ouv8PW2tzF1nAW4yHcL4uZKrFpIU+uszIRzTkcCuie37gpkId0A==}
+
+ '@peculiar/[email protected]':
+ resolution: {integrity: sha512-p0SjJ3TuuleIvjPM4aYfvYw8Fk1Hn/zAVyPJZTtZ2eE9/MIer6/18ROxX6N/e6edVSfvuZBqhxAj3YgsmSjQ/A==}
+
+ '@peculiar/[email protected]':
+ resolution: {integrity: sha512-ioigvA6WSYN9h/YssMmmoIwgl3RvZlAYx4A/9jD2qaqXZwGcNlAxaw54eSx2QG1Yu7YyBC5Rku3nNoHrQ16YsQ==}
+
+ '@peculiar/[email protected]':
+ resolution: {integrity: sha512-t4eYGNhXtLRxaP50h3sfO6aJebUCDGQACoeexcelL4roMFRRVgB20yBIu2LxsPh/tdW9I282gNgMOyg3ywg/mg==}
+
+ '@peculiar/[email protected]':
+ resolution: {integrity: sha512-Vj0d0wxJZA+Ztqfb7W+/iu8Uasw6hhKtCdLKXLG/P3kEPIQpqGI4P4YXlROfl7gOCqFIbgsj1HzFIFwQ5s20ug==}
+
+ '@peculiar/[email protected]':
+ resolution: {integrity: sha512-L7599HTI2SLlitlpEP8oAPaJgYssByI4eCwQq2C9eC90otFpm8MRn66PpbKviweAlhinWQ3ZjDD2KIVtx7PaVw==}
+
+ '@peculiar/[email protected]':
+ resolution: {integrity: sha512-UgqSMBLNLR5TzEZ5ZzxR45Nk6VJrammxd60WMSkofyNzd3DQLSNycGWSK5Xg3UTYbXcDFyG8pA/7/y/ztVCa6A==}
+
+ '@peculiar/[email protected]':
+ resolution: {integrity: sha512-qMZ/vweiTHy9syrkkqWFvbT3eLoedvamcUdnnvwyyUNv5FgFXA3KP8td+ATibnlZ0EANW5PYRm8E6MJzEB/72Q==}
+
'@peculiar/[email protected]':
resolution: {integrity: sha512-QPeD8UA8axQREpgR5UTAfu2mqQmm97oUqahDtNdBcfj3qAnoXzFdQW+aNf/tD2WVXF8Fhmftxoj0eMIT++gX2w==}
+ '@peculiar/[email protected]':
+ resolution: {integrity: sha512-YM/nFfskFJSlHqv59ed6dZlLZqtZQwjRVJ4bBAiWV08Oc+1rSd5lDZcBEx0lGDHfSoH3UziI2pXt2UM33KerPQ==}
+
+ '@peculiar/[email protected]':
+ resolution: {integrity: sha512-9f0hPOxiJDoG/bfNLAFven+Bd4gwz/VzrCIIWc1025LEI4BXO0U5fOCTNDPbbp2ll+UzqKsZ3g61mpBp74gk9A==}
+
+ '@peculiar/[email protected]':
+ resolution: {integrity: sha512-CpwtMCTJvfvYTFMuiME5IH+8qmDe3yEWzKHe7OOADbGfq7ohxeLaXwQo0q4du3qs0AII3UbLCvb9NF/6q0oTKQ==}
+
'@peculiar/[email protected]':
resolution: {integrity: sha512-coUfuoMeIB7B8/NMekxaDzLhaYmp0HZNPEjYRm9goRou8UZIC3z21s0sL9AWoCw4EG876QyO3kYrc61WNF9B/w==}
engines: {node: '>=8.0.0'}
@@ -3031,6 +3096,9 @@ packages:
resolution: {integrity: sha512-BRs5XUAwiyCDQMsVA9IDvDa7UBR9gAvPHgugOeGng3YN6vJ9JYonyDc0lNczErgtCWtucjR5N7VtaonboD/ezg==}
engines: {node: '>=10.12.0'}
+ '@peculiar/[email protected]':
+ resolution: {integrity: sha512-Yc4PDxN3OrxUPiXgU63c+ZRXKGE8YKF2McTciYhUHFtHVB0KMnjeFSU0qpztGhsp4P0uKix4+J2xEpIEDu8oXg==}
+
resolution: {integrity: sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==}
engines: {node: '>=14'}
@@ -4069,6 +4137,13 @@ packages:
'@shikijs/[email protected]':
resolution: {integrity: sha512-83yeghZ2xxin3Nj8z1NMd/NCuca+gsYXswywDy5bHvwlWL8tpTQmzGeUuHd9FC3E/SBEMvzJRwWEOz5gGes9Qg==}
+ '@simplewebauthn/[email protected]':
+ resolution: {integrity: sha512-FNW1oLQpTJyqG5kkDg5ZsotvWgmBaC6jCHR7Ej0qUNep36Wl9tj2eZu7J5rP+uhXgHaLk+QQ3lqcw2vS5MX1IA==}
+
+ '@simplewebauthn/[email protected]':
+ resolution: {integrity: sha512-HcWLW28yTMGXpwE9VLx9J+N2KEUaELadLrkPEEI9tpI5la70xNEVEsu/C+m3u7uoq4FulLqZQhgBCzR9IZhFpA==}
+ engines: {node: '>=20.0.0'}
+
'@sindresorhus/[email protected]':
resolution: {integrity: sha512-TV7t8GKYaJWsn00tFDqBw8+Uqmr8A0fRU1tvTQhyZzGv0sJCGRQL3JGMI3ucuKo3XIZdUP+Lx7/gh2t3lewy7g==}
engines: {node: '>=14.16'}
@@ -4797,6 +4872,9 @@ packages:
resolution: {integrity: sha512-oJoftv0LSuaDZE3Le4DbKX+KS9G36NzOeSap90UIK0yMA/NhKJhqlSGtNDORNRaIbQfzjXDrQa0ytJ6mNRGz/Q==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-FZJgC5Bxuqg7Rhsm/bx6gAruHHhDQ55r+s0JhDh8CQ16fD7NsJJ+p8YMMQDhSQoIrSmjpqqYWA96oQVMNkjRyA==}
+
resolution: {integrity: sha512-ons5CwXZ/51wrUPfoduC+cO7AS1/wRb0ybpQJ9RrssossDxVy4t49QxWoWgfBDvVKsz9VXzBk9z0wqTdZ+Cq8g==}
@@ -5257,6 +5335,38 @@ packages:
resolution: {integrity: sha512-4Bcg1P8xhUuqcii/S0Z9wiHIrQVPMermM1any+MX5GeGD7faD3/msQUDGLol9wOcz4/jbg/WJnGqoJF6LiBdtg==}
engines: {node: '>=10.0.0'}
+ resolution: {integrity: sha512-SwiGAJ7yU6dBhNg0NdV1h5M8T5sa7/AszZVc4vBfMDrLLmvUfbt9JoJ0uRUJUEdKRAAxTyl9yA+F3+GhtAD80w==}
+ peerDependencies:
+ '@lynx-js/react': '*'
+ '@sveltejs/kit': '*'
+ next: '*'
+ react: '*'
+ react-dom: '*'
+ solid-js: '*'
+ svelte: '*'
+ vue: '*'
+ peerDependenciesMeta:
+ '@lynx-js/react':
+ optional: true
+ '@sveltejs/kit':
+ optional: true
+ next:
+ optional: true
+ react:
+ optional: true
+ react-dom:
+ optional: true
+ solid-js:
+ optional: true
+ svelte:
+ optional: true
+ vue:
+ optional: true
+
+ resolution: {integrity: sha512-sI3GcA1SCVa3H+CDHl8W8qzhlrckwXOTKhqq3OOPXjgn5aTOMIqGY34zLY/pHA6tRRMjTUC3lz5Mi7EbDA24Kw==}
+
resolution: {integrity: sha512-aVNobHnJqLiUelTaHat9DZ1qM2w0C0Eym4LPI/3JxOnSokGVdsl1T1kN7TFvsEAD8G47A6VKQ0TVHqbBnYMJlQ==}
engines: {node: '>=12.0.0'}
@@ -5793,6 +5903,9 @@ packages:
resolution: {integrity: sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==}
engines: {node: '>= 0.4'}
+ resolution: {integrity: sha512-mEQCMmwJu317oSz8CwdIOdwf3xMif1ttiM8LTufzc3g6kR+9Pe236twL8j3IYT1F7GfRgGcW6MWxzZjLIkuHIg==}
+
resolution: {integrity: sha512-TllpMR/t0M5sqCXfj85i4XaAzxmS5tVA16dqvdkMwGmzI+dXLXnw3J+3Vdv7VKw+ThlTMboK6i9rnZ6Nntj5CQ==}
engines: {node: '>= 14'}
@@ -6966,6 +7079,9 @@ packages:
resolution: {integrity: sha512-skIAxZqcMkOrSwjJvplIPYrlXGpxTPnro2/QWTDCxAdWQrSTV5/KqspMWmi5WAx5+ULswASJiZ0a+1B/Lxt9cw==}
+ resolution: {integrity: sha512-TTQJyoEoKcC1lscpVDCSsVgYzUDg/0Bt3WE//WiTPK6uOCQC2KZS4MpugbMWt/zyjkopgZoXhZuCi00gLudfUA==}
+
resolution: {integrity: sha512-HvdH2LzI/EAZcUwA8+0nKNtWHqS+ZmijLA30RwZA0bo7ToCckjK5MkGhjED9KoRcXO6BaGI3I9UIzSA1FKFPOQ==}
@@ -7062,6 +7178,10 @@ packages:
resolution: {integrity: sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==}
engines: {node: '>=0.10.0'}
+ resolution: {integrity: sha512-QUOgl5ZrS9IRuhq5FvOKFSsD/3+IA6MLE81/bOOTRA/YQpKDza2sFdN5g6JCB9BOpqMJDGefLCQ9F12hRS13TA==}
+ engines: {node: '>=20.0.0'}
+
resolution: {integrity: sha512-TB+ZjoillV6B26Vspf9l2L/vKaRY/4ep3hahcyVkCGFgsTNRUQdc24bQeNFiZeoxH0vr5+7SfNRMQuPHv/1IrQ==}
@@ -7543,6 +7663,10 @@ packages:
engines: {node: ^18 || >=20}
hasBin: true
+ resolution: {integrity: sha512-kNZ9xnoJYKg/AfxjrVL4SS0fKX++4awQReGqWnwTRHxeHGZ1FJFVgTqr/eMrNQdp0Tz7M7tG/TDaX8QfHDwVCw==}
+ engines: {node: ^20.0.0 || >=22.0.0}
+
resolution: {integrity: sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==}
engines: {node: '>= 0.6'}
@@ -8302,6 +8426,9 @@ packages:
resolution: {integrity: sha512-6tDA8g98We0zd0GvVeMT9arEOnTw9qM03L9cJXaCjrip1OO764RDBLBfrB4cwzNGDj5OA5ioymC9GkizgWJDUg==}
engines: {node: '>=8'}
+ resolution: {integrity: sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==}
+
resolution: {integrity: sha512-00o4I+DVrefhv+nX0ulyi3biSHCPDe+yLv5o/p6d/UVlirijB8E16FtfwSAi4g3tcqrQ4lRAqQSoFEZJehYEcw==}
engines: {node: '>= 0.4'}
@@ -8469,6 +8596,9 @@ packages:
engines: {node: '>=18.0.0', npm: '>=8.0.0'}
hasBin: true
+ resolution: {integrity: sha512-OXMmJ3zRk2xeXFGfA3K+EOPHC5u7RDFG7lIOx0X1pdnhUkI8MdVrbV+sNsD80ElpUZ+MRHdyxPnFthq9VHs8uQ==}
+
resolution: {integrity: sha512-guoltQEx+9aMf2gDZ0s62EcV8lsXR+0w8915TC3ITdn2YueuNjdAYh/levpU9nFaoChh9RUS5ZdQMrKfVEN9tw==}
@@ -8566,6 +8696,9 @@ packages:
resolution: {integrity: sha512-VqpjJZKadQB/PEbEwvFdO43Ax5dFBZ2UECszz8bQ7pi7wt//PWe1P6MN7eCnjsatYtBT6EuiClbjSWP2WrIoTw==}
engines: {node: '>= 0.8.0'}
+ resolution: {integrity: sha512-IOc8uWeOZgnb3ptbCURJWNjWUPcO3ZnTTdzsurqERrP6nPyv+paC55vJM0LpOlT2ne+Ix+9+CRG1MNLlyZ4GjQ==}
+
resolution: {integrity: sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==}
engines: {node: '>= 0.4'}
@@ -9061,6 +9194,10 @@ packages:
engines: {node: '>=18.0.0'}
hasBin: true
+ resolution: {integrity: sha512-axr3IdNuVIxnaK5XGEUFTu3YmAQ6lllgrvqfEoR16g/HGnYY/6We4oWENtAnzK6/LpJ2ur9PAb80RBt7/U4ugw==}
+ engines: {node: '>= 6.0.0'}
+
resolution: {integrity: sha512-ah6YnH2dErojhFooxEzmvsoZQTMImaruZhFPfMKPBq8sb+hALRdvBNLqfc8NWlZq576FkfRZ/MSi4SHvVFT9PQ==}
cpu: [x64]
@@ -9148,6 +9285,9 @@ packages:
peerDependencies:
react: '>=15.0.0'
+ resolution: {integrity: sha512-Ql87qFHB3s/De2ClA9e0gsnS6zXG27SkTiSJwjCc9MebbfapQfuPzumMIUMi38ezPZVNFcHI9sUIepeQfw8J8Q==}
+
resolution: {integrity: sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw==}
@@ -9624,6 +9764,9 @@ packages:
resolution: {integrity: sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==}
+ resolution: {integrity: sha512-Bq0B+ixT/DMyG8kgX2xWcI5jUvCwqrMxSFam7m0lAf78nf04hv6lNCsyLYdyYTrCVMqNDY/206K7eExYCeSyUQ==}
+
snapshots:
'@adobe/[email protected]': {}
@@ -11030,6 +11173,15 @@ snapshots:
'@babel/helper-string-parser': 7.27.1
'@babel/helper-validator-identifier': 7.27.1
+ '@better-auth/[email protected]':
+ dependencies:
+ better-call: 1.0.19
+ zod: 4.1.8
+
+ '@better-auth/[email protected]': {}
+
+ '@better-fetch/[email protected]': {}
+
'@biomejs/[email protected]':
optionalDependencies:
'@biomejs/cli-darwin-arm64': 2.1.1
@@ -11381,6 +11533,8 @@ snapshots:
dependencies:
is-negated-glob: 1.0.0
+ '@hexagon/[email protected]': {}
+
dependencies:
hono-rate-limiter: 0.2.3([email protected])
@@ -11727,6 +11881,8 @@ snapshots:
'@leichtgewicht/[email protected]': {}
+ '@levischuck/[email protected]': {}
+
dependencies:
'@types/estree': 1.0.7
@@ -12071,6 +12227,10 @@ snapshots:
optional: true
+ '@noble/[email protected]': {}
+
+ '@noble/[email protected]': {}
+
'@nodelib/[email protected]':
dependencies:
'@nodelib/fs.stat': 2.0.5
@@ -12359,12 +12519,94 @@ snapshots:
'@panva/[email protected]': {}
+ '@peculiar/[email protected]':
+ dependencies:
+ '@peculiar/asn1-schema': 2.5.0
+ asn1js: 3.0.6
+ tslib: 2.8.1
+
+ '@peculiar/[email protected]':
+ dependencies:
+ '@peculiar/asn1-schema': 2.5.0
+ '@peculiar/asn1-x509': 2.5.0
+ '@peculiar/asn1-x509-attr': 2.5.0
+ asn1js: 3.0.6
+ tslib: 2.8.1
+
+ '@peculiar/[email protected]':
+ dependencies:
+ '@peculiar/asn1-schema': 2.5.0
+ '@peculiar/asn1-x509': 2.5.0
+ asn1js: 3.0.6
+ tslib: 2.8.1
+
+ '@peculiar/[email protected]':
+ dependencies:
+ '@peculiar/asn1-schema': 2.5.0
+ '@peculiar/asn1-x509': 2.5.0
+ asn1js: 3.0.6
+ tslib: 2.8.1
+
+ '@peculiar/[email protected]':
+ dependencies:
+ '@peculiar/asn1-cms': 2.5.0
+ '@peculiar/asn1-pkcs8': 2.5.0
+ '@peculiar/asn1-rsa': 2.5.0
+ '@peculiar/asn1-schema': 2.5.0
+ asn1js: 3.0.6
+ tslib: 2.8.1
+
+ '@peculiar/[email protected]':
+ dependencies:
+ '@peculiar/asn1-schema': 2.5.0
+ '@peculiar/asn1-x509': 2.5.0
+ asn1js: 3.0.6
+ tslib: 2.8.1
+
+ '@peculiar/[email protected]':
+ dependencies:
+ '@peculiar/asn1-cms': 2.5.0
+ '@peculiar/asn1-pfx': 2.5.0
+ '@peculiar/asn1-pkcs8': 2.5.0
+ '@peculiar/asn1-schema': 2.5.0
+ '@peculiar/asn1-x509': 2.5.0
+ '@peculiar/asn1-x509-attr': 2.5.0
+ asn1js: 3.0.6
+ tslib: 2.8.1
+
+ '@peculiar/[email protected]':
+ dependencies:
+ '@peculiar/asn1-schema': 2.5.0
+ '@peculiar/asn1-x509': 2.5.0
+ asn1js: 3.0.6
+ tslib: 2.8.1
+
'@peculiar/[email protected]':
dependencies:
asn1js: 3.0.6
pvtsutils: 1.3.6
tslib: 2.8.1
+ '@peculiar/[email protected]':
+ dependencies:
+ asn1js: 3.0.6
+ pvtsutils: 1.3.6
+ tslib: 2.8.1
+
+ '@peculiar/[email protected]':
+ dependencies:
+ '@peculiar/asn1-schema': 2.5.0
+ '@peculiar/asn1-x509': 2.5.0
+ asn1js: 3.0.6
+ tslib: 2.8.1
+
+ '@peculiar/[email protected]':
+ dependencies:
+ '@peculiar/asn1-schema': 2.5.0
+ asn1js: 3.0.6
+ pvtsutils: 1.3.6
+ tslib: 2.8.1
+
'@peculiar/[email protected]':
dependencies:
tslib: 2.8.1
@@ -12377,6 +12619,20 @@ snapshots:
tslib: 2.8.1
webcrypto-core: 1.8.1
+ '@peculiar/[email protected]':
+ dependencies:
+ '@peculiar/asn1-cms': 2.5.0
+ '@peculiar/asn1-csr': 2.5.0
+ '@peculiar/asn1-ecc': 2.5.0
+ '@peculiar/asn1-pkcs9': 2.5.0
+ '@peculiar/asn1-rsa': 2.5.0
+ '@peculiar/asn1-schema': 2.5.0
+ '@peculiar/asn1-x509': 2.5.0
+ pvtsutils: 1.3.6
+ reflect-metadata: 0.2.2
+ tslib: 2.8.1
+ tsyringe: 4.10.0
+
optional: true
@@ -13437,6 +13693,19 @@ snapshots:
'@shikijs/[email protected]': {}
+ '@simplewebauthn/[email protected]': {}
+
+ '@simplewebauthn/[email protected]':
+ dependencies:
+ '@hexagon/base64': 1.1.28
+ '@levischuck/tiny-cbor': 0.2.11
+ '@peculiar/asn1-android': 2.5.0
+ '@peculiar/asn1-ecc': 2.5.0
+ '@peculiar/asn1-rsa': 2.5.0
+ '@peculiar/asn1-schema': 2.5.0
+ '@peculiar/asn1-x509': 2.5.0
+ '@peculiar/x509': 1.14.0
+
'@sindresorhus/[email protected]': {}
'@sindresorhus/[email protected]':
@@ -14372,6 +14641,8 @@ snapshots:
'@types/node': 20.17.50
optional: true
+ '@types/[email protected]': {}
+
'@ucast/[email protected]': {}
@@ -14837,6 +15108,34 @@ snapshots:
+ dependencies:
+ '@better-auth/core': 1.3.27
+ '@better-auth/utils': 0.3.0
+ '@better-fetch/fetch': 1.1.18
+ '@noble/ciphers': 2.0.1
+ '@noble/hashes': 2.0.1
+ '@simplewebauthn/browser': 13.2.2
+ '@simplewebauthn/server': 13.2.2
+ better-call: 1.0.19
+ defu: 6.1.4
+ jose: 6.1.0
+ kysely: 0.28.8
+ nanostores: 1.0.1
+ zod: 4.1.8
+ optionalDependencies:
+ react: 19.1.0
+ react-dom: 19.1.0([email protected])
+
+ dependencies:
+ '@better-auth/utils': 0.3.0
+ '@better-fetch/fetch': 1.1.18
+ rou3: 0.5.1
+ set-cookie-parser: 2.7.1
+ uncrypto: 0.1.3
+
dependencies:
open: 8.4.2
@@ -15358,6 +15657,8 @@ snapshots:
has-property-descriptors: 1.0.2
object-keys: 1.1.1
+
dependencies:
ast-types: 0.13.4
@@ -16881,6 +17182,8 @@ snapshots:
+
@@ -16982,6 +17285,8 @@ snapshots:
+
dependencies:
gcd: 0.0.1
@@ -17698,6 +18003,8 @@ snapshots:
+
@@ -18521,6 +18828,8 @@ snapshots:
indent-string: 4.0.0
strip-indent: 3.0.0
+
dependencies:
call-bind: 1.0.8
@@ -18822,6 +19131,8 @@ snapshots:
'@rollup/rollup-win32-x64-msvc': 4.40.0
fsevents: 2.3.3
+
@@ -18934,6 +19245,8 @@ snapshots:
transitivePeerDependencies:
- supports-color
+
dependencies:
define-data-property: 1.1.4
@@ -19537,6 +19850,10 @@ snapshots:
optionalDependencies:
fsevents: 2.3.3
+ dependencies:
+ tslib: 1.14.1
+
optional: true
@@ -19632,6 +19949,8 @@ snapshots:
react: 19.1.0
react-lifecycles-compat: 3.0.4
+
@@ -20170,3 +20489,5 @@ snapshots:
+