fix(auth): migrate from next-auth to better-auth (#1453)
This commit is contained in:
parent
453f5bb3e6
commit
b4f595a68c
40 changed files with 668 additions and 390 deletions
|
|
@ -1,10 +1,7 @@
|
|||
"use server";
|
||||
|
||||
import { z } from "zod";
|
||||
|
||||
import { createUser, getUser } from "@/lib/db/queries";
|
||||
|
||||
import { signIn } from "./auth";
|
||||
import { auth } from "@/lib/auth";
|
||||
|
||||
const authFormSchema = z.object({
|
||||
email: z.string().email(),
|
||||
|
|
@ -25,10 +22,11 @@ export const login = async (
|
|||
password: formData.get("password"),
|
||||
});
|
||||
|
||||
await signIn("credentials", {
|
||||
email: validatedData.email,
|
||||
password: validatedData.password,
|
||||
redirect: false,
|
||||
await auth.api.signInEmail({
|
||||
body: {
|
||||
email: validatedData.email,
|
||||
password: validatedData.password,
|
||||
},
|
||||
});
|
||||
|
||||
return { status: "success" };
|
||||
|
|
@ -61,24 +59,29 @@ export const register = async (
|
|||
password: formData.get("password"),
|
||||
});
|
||||
|
||||
const [user] = await getUser(validatedData.email);
|
||||
|
||||
if (user) {
|
||||
return { status: "user_exists" } as RegisterActionState;
|
||||
}
|
||||
await createUser(validatedData.email, validatedData.password);
|
||||
await signIn("credentials", {
|
||||
email: validatedData.email,
|
||||
password: validatedData.password,
|
||||
redirect: false,
|
||||
const result = await auth.api.signUpEmail({
|
||||
body: {
|
||||
email: validatedData.email,
|
||||
password: validatedData.password,
|
||||
name: validatedData.email,
|
||||
},
|
||||
});
|
||||
|
||||
if (!result) {
|
||||
return { status: "failed" };
|
||||
}
|
||||
|
||||
return { status: "success" };
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError) {
|
||||
return { status: "invalid_data" };
|
||||
}
|
||||
|
||||
const message = error instanceof Error ? error.message : "";
|
||||
if (message.includes("already exists") || message.includes("UNIQUE")) {
|
||||
return { status: "user_exists" };
|
||||
}
|
||||
|
||||
return { status: "failed" };
|
||||
}
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1 +0,0 @@
|
|||
export { GET, POST } from "@/app/(auth)/auth";
|
||||
|
|
@ -1,21 +0,0 @@
|
|||
import { NextResponse } from "next/server";
|
||||
import { getToken } from "next-auth/jwt";
|
||||
import { signIn } from "@/app/(auth)/auth";
|
||||
import { isDevelopmentEnvironment } from "@/lib/constants";
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const redirectUrl = searchParams.get("redirectUrl") || "/";
|
||||
|
||||
const token = await getToken({
|
||||
req: request,
|
||||
secret: process.env.AUTH_SECRET,
|
||||
secureCookie: !isDevelopmentEnvironment,
|
||||
});
|
||||
|
||||
if (token) {
|
||||
return NextResponse.redirect(new URL("/", request.url));
|
||||
}
|
||||
|
||||
return signIn("guest", { redirect: true, redirectTo: redirectUrl });
|
||||
}
|
||||
|
|
@ -1,14 +0,0 @@
|
|||
import type { NextAuthConfig } from "next-auth";
|
||||
|
||||
export const authConfig = {
|
||||
basePath: "/api/auth",
|
||||
pages: {
|
||||
signIn: "/login",
|
||||
newUser: "/",
|
||||
},
|
||||
providers: [
|
||||
// added later in auth.ts since it requires bcrypt which is only compatible with Node.js
|
||||
// while this file is also used in non-Node.js environments
|
||||
],
|
||||
callbacks: {},
|
||||
} satisfies NextAuthConfig;
|
||||
|
|
@ -1,94 +0,0 @@
|
|||
import { compare } from "bcrypt-ts";
|
||||
import NextAuth, { type DefaultSession } from "next-auth";
|
||||
import type { DefaultJWT } from "next-auth/jwt";
|
||||
import Credentials from "next-auth/providers/credentials";
|
||||
import { DUMMY_PASSWORD } from "@/lib/constants";
|
||||
import { createGuestUser, getUser } from "@/lib/db/queries";
|
||||
import { authConfig } from "./auth.config";
|
||||
|
||||
export type UserType = "guest" | "regular";
|
||||
|
||||
declare module "next-auth" {
|
||||
interface Session extends DefaultSession {
|
||||
user: {
|
||||
id: string;
|
||||
type: UserType;
|
||||
} & DefaultSession["user"];
|
||||
}
|
||||
|
||||
interface User {
|
||||
id?: string;
|
||||
email?: string | null;
|
||||
type: UserType;
|
||||
}
|
||||
}
|
||||
|
||||
declare module "next-auth/jwt" {
|
||||
interface JWT extends DefaultJWT {
|
||||
id: string;
|
||||
type: UserType;
|
||||
}
|
||||
}
|
||||
|
||||
export const {
|
||||
handlers: { GET, POST },
|
||||
auth,
|
||||
signIn,
|
||||
signOut,
|
||||
} = NextAuth({
|
||||
...authConfig,
|
||||
providers: [
|
||||
Credentials({
|
||||
credentials: {},
|
||||
async authorize({ email, password }: any) {
|
||||
const users = await getUser(email);
|
||||
|
||||
if (users.length === 0) {
|
||||
await compare(password, DUMMY_PASSWORD);
|
||||
return null;
|
||||
}
|
||||
|
||||
const [user] = users;
|
||||
|
||||
if (!user.password) {
|
||||
await compare(password, DUMMY_PASSWORD);
|
||||
return null;
|
||||
}
|
||||
|
||||
const passwordsMatch = await compare(password, user.password);
|
||||
|
||||
if (!passwordsMatch) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return { ...user, type: "regular" };
|
||||
},
|
||||
}),
|
||||
Credentials({
|
||||
id: "guest",
|
||||
credentials: {},
|
||||
async authorize() {
|
||||
const [guestUser] = await createGuestUser();
|
||||
return { ...guestUser, type: "guest" };
|
||||
},
|
||||
}),
|
||||
],
|
||||
callbacks: {
|
||||
jwt({ token, user }) {
|
||||
if (user) {
|
||||
token.id = user.id as string;
|
||||
token.type = user.type;
|
||||
}
|
||||
|
||||
return token;
|
||||
},
|
||||
session({ session, token }) {
|
||||
if (session.user) {
|
||||
session.user.id = token.id;
|
||||
session.user.type = token.type;
|
||||
}
|
||||
|
||||
return session;
|
||||
},
|
||||
},
|
||||
});
|
||||
|
|
@ -2,12 +2,12 @@
|
|||
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useSession } from "next-auth/react";
|
||||
import { useActionState, useEffect, useState } from "react";
|
||||
|
||||
import { AuthForm } from "@/components/auth-form";
|
||||
import { SubmitButton } from "@/components/submit-button";
|
||||
import { toast } from "@/components/toast";
|
||||
import { useSession } from "@/lib/client";
|
||||
import { type LoginActionState, login } from "../actions";
|
||||
|
||||
export default function Page() {
|
||||
|
|
@ -23,9 +23,9 @@ export default function Page() {
|
|||
}
|
||||
);
|
||||
|
||||
const { update: updateSession } = useSession();
|
||||
const { refetch } = useSession();
|
||||
|
||||
// biome-ignore lint/correctness/useExhaustiveDependencies: router and updateSession are stable refs
|
||||
// biome-ignore lint/correctness/useExhaustiveDependencies: router and refetch are stable refs
|
||||
useEffect(() => {
|
||||
if (state.status === "failed") {
|
||||
toast({
|
||||
|
|
@ -39,7 +39,7 @@ export default function Page() {
|
|||
});
|
||||
} else if (state.status === "success") {
|
||||
setIsSuccessful(true);
|
||||
updateSession();
|
||||
refetch();
|
||||
router.refresh();
|
||||
}
|
||||
}, [state.status]);
|
||||
|
|
|
|||
|
|
@ -2,11 +2,11 @@
|
|||
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useSession } from "next-auth/react";
|
||||
import { useActionState, useEffect, useState } from "react";
|
||||
import { AuthForm } from "@/components/auth-form";
|
||||
import { SubmitButton } from "@/components/submit-button";
|
||||
import { toast } from "@/components/toast";
|
||||
import { useSession } from "@/lib/client";
|
||||
import { type RegisterActionState, register } from "../actions";
|
||||
|
||||
export default function Page() {
|
||||
|
|
@ -22,9 +22,9 @@ export default function Page() {
|
|||
}
|
||||
);
|
||||
|
||||
const { update: updateSession } = useSession();
|
||||
const { refetch } = useSession();
|
||||
|
||||
// biome-ignore lint/correctness/useExhaustiveDependencies: router and updateSession are stable refs
|
||||
// biome-ignore lint/correctness/useExhaustiveDependencies: router and refetch are stable refs
|
||||
useEffect(() => {
|
||||
if (state.status === "user_exists") {
|
||||
toast({ type: "error", description: "Account already exists!" });
|
||||
|
|
@ -39,7 +39,7 @@ export default function Page() {
|
|||
toast({ type: "success", description: "Account created successfully!" });
|
||||
|
||||
setIsSuccessful(true);
|
||||
updateSession();
|
||||
refetch();
|
||||
router.refresh();
|
||||
}
|
||||
}, [state.status]);
|
||||
|
|
|
|||
4
app/(chat)/api/auth/[...all]/route.ts
Normal file
4
app/(chat)/api/auth/[...all]/route.ts
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
import { toNextJsHandler } from "better-auth/next-js";
|
||||
import { auth } from "@/lib/auth";
|
||||
|
||||
export const { GET, POST } = toNextJsHandler(auth);
|
||||
|
|
@ -10,7 +10,6 @@ import {
|
|||
import { checkBotId } from "botid/server";
|
||||
import { after } from "next/server";
|
||||
import { createResumableStreamContext } from "resumable-stream";
|
||||
import { auth, type UserType } from "@/app/(auth)/auth";
|
||||
import { entitlementsByUserType } from "@/lib/ai/entitlements";
|
||||
import { allowedModelIds } from "@/lib/ai/models";
|
||||
import { type RequestHints, systemPrompt } from "@/lib/ai/prompts";
|
||||
|
|
@ -19,6 +18,7 @@ import { createDocument } from "@/lib/ai/tools/create-document";
|
|||
import { getWeather } from "@/lib/ai/tools/get-weather";
|
||||
import { requestSuggestions } from "@/lib/ai/tools/request-suggestions";
|
||||
import { updateDocument } from "@/lib/ai/tools/update-document";
|
||||
import { getSession, getUserType, type UserType } from "@/lib/auth";
|
||||
import { isProductionEnvironment } from "@/lib/constants";
|
||||
import {
|
||||
createStreamId,
|
||||
|
|
@ -67,7 +67,7 @@ export async function POST(request: Request) {
|
|||
|
||||
const [, session] = await Promise.all([
|
||||
checkBotId().catch(() => null),
|
||||
auth(),
|
||||
getSession(),
|
||||
]);
|
||||
|
||||
if (!session?.user) {
|
||||
|
|
@ -80,7 +80,7 @@ export async function POST(request: Request) {
|
|||
|
||||
await checkIpRateLimit(ipAddress(request));
|
||||
|
||||
const userType: UserType = session.user.type;
|
||||
const userType: UserType = getUserType(session.user);
|
||||
|
||||
const messageCount = await getMessageCountByUserId({
|
||||
id: session.user.id,
|
||||
|
|
@ -295,7 +295,7 @@ export async function DELETE(request: Request) {
|
|||
return new ChatbotError("bad_request:api").toResponse();
|
||||
}
|
||||
|
||||
const session = await auth();
|
||||
const session = await getSession();
|
||||
|
||||
if (!session?.user) {
|
||||
return new ChatbotError("unauthorized:chat").toResponse();
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { auth } from "@/app/(auth)/auth";
|
||||
import type { ArtifactKind } from "@/components/artifact";
|
||||
import { getSession } from "@/lib/auth";
|
||||
import {
|
||||
deleteDocumentsByIdAfterTimestamp,
|
||||
getDocumentsById,
|
||||
|
|
@ -18,7 +18,7 @@ export async function GET(request: Request) {
|
|||
).toResponse();
|
||||
}
|
||||
|
||||
const session = await auth();
|
||||
const session = await getSession();
|
||||
|
||||
if (!session?.user) {
|
||||
return new ChatbotError("unauthorized:document").toResponse();
|
||||
|
|
@ -50,7 +50,7 @@ export async function POST(request: Request) {
|
|||
).toResponse();
|
||||
}
|
||||
|
||||
const session = await auth();
|
||||
const session = await getSession();
|
||||
|
||||
if (!session?.user) {
|
||||
return new ChatbotError("not_found:document").toResponse();
|
||||
|
|
@ -103,7 +103,7 @@ export async function DELETE(request: Request) {
|
|||
).toResponse();
|
||||
}
|
||||
|
||||
const session = await auth();
|
||||
const session = await getSession();
|
||||
|
||||
if (!session?.user) {
|
||||
return new ChatbotError("unauthorized:document").toResponse();
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ import { put } from "@vercel/blob";
|
|||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
|
||||
import { auth } from "@/app/(auth)/auth";
|
||||
import { getSession } from "@/lib/auth";
|
||||
|
||||
// Use Blob instead of File since File is not available in Node.js environment
|
||||
const FileSchema = z.object({
|
||||
|
|
@ -18,7 +18,7 @@ const FileSchema = z.object({
|
|||
});
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const session = await auth();
|
||||
const session = await getSession();
|
||||
|
||||
if (!session) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import type { NextRequest } from "next/server";
|
||||
import { auth } from "@/app/(auth)/auth";
|
||||
import { getSession } from "@/lib/auth";
|
||||
import { deleteAllChatsByUserId, getChatsByUserId } from "@/lib/db/queries";
|
||||
import { ChatbotError } from "@/lib/errors";
|
||||
|
||||
|
|
@ -17,7 +17,7 @@ export async function GET(request: NextRequest) {
|
|||
).toResponse();
|
||||
}
|
||||
|
||||
const session = await auth();
|
||||
const session = await getSession();
|
||||
|
||||
if (!session?.user) {
|
||||
return new ChatbotError("unauthorized:chat").toResponse();
|
||||
|
|
@ -34,7 +34,7 @@ export async function GET(request: NextRequest) {
|
|||
}
|
||||
|
||||
export async function DELETE() {
|
||||
const session = await auth();
|
||||
const session = await getSession();
|
||||
|
||||
if (!session?.user) {
|
||||
return new ChatbotError("unauthorized:chat").toResponse();
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { auth } from "@/app/(auth)/auth";
|
||||
import { getSession } from "@/lib/auth";
|
||||
import { getSuggestionsByDocumentId } from "@/lib/db/queries";
|
||||
import { ChatbotError } from "@/lib/errors";
|
||||
|
||||
|
|
@ -13,7 +13,7 @@ export async function GET(request: Request) {
|
|||
).toResponse();
|
||||
}
|
||||
|
||||
const session = await auth();
|
||||
const session = await getSession();
|
||||
|
||||
if (!session?.user) {
|
||||
return new ChatbotError("unauthorized:suggestions").toResponse();
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { auth } from "@/app/(auth)/auth";
|
||||
import { getSession } from "@/lib/auth";
|
||||
import { getChatById, getVotesByChatId, voteMessage } from "@/lib/db/queries";
|
||||
import { ChatbotError } from "@/lib/errors";
|
||||
|
||||
|
|
@ -13,7 +13,7 @@ export async function GET(request: Request) {
|
|||
).toResponse();
|
||||
}
|
||||
|
||||
const session = await auth();
|
||||
const session = await getSession();
|
||||
|
||||
if (!session?.user) {
|
||||
return new ChatbotError("unauthorized:vote").toResponse();
|
||||
|
|
@ -49,7 +49,7 @@ export async function PATCH(request: Request) {
|
|||
).toResponse();
|
||||
}
|
||||
|
||||
const session = await auth();
|
||||
const session = await getSession();
|
||||
|
||||
if (!session?.user) {
|
||||
return new ChatbotError("unauthorized:vote").toResponse();
|
||||
|
|
|
|||
|
|
@ -1,11 +1,10 @@
|
|||
import { cookies } from "next/headers";
|
||||
import { notFound, redirect } from "next/navigation";
|
||||
import { Suspense } from "react";
|
||||
|
||||
import { auth } from "@/app/(auth)/auth";
|
||||
import { Chat } from "@/components/chat";
|
||||
import { DataStreamHandler } from "@/components/data-stream-handler";
|
||||
import { DEFAULT_CHAT_MODEL } from "@/lib/ai/models";
|
||||
import { getSession } from "@/lib/auth";
|
||||
import { getChatById, getMessagesByChatId } from "@/lib/db/queries";
|
||||
import { convertToUIMessages } from "@/lib/utils";
|
||||
|
||||
|
|
@ -25,10 +24,10 @@ async function ChatPage({ params }: { params: Promise<{ id: string }> }) {
|
|||
redirect("/");
|
||||
}
|
||||
|
||||
const session = await auth();
|
||||
const session = await getSession();
|
||||
|
||||
if (!session) {
|
||||
redirect("/api/auth/guest");
|
||||
redirect("/login");
|
||||
}
|
||||
|
||||
if (chat.visibility === "private") {
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import { Suspense } from "react";
|
|||
import { AppSidebar } from "@/components/app-sidebar";
|
||||
import { DataStreamProvider } from "@/components/data-stream-provider";
|
||||
import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar";
|
||||
import { auth } from "../(auth)/auth";
|
||||
import { getSession } from "@/lib/auth";
|
||||
|
||||
export default function Layout({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
|
|
@ -23,7 +23,7 @@ export default function Layout({ children }: { children: React.ReactNode }) {
|
|||
}
|
||||
|
||||
async function SidebarWrapper({ children }: { children: React.ReactNode }) {
|
||||
const [session, cookieStore] = await Promise.all([auth(), cookies()]);
|
||||
const [session, cookieStore] = await Promise.all([getSession(), cookies()]);
|
||||
const isCollapsed = cookieStore.get("sidebar_state")?.value !== "true";
|
||||
|
||||
return (
|
||||
|
|
|
|||
|
|
@ -6,7 +6,6 @@ import { ThemeProvider } from "@/components/theme-provider";
|
|||
import "katex/dist/katex.min.css";
|
||||
|
||||
import "./globals.css";
|
||||
import { SessionProvider } from "next-auth/react";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
metadataBase: new URL("https://chat.vercel.ai"),
|
||||
|
|
@ -81,7 +80,7 @@ export default function RootLayout({
|
|||
enableSystem
|
||||
>
|
||||
<Toaster position="top-center" />
|
||||
<SessionProvider>{children}</SessionProvider>
|
||||
{children}
|
||||
</ThemeProvider>
|
||||
<Analytics />
|
||||
</body>
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue