自定义会话 next js next-auth

jus*_*est 9 javascript node.js typescript next.js next-auth

我在迁移 js 文件 jo tsx 时遇到问题,我正在做的是使用凭据登录并将会话用户自定义为我的用户数据

// api/auth/[...nextauth].js

import NextAuth from "next-auth";
import Providers from "next-auth/providers";
import { ConnectDatabase } from "../../../lib/db";
import { VertifyPassword } from "../../../lib/password";
import { getSelectedUser } from "../../../helpers/database";
import { MongoClient } from "mongodb";
import { NextApiRequest } from "next";

interface credentialsData {
 data: string | number;
 password: string;
}
export default NextAuth({
 session: {
   jwt: true,
 },
 callbacks: {
   async session(session) {
     const data = await getSelectedUser(session.user.email);
     session.user = data.userData;

// inside data.userdata is a object
// {
//   _id: '60a92f328dc04f58207388d1',
//   email: 'user@user.com',
//   phone: '087864810221',
//   point: 0,
//   role: 'user',
//   accountstatus: 'false'
// }
     return Promise.resolve(session);
   },
 },
 providers: [
   Providers.Credentials({
     async authorize(credentials: credentialsData, req: NextApiRequest) {
       let client;
       try {
         client = await ConnectDatabase();
       } catch (error) {
         throw new Error("Failed connet to database.");
       }

       const checkEmail = await client
         .db()
         .collection("users")
         .findOne({ email: credentials.data });
       const checkPhone = await client
         .db()
         .collection("users")
         .findOne({ phone: credentials.data });

       let validData = {
         password: "",
         email: "",
       };

       if (!checkEmail && !checkPhone) {
         client.close();
         throw new Error("Email atau No HP tidak terdaftar.");
       } else if (checkEmail) {
         validData = checkEmail;
       } else if (checkPhone) {
         validData = checkPhone;
       }

       const checkPassword = await VertifyPassword(
         credentials.password,
         validData.password
       );
       if (!checkPassword) {
         client.close();
         throw new Error("Password Salah.");
       }
       client.close();

// inside validData is a object
// {
//   _id: '60a92f328dc04f58207388d1',
//   email: 'user@user.com',
//   phone: '087864810221',
//   point: 0,
//   role: 'user',
//   accountstatus: 'false'
// }

       return validData;
     },
   }),
 ],
});
// as default provider just return session.user just return email,name, and image, but I want custom the session.user to user data what I got from dababase
Run Code Online (Sandbox Code Playgroud)

这在客户端

// index.tsx

export const getServerSideProps: GetServerSideProps<{
  session: Session | null;
}> = async (context) => {
  const session = await getSession({ req: context.req });

  if (session) {
    if (session.user?.role === "admin") {
      return {
        redirect: {
          destination: "/admin/home",
          permanent: false,
        },
      };
    }
  }
  return {
    props: {
      session,
    },
  };
};
Run Code Online (Sandbox Code Playgroud)

但在客户端我收到警告

Property 'role' does not exist on type '{ name?: string; email?: string; image?: string; 
Run Code Online (Sandbox Code Playgroud)

实际上我的文件仍然工作正常,但是当我的文件js格式正确时,它不会发出这样的警告

有人可以帮我解决它吗?

小智 7

我想现在您已经解决了这个问题,但由于我遇到了同样的问题,我想我应该发布我的解决方案。以防万一其他人碰到它。我是 typescript/nextjs 的新手,没有意识到我只需创建一个类型定义文件即可将角色字段添加到 session.user

您在这里所做的是将更改合并到 next-auth 模块中,如此处所述

我创建了 /types/next-auth.d.ts

import NextAuth from "next-auth";

declare module "next-auth" {
  interface Session {
    user: {
      id: string;
      username: string;
      email: string;
      role: string;
      [key: string]: string;
    };
  }
}
Run Code Online (Sandbox Code Playgroud)

然后我必须将其添加到我的 tsconfig.json 中

  "include": ["next-env.d.ts", "types/**/*.ts", "**/*.ts", "**/*.tsx"],
Run Code Online (Sandbox Code Playgroud)


小智 6

不确定您是否找到了解决方法,但您还需要配置 jwt 回调!这是我的一个项目的示例:

callbacks: {
        async session(session, token) {
            session.accessToken = token.accessToken;
            session.user = token.user;
            return session;
        },
        async jwt(token, user, account, profile, isNewUser) {
            if (user) {
                token.accessToken = user._id;
                token.user = user;
            }
            return token;
        },
    },
Run Code Online (Sandbox Code Playgroud)

来解释事情。jwt 函数始终在会话之前运行,因此您传递给 jwt 令牌的任何数据都将在会话函数上可用,您可以用它做任何您想做的事情。在 jwt 函数中,我检查是否有用户,因为这只在您登录时返回数据。