簡體   English   中英

如何在 next-auth 中向客戶端 API 添加數據?

[英]How do I add data to the client API in next-auth?

我目前正在使用 next-auth 使用憑據提供程序進行授權,我有會話工作並且用戶可以登錄等。但是,在 session 上,我需要使用客戶端 API 傳遞一些數據,用戶,名字,姓氏,用戶名和 email。

默認情況下,客戶端 API 傳遞,名稱,email 和圖像,但是,如何更改它以添加上述數據,這是我到目前為止所擁有的。

index.js

import { useState, useEffect  } from 'react';
import { getSession } from 'next-auth/client'
import { useRouter } from 'next/router';
import Link from 'next/link';
import Head from 'next/head';
import Sidebar from '../components/Sidebar';

export default function Dashboard({ user}) {
  return (
    <div>
      <Head>
        <title>Dashboard</title>
      </Head>

      <Sidebar />

      <section className="content dashboard-content">
        <h1>Dashboard</h1>

        <h3>Welcome to Ellis development {user.firstname }</h3>
      </section>
    </div>
  )
}

export async function getServerSideProps(ctx) {
  const session = await getSession(ctx);
  
  if (!session) {
    return {
      redirect: {
        destination: '/dashboard/auth/login',
        permanent: false
      },
    }
  }

  console.log(session);

  return {
    props: {
      user: {
        firstname: session.user.firstname,
        lastname: session.user.lastname,
        username: session.user.username,
        email: session.user.email,
      }
    },
  }
}

[...nextauth.js]

import NextAuth from 'next-auth';
import Providers from 'next-auth/providers';

import { verifyPassword } from '../../../lib/auth';
import { connectToDatabase } from '../../../lib/mongodb';

export default NextAuth({
  session: {
    jwt: true,
  },
  providers: [
    Providers.Credentials({
      async authorize(credentials) {
        const client = await connectToDatabase();
        const usersCollection = client.db().collection('users');

        const user = await usersCollection.findOne({
          email: credentials.email,
        });

        if (!user) {
          client.close();
          throw new Error('No user found!');
        }

        const isValid = await verifyPassword(
          credentials.password,
          user.password
        );

        if (!isValid) {
          client.close();
          throw new Error('Could not log you in!');
        }

        client.close();

        return {
          firstname: user.firstname,
          lastname: user.lastname,
          username: user.username,
          email: user.email
        };
      },
    }),
  ],
});

任何幫助都會很棒,謝謝。

編輯

我已將以下內容添加到 [...next-auth] 頁面

callbacks: {
  session: async (session) => {
    if (!session) return;

    const client = await connectToDatabase();
    const usersCollection = client.db().collection('users');
    
    const userData = await usersCollection.findOne({
      email: session.user.email,
    });

    return {
      session: {
        user: {
          id: userData._id,
          firstname: userData.firstname,
          lastname: userData.lastname,
          username: userData.username,
          email: userData.email
        }
      }
    };
  },
},

這給了我以下結果

{
  session: {
    user: {
      id: '61a107f29ca24c12146d1b22',
      firstname: 'Ben',
      lastname: 'Bagley',
      username: 'benbagley',
      email: 'benbagley@pm.me'
    }
  }
}

所以我現在有了我需要的值,但是,我如何 go 將數據渲染到頁面上我現在有以下

import { getSession } from 'next-auth/client'
import Head from 'next/head';
import Sidebar from '../components/Sidebar';

export default function Dashboard({ session }) {
  return (
    <div>
      <Head>
        <title>Dashboard</title>
      </Head>

      <Sidebar />

      <section className="content dashboard-content">
        <h1>Dashboard</h1>

        <h3>Welcome {session.user.firstname} to Ellis development</h3>
      </section>
    </div>
  )
}

export async function getServerSideProps(ctx) {
  const session = await getSession(ctx);
  
  if (!session) {
    return {
      redirect: {
        destination: '/dashboard/auth/login',
        permanent: false
      },
    }
  }

  console.log(session);

  return {
    props: {
      session: {
        user: {
          id: session.user.id,
          firstname: session.user.firstname,
          lastname: session.user.lastname,
          username: session.user.username,
        }
      }
    },
  }
}

但是,我收到TypeError: Cannot read properties of undefined (reading 'id')

您應該檢查下一個身份驗證回調。 用戶 object 將包含 email、圖像和名稱。 You can use it to fetch an internal api or so, and append the info to the session object which will be encoded in the jwt.

callbacks: {
        session: async (session, user) => {
            if (!session) return;
            const userServerData = fetch(...); // or some internal logic
            
            session.user.firstName = userServerData.firstName;
            session.user.lastname = userServerData.lastname;
            session.user.username = userServerData.username;
            
            return Promise.resolve(session);
        },
    },

這就是我在項目中解決相同問題的方法

第 1 步:將以下內容添加到...[nextauth].ts

  pages: {
    // signIn: '/auth/signin',
    // signOut: '/auth/signout',
    // error: '/auth/error', // Error code passed in query string as ?error=
    // verifyRequest: '/auth/verify-request', // (used for check email message)
    newUser: '/auth/newuser' // New users will be directed here on first sign in 
  },

第 2 步:現在您可以更新用戶數據並發布到您的 api

'/auth/newuser.ts'

    React.useEffect(() => {
   

       post updated user data to -> "/api/auth/newuserwelcome"

      }, [])

//
Step 3: create api endpoint to save updated user data to DB
    /api/auth/newuserwelcome.ts
      

這里的問題有兩個,

a) 不使用適當的回調來添加和覆蓋下一個身份驗證 api,例如:

callbacks: {
  session: async (session) => {
    if (!session) return;

    const client = await connectToDatabase();
    const usersCollection = client.db().collection('users');
    
    const userData = await usersCollection.findOne({
      email: session.user.email,
    });

    return {
      session: {
        user: {
          id: userData._id,
          firstname: userData.firstname,
          lastname: userData.lastname,
          username: userData.username,
          email: userData.email
        }
      }
    };
  },
},

現在這是傳遞值,下一個問題支持......

b) 傳遞道具時不使用擴展運算符

export async function getServerSideProps(ctx) {
  const session = await getSession(ctx);
  
  if (!session) {
    return {
      redirect: {
        destination: '/dashboard/auth/login',
        permanent: false
      },
    }
  }

  return {
    props: {
      ...session,
    }
  }
}

調用...session獲得所有返回 object 並允許它像session.user.firstname這樣傳遞,非常方便。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM