回调时出现Nextauth错误的credentialProvider

r7knjye2  于 2023-05-28  发布在  其他
关注(0)|答案(1)|浏览(103)

我正在构建一个自定义的credentialProvider与下一个auth,这是我的逻辑登录

credentials: {
        email: { label: 'email', type: 'email', placeholder: 'Your email' },
        password: { label: 'Password', type: 'password' },
      },
      async authorize(credentials) {
        try {
          const { email, password } = credentials;
          const login: Awaited<Promise<LoginResponse>> = await fetch(
            `${process.env.NEXT_PUBLIC_API_URL}${process.env.NEXT_PLUBIC_API_LOGIN}`,
            {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json',
              },
              body: JSON.stringify({ email, password }),
            },
          )
            .then((res) => res.json() as Promise<LoginResponse>)
            .then((json) => json);

          const {
            token,
            user: { _id, name },
          } = login;

          if (!token || !name || !_id) return null;

          return {
            token,
            name,
            email,
            id: _id,
          };
        } catch (error) {
          return null;
        }
      },
    }),

如你所见,我的用户是一个对象,其类型为

{
   token:string;
   name:string,
   email:string,
   id:string
}

但是,在我的jwt的回调函数中,USER没有TOKEN键。

callbacks: {
    jwt: async ({ token, user }) => {
      const isSignIn = !!user;
      const currentDateInSeconds = Math.floor(Date.now() / 1000);
      const expirateDateInSeconds = Math.floor(7 * 24 * 60 * 60);
      if (isSignIn) {
        token.email = user.email;
        token.name = user.name;
        token.token = user.token; //<<<-- error on this line
        token.id = user.id;
        token.expiration = Math.floor(
          currentDateInSeconds + expirateDateInSeconds,
        );
      }
      return token;
    },
  },

我需要扩展类型User|适配器用户?我需要做什么?

nvbavucw

nvbavucw1#

您需要扩展/覆盖next-auth中的基本对象

declare module 'next-auth' {
  /**
   * Returned by `useSession`, `getSession` and received as a prop on the `SessionProvider` React Context
   */
  interface Session {
    user: SessionUser; // My User with the session token
    expires: string;
  }

  interface User extends EnterpriseUser {}
}

相关问题