簡體   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