refactor: small tweaks to password reset flow

This commit is contained in:
Henry
2026-05-11 13:43:35 +01:00
parent 54dcd08d9a
commit 3d9e859b31
4 changed files with 50 additions and 20 deletions

View File

@@ -1,6 +1,7 @@
import { useTheme } from "next-themes";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { t } from "@lingui/core/macro";
import { env } from "next-runtime-env"; import { env } from "next-runtime-env";
import { useTheme } from "next-themes";
import { useEffect, useRef, useState } from "react"; import { useEffect, useRef, useState } from "react";
import { import {
TbLayoutSidebarLeftCollapse, TbLayoutSidebarLeftCollapse,
@@ -8,7 +9,6 @@ import {
TbLayoutSidebarRightCollapse, TbLayoutSidebarRightCollapse,
TbLayoutSidebarRightExpand, TbLayoutSidebarRightExpand,
} from "react-icons/tb"; } from "react-icons/tb";
import { t } from "@lingui/core/macro";
import { authClient } from "@kan/auth/client"; import { authClient } from "@kan/auth/client";
@@ -16,10 +16,10 @@ import { useClickOutside } from "~/hooks/useClickOutside";
import { useModal } from "~/providers/modal"; import { useModal } from "~/providers/modal";
import { useWorkspace, WorkspaceProvider } from "~/providers/workspace"; import { useWorkspace, WorkspaceProvider } from "~/providers/workspace";
import { api } from "~/utils/api"; import { api } from "~/utils/api";
import { ChangePasswordFormConfirmation } from "~/views/settings/components/ChangePasswordConfirmation";
import Button from "./Button"; import Button from "./Button";
import Modal from "./modal"; import Modal from "./modal";
import SideNavigation from "./SideNavigation"; import SideNavigation from "./SideNavigation";
import { ChangePasswordFormConfirmation } from "~/views/settings/components/ChangePasswordConfirmation";
interface DashboardProps { interface DashboardProps {
children: React.ReactNode; children: React.ReactNode;
@@ -106,7 +106,9 @@ export default function Dashboard({
useEffect(() => { useEffect(() => {
if (hasLoaded && availableWorkspaces.length === 0) { if (hasLoaded && availableWorkspaces.length === 0) {
if (env("NEXT_PUBLIC_KAN_ENV") === "cloud") { if (env("NEXT_PUBLIC_KAN_ENV") === "cloud") {
router.push(`/onboarding/select-plan?returnUrl=${encodeURIComponent(window.location.pathname)}`); router.push(
`/onboarding/select-plan?returnUrl=${encodeURIComponent(window.location.pathname)}`,
);
} else { } else {
openModal("NEW_WORKSPACE", undefined, undefined, false); openModal("NEW_WORKSPACE", undefined, undefined, false);
} }
@@ -123,7 +125,6 @@ export default function Dashboard({
isCredentialsEnabled && isCredentialsEnabled &&
user.hasMagicLinkAccount && user.hasMagicLinkAccount &&
!user.hasPassword && !user.hasPassword &&
typeof window !== "undefined" &&
!sessionStorage.getItem("set_password_prompted") !sessionStorage.getItem("set_password_prompted")
) { ) {
sessionStorage.setItem("set_password_prompted", "1"); sessionStorage.setItem("set_password_prompted", "1");
@@ -226,14 +227,22 @@ export default function Dashboard({
</div> </div>
</div> </div>
<Modal modalSize="sm" isVisible={modalContentType === "SET_PASSWORD_PROMPT"}> <Modal
modalSize="sm"
isVisible={modalContentType === "SET_PASSWORD_PROMPT"}
>
{user?.hasPassword ? ( {user?.hasPassword ? (
<div className="p-5"> <div className="p-5">
<h2 className="text-md pb-4 font-medium dark:text-white">{t`Password already set`}</h2> <h2 className="pb-4 text-base font-medium dark:text-white">{t`Password already set`}</h2>
<p className="mb-6 text-sm text-light-900"> <p className="mb-6 text-sm text-light-900">
{t`Your account already has a password. You can change it from your account settings.`} {t`Your account already has a password. You can change it from your account settings.`}
</p> </p>
<Button variant="secondary" onClick={closeModal} fullWidth size="lg"> <Button
variant="secondary"
onClick={closeModal}
fullWidth
size="lg"
>
{t`Close`} {t`Close`}
</Button> </Button>
</div> </div>

View File

@@ -39,11 +39,11 @@ const buildSchema = (hasPassword: boolean) => {
); );
}; };
type FormValues = { interface FormValues {
currentPassword?: string; currentPassword?: string;
newPassword: string; newPassword: string;
confirmPassword: string; confirmPassword: string;
}; }
interface Props { interface Props {
hasPassword: boolean; hasPassword: boolean;
@@ -97,13 +97,11 @@ export function ChangePasswordFormConfirmation({ hasPassword }: Props) {
icon: "success", icon: "success",
}); });
// Clear the session prompt flag so future magic link logins if (!hasPassword) {
// don't re-show the set-password modal (password is now set)
if (!hasPassword && typeof window !== "undefined") {
sessionStorage.removeItem("set_password_prompted"); sessionStorage.removeItem("set_password_prompted");
} }
utils.invalidate(); utils.user.getUser.invalidate();
reset(); reset();
router.push("/"); router.push("/");
}, },
@@ -118,7 +116,9 @@ export function ChangePasswordFormConfirmation({ hasPassword }: Props) {
} else { } else {
closeModal(); closeModal();
showPopup({ showPopup({
header: hasPassword ? t`Error Changing Password` : t`Error Setting Password`, header: hasPassword
? t`Error Changing Password`
: t`Error Setting Password`,
message: t`An unexpected error occurred. Please try again later.`, message: t`An unexpected error occurred. Please try again later.`,
icon: "error", icon: "error",
}); });
@@ -138,7 +138,7 @@ export function ChangePasswordFormConfirmation({ hasPassword }: Props) {
return ( return (
<div className="p-5"> <div className="p-5">
<div className="flex w-full flex-col justify-between pb-4"> <div className="flex w-full flex-col justify-between pb-4">
<h2 className="text-md pb-4 font-medium dark:text-white"> <h2 className="pb-4 text-base font-medium dark:text-white">
{hasPassword ? t`Change Password` : t`Set Password`} {hasPassword ? t`Change Password` : t`Set Password`}
</h2> </h2>
<p className="mb-4 text-sm text-light-900"> <p className="mb-4 text-sm text-light-900">

View File

@@ -2,9 +2,9 @@ import { TRPCError } from "@trpc/server";
import { z } from "zod"; import { z } from "zod";
import * as userRepo from "@kan/db/repository/user.repo"; import * as userRepo from "@kan/db/repository/user.repo";
import { generateAvatarUrl } from "@kan/shared/utils";
import { createTRPCRouter, protectedProcedure } from "../trpc"; import { createTRPCRouter, protectedProcedure } from "../trpc";
import { generateAvatarUrl } from "@kan/shared/utils";
export const userRouter = createTRPCRouter({ export const userRouter = createTRPCRouter({
getUser: protectedProcedure getUser: protectedProcedure
@@ -119,6 +119,17 @@ export const userRouter = createTRPCRouter({
}; };
}), }),
setPassword: protectedProcedure setPassword: protectedProcedure
.meta({
openapi: {
method: "POST",
path: "/users/me/password",
summary: "Set password",
description:
"Sets a password for a user who signed up via magic link and has no password yet",
tags: ["Users"],
protect: true,
},
})
.input( .input(
z.object({ z.object({
newPassword: z newPassword: z
@@ -152,7 +163,14 @@ export const userRouter = createTRPCRouter({
}); });
} }
await ctx.auth.api.setPassword({ newPassword: input.newPassword }); try {
await ctx.auth.api.setPassword({ newPassword: input.newPassword });
} catch {
throw new TRPCError({
message: "Failed to set password",
code: "INTERNAL_SERVER_ERROR",
});
}
return { success: true }; return { success: true };
}), }),

View File

@@ -4,6 +4,9 @@ import { v4 as uuidv4 } from "uuid";
import type { dbClient } from "@kan/db/client"; import type { dbClient } from "@kan/db/client";
import { account, apikey, users } from "@kan/db/schema"; import { account, apikey, users } from "@kan/db/schema";
const PROVIDER_CREDENTIAL = "credential";
const PROVIDER_MAGIC_LINK = "magic-link";
export const getCount = async (db: dbClient) => { export const getCount = async (db: dbClient) => {
const result = await db.select({ count: count() }).from(users); const result = await db.select({ count: count() }).from(users);
@@ -39,7 +42,7 @@ export const getById = async (db: dbClient, userId: string) => {
.where( .where(
and( and(
eq(account.userId, userId), eq(account.userId, userId),
eq(account.providerId, "credential"), eq(account.providerId, PROVIDER_CREDENTIAL),
isNotNull(account.password), isNotNull(account.password),
), ),
) )
@@ -50,7 +53,7 @@ export const getById = async (db: dbClient, userId: string) => {
.where( .where(
and( and(
eq(account.userId, userId), eq(account.userId, userId),
eq(account.providerId, "magic-link"), eq(account.providerId, PROVIDER_MAGIC_LINK),
), ),
) )
.limit(1), .limit(1),