提问人:Rahul Battin 提问时间:11/16/2023 最后编辑:VolkorpRahul Battin 更新时间:11/17/2023 访问量:26
我得不到这份工作,有人可以帮助我吗?
I can't get this work can someone help me?
问:
以下是我使用 CredentialsProvider 及其配置的 NextAuth 代码。
import type { NextAuthOptions } from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import User from "@/models/userModel";
import { connectToDb } from "@/lib/connectToDb";
export const authOptions: NextAuthOptions = {
providers: [
CredentialsProvider({
name: "Sign In",
credentials: {
username: { type: "text" },
password: { type: "password" },
},
async authorize(
credentials: Record<"username" | "password", string> | undefined
) {
if (!credentials?.username || !credentials?.password) {
return null;
}
connectToDb();
const user = await User.findOne({
$or: [
{ username: credentials.username },
{ email: credentials.username },
],
}).select("+password");
if (!user) {
return null;
}
const comparePassword = await user.comparePassword(
credentials.password
);
if (!comparePassword) {
return null;
}
console.log(user);
return user;
},
}),
],
secret: process.env.NEXTAUTH_SECRET,
callbacks: {
async session({ session, token }) {
console.log("session token", { session, token });
return {
...session,
user: {
...session.user,
_id: token._id,
username: token.username,
},
};
},
async jwt({ token, user }) {
if (user) {
return {
...token,
id: user._id,
username: user.username,
};
}
return token;
},
},
pages: {
signIn: "/login",
signOut: "/login",
error: "/login",
},
session: {
strategy: "jwt",
},
};
我在next-auth.d.ts中也有声明文件:
import { DefaultSession, DefaultUser } from "next-auth";
import { DefaultJWT } from "next-auth/jwt";
declare module "next-auth" {
interface Session {
user: {
_id: string;
username: string;
} & DefaultSession;
}
interface User extends DefaultUser {
_id: string;
username: string;
fullname: string;
email: string;
isVerified: boolean;
verificationToken: Record<string | null>;
}
}
declare module "next-auth/jwt" {
interface JWT extends DefaultJWT {
_id: string;
username: string;
}
}
我想为上面的代码获取中间件,我写了一些代码
import { withAuth, NextRequestWithAuth } from "next-auth/middleware";
import { NextResponse } from "next/server";
export default withAuth(
function middleware(request: NextRequestWithAuth) {
console.log(request.nextauth.token);
console.log(request.nextUrl.pathname);
},
{
// callbacks
pages: {
signIn: "/login",
signOut: "/login",
error: "/login",
},
}
);
export const config = {
matcher: ["/", "/login", "/verifyemail"],
};
这里的问题是这个中间件不适用于“/login”路由?
我尝试了这项工作。
但是我也想为“/login”路径匹配器处理这个中间件代码?
答: 暂无答案
评论