diff --git a/.cursorrules b/.cursorrules new file mode 100644 index 000000000..59d57b688 --- /dev/null +++ b/.cursorrules @@ -0,0 +1,76 @@ +You are a Senior Frontend Developer and an Expert in React, Next.js, tRPC, TypeScript, TailwindCSS, HTML and CSS. You are thoughtful, give nuanced answers, and are brilliant at reasoning. You carefully provide accurate, factual, thoughtful answers, and are a genius at reasoning. + +Follow the user’s requirements carefully & to the letter. + +- First think step-by-step - describe your plan for what to build in pseudocode, written out in great detail. +- Confirm, then write code! +- Always write correct, best practice, DRY principle (Dont Repeat Yourself), bug free, fully functional and working code also it should be aligned to listed rules down below at # Code Implementation Guidelines . +- Focus on easy and readability code, over being performant. +- Fully implement all requested functionality. +- Leave NO todo’s, placeholders or missing pieces. +- Ensure code is complete! Verify thoroughly finalised. +- Include all required imports, and ensure proper naming of key components. +- Be concise Minimize any other prose. +- If you think there might not be a correct answer, you say so. +- If you do not know the answer, say so, instead of guessing + +**Coding Environment** + +The user asks questions about the following coding languages and frameworks: + +- React +- Next.js +- Drizzle +- tRPC +- Vitest +- TypeScript +- TailwindCSS +- HTML +- CSS + +**Code Implementation Guidelines** + +Follow these rules when you write code: + +- Use early returns whenever possible to make the code more readable. +- Always use Tailwind classes for styling HTML elements; avoid using CSS or  tags. +- Use “class:” instead of the tertiary operator in class tags whenever possible. +- Use descriptive variable and function/const names. Also, event functions should be named with a “handle” prefix, like “handleClick” for onClick and “handleKeyDown” for onKeyDown. +- Implement accessibility features on elements. For example, a  tag should have a tabindex=“0”, aria-label, on:click, and on:keydown, and similar attributes. +- Usefunctions instead of consts, for example, “function toggle() {}”. Also, define a type if possible. + +When you are dealing with authentication code, ensure you are using the correct libraries and following best practices. + +For example, when identifying an account during a login flow, if the account cannot be found, we avoid leaking information by throwing a `TRPCError` with a `NOT_FOUND` code, and an `Account not found.` message. + +**Test Implementation Guidelines** + +Follow these rules when you write tests: + +- Use Vitest, do not use Jest. +- When you are testing for errors, use `waitError` to wait for the error to be thrown. For example: + +``` +import waitError from "@peated/server/lib/test/waitError"; + +const err = await waitError( + caller.authPasswordResetConfirm({ + token, + password: "testpassword", + }), +); +``` + +- In addition to using `waitError`, utilize snapshots for the resulting error. For example, `expect(err).toMatchInlineSnapshot();` +- Prefer dependency injection over mocking when the called functions make it possible. +- When calling tRPC endpoints that are not expected to error, await on the caller. Do not test the Promise directly. For example: + +``` +const caller = createCaller(); + +const data = await caller.authRegister({ + username: "foo", + email: "foo@example.com", + password: "example", +}); +``` diff --git a/.vscode/settings.json b/.vscode/settings.json index 323b75bea..ae59c91e7 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -9,5 +9,6 @@ "**/app/**/layout.tsx": "${dirname} - Layout", "**/component/**/index.tsx": "${dirname} - Component" }, - "scm.showHistoryGraph": false + "scm.showHistoryGraph": false, + "makefile.configureOnOpen": false } diff --git a/apps/server/src/lib/auth.ts b/apps/server/src/lib/auth.ts index 3d0cb63a5..d04aa2029 100644 --- a/apps/server/src/lib/auth.ts +++ b/apps/server/src/lib/auth.ts @@ -10,6 +10,7 @@ import { random } from "../lib/rand"; import { serialize } from "../serializers"; import { UserSerializer } from "../serializers/user"; import { logError } from "./log"; +import { absoluteUrl } from "./urls"; // I love to ESM. import type { JwtPayload } from "jsonwebtoken"; @@ -120,3 +121,22 @@ export async function createUser( if (!user) throw new Error("Unable to create user"); return user; } + +export async function generateMagicLink(user: User, redirectTo = "/") { + const token = { + id: user.id, + email: user.email, + createdAt: new Date().toISOString(), + }; + + const signedToken = await signPayload(token); + const url = absoluteUrl( + config.URL_PREFIX, + `/auth/magic-link?token=${signedToken}&redirectTo=${encodeURIComponent(redirectTo)}`, + ); + + return { + token: signedToken, + url, + }; +} diff --git a/apps/server/src/lib/email.ts b/apps/server/src/lib/email.ts index 771898218..10048b227 100644 --- a/apps/server/src/lib/email.ts +++ b/apps/server/src/lib/email.ts @@ -1,4 +1,5 @@ import cuid2 from "@paralleldrive/cuid2"; +import { Template as MagicLinkEmailTemplate } from "@peated/email/templates/magicLinkEmail"; import { Template as NewCommentTemplate } from "@peated/email/templates/newCommentEmail"; import { Template as PasswordResetEmailTemplate } from "@peated/email/templates/passwordResetEmail"; import { Template as VerifyEmailTemplate } from "@peated/email/templates/verifyEmail"; @@ -20,7 +21,7 @@ import { type User, } from "../db/schema"; import type { EmailVerifySchema, PasswordResetSchema } from "../schemas"; -import { signPayload } from "./auth"; +import { generateMagicLink, signPayload } from "./auth"; import { logError } from "./log"; let mailTransport: Transporter; @@ -127,12 +128,11 @@ export async function notifyComment({ for (const email of emailList) { try { await transport.sendMail({ - from: `"${config.SMTP_FROM_NAME}" <${config.SMTP_FROM}>`, + ...getMailDefaults(), to: email, subject: "New Comment on Tasting", text: `View this comment on Peated: ${commentUrl}\n\n${comment.comment}`, html, - replyTo: `"${config.SMTP_FROM_NAME}" <${config.SMTP_REPLY_TO || config.SMTP_FROM}>`, }); } catch (err) { logError(err); @@ -147,6 +147,7 @@ export async function sendVerificationEmail({ user: User; transport?: Transporter; }) { + // TODO: error out if (!hasEmailSupport()) return; if (!transport) { @@ -167,13 +168,12 @@ export async function sendVerificationEmail({ try { await transport.sendMail({ - from: `"${config.SMTP_FROM_NAME}" <${config.SMTP_FROM}>`, + ...getMailDefaults(), to: user.email, subject: "Account Verification", // TODO: text: `Your account requires verification: ${verifyUrl}`, html, - replyTo: `"${config.SMTP_FROM_NAME}" <${config.SMTP_REPLY_TO || config.SMTP_FROM}>`, }); } catch (err) { logError(err); @@ -187,6 +187,7 @@ export async function sendPasswordResetEmail({ user: User; transport?: Transporter; }) { + // TODO: error out if (!hasEmailSupport()) return; if (!transport) { @@ -210,20 +211,55 @@ export async function sendPasswordResetEmail({ PasswordResetEmailTemplate({ baseUrl: config.URL_PREFIX, resetUrl }), ); - try { - await transport.sendMail({ - from: `"${config.SMTP_FROM_NAME}" <${config.SMTP_FROM}>`, - to: user.email, - subject: "Reset Password", - // TODO: - text: `A password reset was requested for your account.\n\nIf you don't recognize this request, you can ignore this.\n\nTo continue: ${resetUrl}`, - html, - replyTo: `"${config.SMTP_FROM_NAME}" <${config.SMTP_REPLY_TO || config.SMTP_FROM}>`, - headers: { - References: `${cuid2.createId()}@peated.com`, - }, - }); - } catch (err) { - logError(err); + await transport.sendMail({ + ...getMailDefaults(), + to: user.email, + subject: "Reset Password", + // TODO: + text: `A password reset was requested for your account.\n\nIf you don't recognize this request, you can ignore this.\n\nTo continue: ${resetUrl}`, + html, + headers: { + References: `${cuid2.createId()}@peated.com`, + }, + }); +} + +export async function sendMagicLinkEmail({ + user, + transport = mailTransport, +}: { + user: User; + transport?: Transporter; +}) { + // TODO: error out + if (!hasEmailSupport()) return; + + if (!transport) { + if (!mailTransport) mailTransport = createMailTransport(); + transport = mailTransport; } + + const magicLink = await generateMagicLink(user); + + const html = await render( + MagicLinkEmailTemplate({ + baseUrl: config.URL_PREFIX, + magicLinkUrl: magicLink.url, + }), + ); + + await transport.sendMail({ + ...getMailDefaults(), + to: user.email, + subject: "Magic Link for Peated", + text: `Click the following link to log in to Peated: ${magicLink.url}`, + html: html, + }); +} + +function getMailDefaults() { + return { + from: `"${config.SMTP_FROM_NAME}" <${config.SMTP_FROM}>`, + replyTo: `"${config.SMTP_FROM_NAME}" <${config.SMTP_REPLY_TO || config.SMTP_FROM}>`, + }; } diff --git a/apps/server/src/schemas/index.ts b/apps/server/src/schemas/index.ts index 98c5c40c4..e575bcc15 100644 --- a/apps/server/src/schemas/index.ts +++ b/apps/server/src/schemas/index.ts @@ -12,6 +12,7 @@ export * from "./externalSites"; export * from "./flights"; export * from "./follows"; export * from "./friends"; +export * from "./magicLink"; export * from "./notifications"; export * from "./regions"; export * from "./reviews"; diff --git a/apps/server/src/schemas/magicLink.ts b/apps/server/src/schemas/magicLink.ts new file mode 100644 index 000000000..816ee7a1d --- /dev/null +++ b/apps/server/src/schemas/magicLink.ts @@ -0,0 +1,10 @@ +import { z } from "zod"; +import { zDatetime } from "./common"; + +export const MagicLinkSchema = z.object({ + id: z.number(), + email: z.string().email(), + createdAt: zDatetime, +}); + +export type MagicLink = z.infer; diff --git a/apps/server/src/trpc/router.ts b/apps/server/src/trpc/router.ts index ca75d386d..9615657b9 100644 --- a/apps/server/src/trpc/router.ts +++ b/apps/server/src/trpc/router.ts @@ -4,6 +4,8 @@ import type { Context } from "./context"; import auth from "./routes/auth"; import authBasic from "./routes/authBasic"; import authGoogle from "./routes/authGoogle"; +import authMagicLinkConfirm from "./routes/authMagicLinkConfirm"; +import authMagicLinkSend from "./routes/authMagicLinkSend"; import authPasswordReset from "./routes/authPasswordReset"; import authPasswordResetConfirm from "./routes/authPasswordResetConfirm"; import authRegister from "./routes/authRegister"; @@ -118,6 +120,8 @@ export const appRouter = router({ auth, authBasic, authGoogle, + authMagicLinkConfirm, + authMagicLinkSend, authRegister, authPasswordReset, authPasswordResetConfirm, diff --git a/apps/server/src/trpc/routes/authMagicLinkConfirm.test.ts b/apps/server/src/trpc/routes/authMagicLinkConfirm.test.ts new file mode 100644 index 000000000..532e052b9 --- /dev/null +++ b/apps/server/src/trpc/routes/authMagicLinkConfirm.test.ts @@ -0,0 +1,108 @@ +import { createAccessToken, verifyPayload } from "@peated/server/lib/auth"; +import waitError from "@peated/server/lib/test/waitError"; +import { beforeEach, describe, expect, test, vi } from "vitest"; +import { createCaller } from "../router"; + +// Mock the auth functions +vi.mock("@peated/server/lib/auth", () => ({ + createAccessToken: vi.fn(), + verifyPayload: vi.fn(), +})); + +describe("authMagicLinkConfirm", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + test("confirms magic link for active user", async ({ fixtures }) => { + const user = await fixtures.User({ active: true, verified: false }); + const caller = createCaller({ user: null }); + const token = "valid-token"; + + vi.mocked(verifyPayload).mockResolvedValue({ + id: user.id, + email: user.email, + createdAt: new Date().toISOString(), + }); + + vi.mocked(createAccessToken).mockResolvedValue("mocked-access-token"); + + const result = await caller.authMagicLinkConfirm({ token }); + + expect(result.user.id).toBe(user.id); + expect(result.user.verified).toBe(true); + expect(result.accessToken).toBe("mocked-access-token"); + expect(createAccessToken).toHaveBeenCalledWith( + expect.objectContaining({ id: user.id }), + ); + }); + + test("throws error for invalid token", async ({ fixtures }) => { + const caller = createCaller({ user: null }); + const token = "invalid-token"; + + vi.mocked(verifyPayload).mockRejectedValue(new Error("Invalid token")); + + const error = await waitError(caller.authMagicLinkConfirm({ token })); + + expect(error).toMatchInlineSnapshot( + `[TRPCError: Invalid magic link token.]`, + ); + }); + + test("throws error for expired token", async ({ fixtures }) => { + const user = await fixtures.User({ active: true }); + const caller = createCaller({ user: null }); + const token = "expired-token"; + + const expiredDate = new Date(); + expiredDate.setMinutes(expiredDate.getMinutes() - 11); // 11 minutes ago + + vi.mocked(verifyPayload).mockResolvedValue({ + id: user.id, + email: user.email, + createdAt: expiredDate.toISOString(), + }); + + const error = await waitError(caller.authMagicLinkConfirm({ token })); + + expect(error).toMatchInlineSnapshot( + `[TRPCError: Invalid magic link token.]`, + ); + }); + + test("throws error for inactive user", async ({ fixtures }) => { + const user = await fixtures.User({ active: false }); + const caller = createCaller({ user: null }); + const token = "valid-token"; + + vi.mocked(verifyPayload).mockResolvedValue({ + id: user.id, + email: user.email, + createdAt: new Date().toISOString(), + }); + + const error = await waitError(caller.authMagicLinkConfirm({ token })); + + expect(error).toMatchInlineSnapshot( + `[TRPCError: Invalid magic link token.]`, + ); + }); + + test("throws error for non-existent user", async ({ fixtures }) => { + const caller = createCaller({ user: null }); + const token = "valid-token"; + + vi.mocked(verifyPayload).mockResolvedValue({ + id: "non-existent-id", + email: "nonexistent@example.com", + createdAt: new Date().toISOString(), + }); + + const error = await waitError(caller.authMagicLinkConfirm({ token })); + + expect(error).toMatchInlineSnapshot( + `[TRPCError: Invalid magic link token.]`, + ); + }); +}); diff --git a/apps/server/src/trpc/routes/authMagicLinkConfirm.ts b/apps/server/src/trpc/routes/authMagicLinkConfirm.ts new file mode 100644 index 000000000..7c5f58fd8 --- /dev/null +++ b/apps/server/src/trpc/routes/authMagicLinkConfirm.ts @@ -0,0 +1,89 @@ +import { db } from "@peated/server/db"; +import { users } from "@peated/server/db/schema"; +import { createAccessToken, verifyPayload } from "@peated/server/lib/auth"; +import { MagicLinkSchema } from "@peated/server/schemas/magicLink"; +import { serialize } from "@peated/server/serializers"; +import { UserSerializer } from "@peated/server/serializers/user"; +import { TRPCError } from "@trpc/server"; +import { and, eq, sql } from "drizzle-orm"; +import { z } from "zod"; +import { publicProcedure } from ".."; + +const TOKEN_CUTOFF = 600; // 10 minutes + +export default publicProcedure + .input( + z.object({ + token: z.string(), + }), + ) + .mutation(async function ({ input }) { + let payload; + try { + payload = await verifyPayload(input.token); + } catch (err) { + throw new TRPCError({ + code: "BAD_REQUEST", + message: "Invalid magic link token.", + cause: err, + }); + } + + let parsedPayload; + try { + parsedPayload = MagicLinkSchema.parse(payload); + } catch (err) { + throw new TRPCError({ + code: "BAD_REQUEST", + message: "Invalid magic link token.", + cause: err, + }); + } + + if ( + new Date(parsedPayload.createdAt).getTime() < + new Date().getTime() - TOKEN_CUTOFF * 1000 + ) { + throw new TRPCError({ + code: "BAD_REQUEST", + message: "Invalid magic link token.", + }); + } + + const [user] = await db + .select() + .from(users) + .where( + and( + eq(users.id, parsedPayload.id), + eq(sql`LOWER(${users.email})`, parsedPayload.email.toLowerCase()), + ), + ); + if (!user) { + throw new TRPCError({ + code: "BAD_REQUEST", + message: "Invalid magic link token.", + }); + } + + if (!user.active) { + throw new TRPCError({ + code: "BAD_REQUEST", + message: "Invalid magic link token.", + }); + } + + // Update user as verified + const [updatedUser] = await db + .update(users) + .set({ + verified: true, + }) + .where(eq(users.id, user.id)) + .returning(); + + return { + user: await serialize(UserSerializer, updatedUser, updatedUser), + accessToken: await createAccessToken(updatedUser), + }; + }); diff --git a/apps/server/src/trpc/routes/authMagicLinkSend.test.ts b/apps/server/src/trpc/routes/authMagicLinkSend.test.ts new file mode 100644 index 000000000..424276c84 --- /dev/null +++ b/apps/server/src/trpc/routes/authMagicLinkSend.test.ts @@ -0,0 +1,67 @@ +import { sendMagicLinkEmail } from "@peated/server/lib/email"; +import waitError from "@peated/server/lib/test/waitError"; +import { beforeEach, describe, expect, test, vi } from "vitest"; +import { createCaller } from "../router"; + +// Mock the sendMagicLinkEmail function +vi.mock("@peated/server/lib/email", () => ({ + sendMagicLinkEmail: vi.fn(), +})); + +describe("authMagicLinkSend", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + test("sends magic link for active user", async ({ fixtures }) => { + const user = await fixtures.User({ active: true }); + const caller = createCaller({ user: null }); + + const result = await caller.authMagicLinkSend({ + email: user.email, + }); + + expect(result).toEqual({}); + expect(sendMagicLinkEmail).toHaveBeenCalledWith({ user }); + }); + + test("throws error when user is not found", async ({ fixtures }) => { + const caller = createCaller({ user: null }); + + const error = await waitError( + caller.authMagicLinkSend({ + email: "nonexistent@example.com", + }), + ); + + expect(error).toMatchInlineSnapshot(`[TRPCError: Account not found.]`); + }); + + test("throws error when user is not active", async ({ fixtures }) => { + const user = await fixtures.User({ active: false }); + const caller = createCaller({ user: null }); + + const error = await waitError( + caller.authMagicLinkSend({ + email: user.email, + }), + ); + + expect(error).toMatchInlineSnapshot(`[TRPCError: Account not found.]`); + }); + + test("is case-insensitive for email", async ({ fixtures }) => { + const user = await fixtures.User({ + active: true, + email: "User@Example.com", + }); + const caller = createCaller({ user: null }); + + const result = await caller.authMagicLinkSend({ + email: "uSER@eXAMPLE.COM", + }); + + expect(result).toEqual({}); + expect(sendMagicLinkEmail).toHaveBeenCalledWith({ user }); + }); +}); diff --git a/apps/server/src/trpc/routes/authMagicLinkSend.ts b/apps/server/src/trpc/routes/authMagicLinkSend.ts new file mode 100644 index 000000000..a6322290b --- /dev/null +++ b/apps/server/src/trpc/routes/authMagicLinkSend.ts @@ -0,0 +1,40 @@ +import { db } from "@peated/server/db"; +import { users } from "@peated/server/db/schema"; +import { sendMagicLinkEmail } from "@peated/server/lib/email"; +import { TRPCError } from "@trpc/server"; +import { eq, sql } from "drizzle-orm"; +import { z } from "zod"; +import { publicProcedure } from ".."; + +export default publicProcedure + .input( + z.object({ + email: z.string().email(), + }), + ) + .mutation(async function ({ input: { email } }) { + const [user] = await db + .select() + .from(users) + .where(eq(sql`LOWER(${users.email})`, email.toLowerCase())); + + if (!user) { + console.log("user not found"); + throw new TRPCError({ + message: "Account not found.", + code: "NOT_FOUND", + }); + } + + if (!user.active) { + console.log("user not active"); + throw new TRPCError({ + message: "Account not found.", + code: "NOT_FOUND", + }); + } + + await sendMagicLinkEmail({ user }); + + return {}; + }); diff --git a/apps/server/src/trpc/routes/authPasswordReset.test.ts b/apps/server/src/trpc/routes/authPasswordReset.test.ts index 7603386af..3a062bb17 100644 --- a/apps/server/src/trpc/routes/authPasswordReset.test.ts +++ b/apps/server/src/trpc/routes/authPasswordReset.test.ts @@ -1,11 +1,72 @@ +import { sendPasswordResetEmail } from "@peated/server/lib/email"; +import waitError from "@peated/server/lib/test/waitError"; +import { TRPCError } from "@trpc/server"; import { createCaller } from "../router"; -test("initiates email", async ({ fixtures }) => { - const user = await fixtures.User(); +// Mock the sendPasswordResetEmail function +vi.mock("@peated/server/lib/email", () => ({ + sendPasswordResetEmail: vi.fn(), +})); - const caller = createCaller({ user: null }); +describe("authPasswordReset", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + test("initiates password reset email for existing user", async ({ + fixtures, + }) => { + const user = await fixtures.User(); + const caller = createCaller({ user: null }); + + await caller.authPasswordReset({ + email: user.email, + }); + + expect(sendPasswordResetEmail).toHaveBeenCalledTimes(1); + expect(sendPasswordResetEmail).toHaveBeenCalledWith({ user }); + }); + + test("does not leak information for non-existent user", async () => { + const caller = createCaller({ user: null }); + const nonExistentEmail = "nonexistent@example.com"; + + const err = await waitError( + caller.authPasswordReset({ + email: nonExistentEmail, + }), + ); + + expect(err).toBeInstanceOf(TRPCError); + expect((err as TRPCError).code).toBe("NOT_FOUND"); + expect(err).toMatchInlineSnapshot(`[TRPCError: Account not found.]`); + expect(sendPasswordResetEmail).not.toHaveBeenCalled(); + }); + + test("throws error for invalid email format", async () => { + const caller = createCaller({ user: null }); + const invalidEmail = "invalid-email"; + + const err = await waitError( + caller.authPasswordReset({ + email: invalidEmail, + }), + ); - await caller.authPasswordReset({ - email: user.email, + expect(err).toBeInstanceOf(TRPCError); + expect((err as TRPCError).code).toBe("BAD_REQUEST"); + expect(err).toMatchInlineSnapshot(` + [TRPCError: [ + { + "validation": "email", + "code": "invalid_string", + "message": "Invalid email", + "path": [ + "email" + ] + } + ]] + `); + expect(sendPasswordResetEmail).not.toHaveBeenCalled(); }); }); diff --git a/apps/server/src/trpc/routes/authPasswordReset.ts b/apps/server/src/trpc/routes/authPasswordReset.ts index 56902524e..fcce44c7b 100644 --- a/apps/server/src/trpc/routes/authPasswordReset.ts +++ b/apps/server/src/trpc/routes/authPasswordReset.ts @@ -9,7 +9,7 @@ import { publicProcedure } from ".."; export default publicProcedure .input( z.object({ - email: z.string(), + email: z.string().email(), }), ) .mutation(async function ({ input }) { diff --git a/apps/server/tsconfig.json b/apps/server/tsconfig.json index 66ac73a25..80853b135 100644 --- a/apps/server/tsconfig.json +++ b/apps/server/tsconfig.json @@ -1,15 +1,14 @@ { "extends": "@peated/tsconfig/base.json", "compilerOptions": { - "baseUrl": ".", "tsBuildInfoFile": "node_modules/.cache/tsbuildinfo.json", "types": ["node", "vitest/globals", "./src/global.d.ts"], "moduleResolution": "Node", "composite": true, "paths": { - "@peated/server/*": ["src/*"] + "@peated/server/*": ["./src/*"] } }, - "include": ["src"], - "exclude": ["src/test/setup-test-env.ts", "node_modules"] + "include": ["./src"], + "exclude": ["./src/test/setup-test-env.ts", "node_modules"] } diff --git a/apps/server/vitest.config.ts b/apps/server/vitest.config.mts similarity index 100% rename from apps/server/vitest.config.ts rename to apps/server/vitest.config.mts diff --git a/apps/web/src/app/(layout-free)/auth/magic-link/route.ts b/apps/web/src/app/(layout-free)/auth/magic-link/route.ts new file mode 100644 index 000000000..52f68c302 --- /dev/null +++ b/apps/web/src/app/(layout-free)/auth/magic-link/route.ts @@ -0,0 +1,37 @@ +import { makeTRPCClient } from "@peated/server/trpc/client"; +import config from "@peated/web/config"; +import { getSafeRedirect } from "@peated/web/lib/auth"; +import { logError } from "@peated/web/lib/log"; +import { getSession } from "@peated/web/lib/session.server"; +import { redirect } from "next/navigation"; + +export async function GET(request: Request) { + const { searchParams } = new URL(request.url); + const redirectTo = searchParams.get("redirectTo"); + const token = searchParams.get("token"); + if (!token) { + throw new Error("No token provided"); + } + + const session = await getSession(); + + const trpcClient = makeTRPCClient(config.API_SERVER, session.accessToken); + + let data; + try { + data = await trpcClient.authMagicLinkConfirm.mutate({ token }); + } catch (err) { + logError(err); + // in an ideal world this would simply render a component with the error, + // but Next does not allow us to mutate the session in RSC, and there's no + // way to render a component via route handlers afaik. + return redirect("/login?error=invalid-token"); + } + + session.user = data.user; + session.accessToken = data.accessToken; + + await session.save(); + + redirect(getSafeRedirect(redirectTo || "/")); +} diff --git a/apps/web/src/components/loginForm.tsx b/apps/web/src/components/loginForm.tsx index af2e5df8a..82e000a2b 100644 --- a/apps/web/src/components/loginForm.tsx +++ b/apps/web/src/components/loginForm.tsx @@ -37,13 +37,12 @@ function FormComponent() { label="Password" type="password" autoComplete="current-password" - required - placeholder="************" + helpText="Enter your password, or alternatively continue without and we'll email you a magic link." />
@@ -51,47 +50,57 @@ function FormComponent() { } export default function LoginForm() { - const [error, formAction] = useFormState(authenticateForm, undefined); + const [result, formAction] = useFormState(authenticateForm, undefined); return (
- {error ? {error} : null} + {result?.error ? {result.error} : null} - {config.GOOGLE_CLIENT_ID && ( + {result?.magicLink ? ( +

+ Please check your email to continue. +

+ ) : ( <> - -
-