繁体   English   中英

定制 session next js next-auth

[英]custom session next js next-auth

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

// 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

这在客户端

// 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,
    },
  };
};

但在客户端我收到警告

Property 'role' does not exist on type '{ name?: string; email?: string; image?: string; 

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

有人可以帮我解决吗?

不确定您是否找到了解决方法,但您还需要配置 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; }, },

解释事情。 jwt function always runs before session, so whatever data you pass to jwt token will be available on session function and you can do whatever you want with it. 在 jwt function 我检查是否有用户,因为这仅在您登录时才返回数据。

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

我创建了 /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;
    };
  }
}

然后我不得不将它添加到我的 tsconfig.json

  "include": ["next-env.d.ts", "types/**/*.ts", "**/*.ts", "**/*.tsx"],

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM