Skip to content

Same agent Smaller bill. The tools and infrastructure to get more work from your AI. Fewer tokens. Less compute. Lower cost.

feat: auth redirection, common auth components (#6)

Aman Agarwal9c13e5e64d44
diff --git a/src/client/src/app/(auth)/auth-form.tsx b/src/client/src/app/(auth)/auth-form.tsx
new file mode 100644
index 00000000..cc1d0190
--- /dev/null
+++ b/src/client/src/app/(auth)/auth-form.tsx
@@ -0,0 +1,147 @@
+import asaw from "@/utils/asaw";
+import { Flex } from "@tremor/react";
+import { signIn } from "next-auth/react";
+import Link from "next/link";
+import { useState } from "react";
+
+const errors = {
+ Signin: "Try signing with a different account.",
+ OAuthSignin: "Try signing with a different account.",
+ OAuthCallback: "Try signing with a different account.",
+ OAuthCreateAccount: "Try signing with a different account.",
+ EmailCreateAccount: "Try signing with a different account.",
+ Callback: "Try signing with a different account.",
+ OAuthAccountNotLinked:
+ "To confirm your identity, sign in with the same account you used originally.",
+ EmailSignin: "Check your email address.",
+ CredentialsSignin:
+ "Sign in failed. Check the details you provided are correct.",
+ default: "Unable to sign in.",
+};
+
+const SignInError = ({ error }: { error: keyof typeof errors }) => {
+ const errorMessage = error && (errors[error] ?? errors.default);
+ return <div className="text-xs text-red-600 text-center">{errorMessage}</div>;
+};
+
+export function AuthForm({ type }: { type: "login" | "register" }) {
+ const [error, setError] = useState<string>("");
+ async function authWrapper(fn: any) {
+ const [err, response] = await asaw(fn());
+
+ if (err) {
+ setError(err.toString());
+ return;
+ }
+
+ if (!response.ok) {
+ setError(response.error);
+ return;
+ }
+
+ window.location.replace("/dashboard");
+ }
+ async function login(formData: FormData) {
+ authWrapper(() =>
+ signIn("login", {
+ callbackUrl: "/dashboard",
+ email: formData.get("email") as string,
+ password: formData.get("password") as string,
+ redirect: false,
+ })
+ );
+ }
+
+ async function register(formData: FormData) {
+ authWrapper(() =>
+ signIn("register", {
+ callbackUrl: "/dashboard",
+ email: formData.get("email") as string,
+ password: formData.get("password") as string,
+ redirect: false,
+ })
+ );
+ }
+
+ return (
+ <div className="flex h-screen w-screen items-center justify-center">
+ <div className="z-10 w-full max-w-md overflow-hidden rounded-2xl dark:text-gray-200 shadow-xl bg-gray-900">
+ <div className="flex flex-col items-center justify-center space-y-3 px-4 py-6 pt-8 text-center sm:px-16">
+ <h3 className="text-xl font-semibold">
+ {type === "login" ? "Sign In" : "Sign Up"}
+ </h3>
+ <p className="text-sm text-gray-500">
+ {type === "login"
+ ? "Use your email and password to sign in"
+ : "Create an account to enter"}
+ </p>
+ </div>
+ {error && <SignInError error={error as keyof typeof errors} />}
+ <form
+ action={type === "login" ? login : register}
+ className="flex flex-col space-y-4 px-4 py-8 sm:px-16 text-gray-900"
+ >
+ <Flex flexDirection="col" className="w-full" alignItems="start">
+ <label
+ htmlFor="email"
+ className="block text-xs dark:text-gray-200 uppercase"
+ >
+ Email Address
+ </label>
+ <input
+ id="email"
+ name="email"
+ type="email"
+ placeholder="[email protected]"
+ autoComplete="email"
+ required
+ className="mt-1 block w-full appearance-none border border-gray-300 px-3 py-2 placeholder-gray-400 shadow-sm focus:border-black focus:outline-none focus:ring-black sm:text-sm"
+ />
+ </Flex>
+ <Flex flexDirection="col" className="w-full" alignItems="start">
+ <label
+ htmlFor="password"
+ className="block text-xs dark:text-gray-200 uppercase"
+ >
+ Password
+ </label>
+ <input
+ autoComplete="current-password"
+ id="password"
+ name="password"
+ type="password"
+ required
+ className="mt-1 block w-full appearance-none border border-gray-300 px-3 py-2 placeholder-gray-400 shadow-sm focus:border-black focus:outline-none focus:ring-black sm:text-sm"
+ />
+ </Flex>
+ {type === "login" ? (
+ <button
+ type="submit"
+ className="dark:text-gray-200 bg-gray-600 p-3"
+ >
+ Sign in
+ </button>
+ ) : (
+ <button
+ type="submit"
+ className="dark:text-gray-200 bg-gray-600 p-3"
+ >
+ Sign Up
+ </button>
+ )}
+ <p className="text-center text-sm text-gray-600">
+ {type === "login"
+ ? "Don't have an account? "
+ : "Already have an account?"}
+ <Link
+ href={type === "login" ? "/register" : "/login"}
+ className="font-semibold text-gray-600"
+ >
+ {type === "login" ? " Sign up" : " Sign in"}
+ </Link>
+ </p>
+ </form>
+ </div>
+ </div>
+ );
+}
diff --git a/src/client/src/app/(auth)/form.tsx b/src/client/src/app/(auth)/form.tsx
deleted file mode 100644
index d1cc6add..00000000
--- a/src/client/src/app/(auth)/form.tsx
+++ /dev/null
@@ -1,48 +0,0 @@
-export function Form({
- action,
- children,
-}: {
- action: any;
- children: React.ReactNode;
-}) {
- return (
- <form
- action={action}
- className="flex flex-col space-y-4 px-4 py-8 sm:px-16"
- >
- <div>
- <label
- htmlFor="email"
- className="block text-xs dark:text-gray-200 uppercase"
- >
- Email Address
- </label>
- <input
- id="email"
- name="email"
- type="email"
- placeholder="[email protected]"
- autoComplete="email"
- required
- className="mt-1 block w-full appearance-none border border-gray-300 px-3 py-2 placeholder-gray-400 shadow-sm focus:border-black focus:outline-none focus:ring-black sm:text-sm"
- />
- </div>
- <div>
- <label
- htmlFor="password"
- className="block text-xs dark:text-gray-200 uppercase"
- >
- Password
- </label>
- <input
- id="password"
- name="password"
- type="password"
- required
- className="mt-1 block w-full appearance-none border border-gray-300 px-3 py-2 placeholder-gray-400 shadow-sm focus:border-black focus:outline-none focus:ring-black sm:text-sm"
- />
- </div>
- {children}
- </form>
- );
-}
diff --git a/src/client/src/app/(auth)/login/page.tsx b/src/client/src/app/(auth)/login/page.tsx
index b095d816..ca64d68a 100644
--- a/src/client/src/app/(auth)/login/page.tsx
+++ b/src/client/src/app/(auth)/login/page.tsx
@@ -1,39 +1,6 @@
"use client";
-import Link from "next/link";
-import { Form } from "../form";
-import { signIn } from "next-auth/react";
-import asaw from "@/utils/asaw";
+import { AuthForm } from "../auth-form";
export default function Login() {
- const login = async (formData: FormData) => {
- await asaw(
- signIn("login", {
- callbackUrl: "/dashboard",
- email: formData.get("email") as string,
- password: formData.get("password") as string,
- })
- );
- };
- return (
- <div className="flex h-screen w-screen items-center justify-center">
- <div className="z-10 w-full max-w-md overflow-hidden rounded-2xl dark:text-gray-200 shadow-xl bg-gray-900">
- <div className="flex flex-col items-center justify-center space-y-3 px-4 py-6 pt-8 text-center sm:px-16">
- <h3 className="text-xl font-semibold">Sign In</h3>
- <p className="text-sm text-gray-500">
- Use your email and password to sign in
- </p>
- </div>
- <Form action={login}>
- <button type="submit" className="dark:text-gray-200 bg-gray-600 p-3">Sign in</button>
- <p className="text-center text-sm text-gray-600">
- {"Don't have an account? "}
- <Link href="/register" className="font-semibold text-gray-600">
- Sign up
- </Link>
- {" for free."}
- </p>
- </Form>
- </div>
- </div>
- );
+ return <AuthForm type={"login"} />;
}
diff --git a/src/client/src/app/(auth)/register/page.tsx b/src/client/src/app/(auth)/register/page.tsx
index dd090dd4..b3d21e13 100644
--- a/src/client/src/app/(auth)/register/page.tsx
+++ b/src/client/src/app/(auth)/register/page.tsx
@@ -1,37 +1,6 @@
"use client";
-import Link from "next/link";
-import { Form } from "../form";
-import { signIn } from "next-auth/react";
+import { AuthForm } from "../auth-form";
export default function Login() {
- async function register(formData: FormData) {
- signIn("register", {
- callbackUrl: "/dashboard",
- email: formData.get("email") as string,
- password: formData.get("password") as string,
- });
- }
-
- return (
- <div className="flex h-screen w-screen items-center justify-center">
- <div className="z-10 w-full max-w-md overflow-hidden rounded-2xl dark:text-gray-200 shadow-xl bg-gray-900">
- <div className="flex flex-col items-center justify-center space-y-3 px-4 py-6 pt-8 text-center sm:px-16">
- <h3 className="text-xl font-semibold">Sign Up</h3>
- <p className="text-sm text-gray-500">
- Create an account with your email and password
- </p>
- </div>
- <Form action={register}>
- <button type="submit" className="dark:text-gray-200 bg-gray-600 p-3">Sign Up</button>
- <p className="text-center text-sm text-gray-600">
- {"Already have an account? "}
- <Link href="/login" className="font-semibold text-gray-600">
- Sign in
- </Link>
- {" instead."}
- </p>
- </Form>
- </div>
- </div>
- );
+ return <AuthForm type={"register"} />;
}
diff --git a/src/client/src/app/page.tsx b/src/client/src/app/page.tsx
deleted file mode 100644
index 8b6f79f8..00000000
--- a/src/client/src/app/page.tsx
+++ /dev/null
@@ -1,7 +0,0 @@
-import Image from "next/image";
-import { redirect } from "next/navigation";
-import { authOptions } from "./auth";
-
-export default function Home() {
- return redirect(authOptions?.pages?.signIn || "/login");
-}
diff --git a/src/client/src/lib/user.ts b/src/client/src/lib/user.ts
index 7f3a2cde..3ee6c51c 100644
--- a/src/client/src/lib/user.ts
+++ b/src/client/src/lib/user.ts
@@ -64,16 +64,14 @@ export const createNewUser = async (
let createdUser = await prisma.user.create({
data: {
email,
- password,
+ password: hash,
},
});
- console.log("register createdUser ", createdUser);
if (createdUser?.id) {
// @ts-expect-error
return exclude(createdUser, options?.selectPassword && []);
}
- console.log("register error");
throw new Error("Cannot create a user!");
};
diff --git a/src/client/src/middleware.ts b/src/client/src/middleware.ts
index 6c32b1d8..eebf1c48 100644
--- a/src/client/src/middleware.ts
+++ b/src/client/src/middleware.ts
@@ -1,16 +1,53 @@
+import { getToken } from "next-auth/jwt";
import { withAuth } from "next-auth/middleware";
+import { NextResponse } from "next/server";
export default withAuth(
- // `withAuth` augments your `Request` with the user's token.
- function middleware() {},
+ async function middleware(req) {
+ const token = await getToken({ req });
+ const isAuth = !!token;
+ const isAuthPage =
+ req.nextUrl.pathname.startsWith("/login") ||
+ req.nextUrl.pathname.startsWith("/register");
+ const isApiPage = req.nextUrl.pathname.startsWith("/api");
+
+ if (isAuthPage) {
+ if (isAuth) {
+ return NextResponse.redirect(new URL("/dashboard", req.url));
+ }
+
+ return null;
+ }
+
+ if (isApiPage) {
+ if (isAuth) {
+ return NextResponse.next();
+ }
+ }
+
+ if (!isAuth) {
+ let from = req.nextUrl.pathname;
+ if (req.nextUrl.search) {
+ from += req.nextUrl.search;
+ }
+
+ return NextResponse.redirect(
+ new URL(`/login?callbackUrl=${encodeURIComponent(from)}`, req.url)
+ );
+ }
+ },
{
callbacks: {
- authorized: ({ token }) => !!token?.id,
+ authorized() {
+ // This is a work-around for handling redirect on auth pages.
+ // We return true here so that the middleware function above
+ // is always called.
+ return true;
+ },
},
}
);
-// See "Matching Paths" below to learn more
export const config = {
- matcher: "/dashboard",
+ matcher: ["/api/:path*", "/dashboard/:path*", "/login", "/register"],
};