mongodb 为什么在使用next-auth和凭据时,我的会话只有用户的电子邮件?

wfauudbj  于 11个月前  发布在  Go
关注(0)|答案(1)|浏览(168)

我使用next-auth和凭据来登录用户,如下所示:

import NextAuth from "next-auth"
import CredentialsProvider from "next-auth/providers/credentials"
import { connectToDb } from "@utils/database"
import User from "@models/user"
import bcrypt from "bcrypt"

export const authOptions = {
    providers: [
        CredentialsProvider({
            name: "credentials",
            credentials: {
                email: { label: "Email", type: "email", placeholder: ""},
                password: { label: "Password", type: "password", placeholder: ""}
            },

            async authorize(credentials) {
                const {email, password} = credentials
                
                try {
                    await connectToDb()

                    const user = await User.findOne({ email })

                    if(!user) {
                        return null
                    }

                    const passwordsMatch = await bcrypt.compare(password, user.password)
                    if(!passwordsMatch) {
                        return null
                    }

                    return user
                } catch (error) {
                    console.log(error)
                    return null
                }
            }
        })
    ],
    session: {
        strategy: "jwt",
    },
    
    secret: process.env.NEXTAUTH_SECRET,
    pages: {
        signIn: '/login'
    }
}

const handler = NextAuth(authOptions)

export { handler as GET, handler as POST}

字符串
登录工作,当我console.log(user)在auth路由,它显示了所有的数据(firstName,lastName,email,phoneNumber,_id,password),但当我去console.log在 Jmeter 板上的会话一旦他们登录,会话唯一的东西是用户的电子邮件.这是我的 Jmeter 板页面:

'use client'

import { useSession } from 'next-auth/react'

const DashboardPage = () => {

    const { data: session, status} = useSession()
    console.log('dashboard', session)

  return (
    <div>
        <h1>Dashboard</h1>
        <h3>{session?.user?.email}</h3>
    </div>
  )
}

export default DashboardPage


有人知道为什么会话只有电子邮件而没有firstName,lastName等吗?或者我应该如何访问它们?这是console.log在 Jmeter 板页面中显示的内容:

dashboard 
Object { user: {…}, expires: "2023-11-24T03:18:28.585Z" }
​
expires: "2023-11-24T03:18:28.585Z"
​
user: Object { email: "[email protected]" }
​​
email: "[email protected]"
​​
<prototype>: Object { … }
​
<prototype>: Object { … }

e0bqpujr

e0bqpujr1#

在下一个认证会话总是只采取用户电子邮件默认情况下,如果你想添加任何其他东西,你将不得不编辑回调对象中的会话对象这里是一个例子,我如何添加(isAdmin和图像和id和提供者)的会话在下一个认证,你可以改变它添加任何你想要的用户对象,没有得到从数据库返回

import NextAuth from 'next-auth'
import CredentialsProvider from "next-auth/providers/credentials"
import { sendVerificationEmail } from '../../../middleware/emailService';

import dbConnect from '../../../lib/dbConnect';
import User from '../../../models/User';
import { compare, hash } from 'bcryptjs';
import crypto from 'crypto';

import axios from 'axios';

export const authOptions = {
  providers: [
    CredentialsProvider({
      name: 'Credentials',
      async authorize(credentials, req){

        const ress  = await axios.get('http://localhost:3000/api/ip-return')
        console.log(ress.data)
        if(ress.data.ok){
          await dbConnect()
          
          //check user existance
          const result = await User.findOne({email: credentials.email}).select('+password')
          if(!result){
            throw new Error('No user Found With Email Please Sign Up!')
          }

          if(result.verified){
            //compare password
            const checkPassword = await compare(credentials.password, result.password)
            if(!checkPassword || result.email !== credentials.email){
              throw new Error("Email or Password dosen't match")
            }

            return result
          }else{
            sendVerificationEmail(result.email, result.verificationToken)
            throw new Error("Please Confirm Your Email!")
          }
        }else{
          throw new Error(ress.data.message)
        }

      }
    })
  ],
  callbacks:{
    jwt: async ({ token, user }) =>{

      if (user) {
        token.uid = user;
      }

      return token
    },
    session: async ({ session, token }) => {
        // here we put session.useData and put inside it whatever you want to be in the session
        // here try to console.log(token) and see what it will have 
        // sometimes the user get stored in token.uid.userData
        // sometimes the user data get stored in just token.uid
        session.userData = {
          isAdmin: token.uid.userData.isAdmin,
          id: token.uid.userData._id,
          image:token.uid.userData.image,
          provider:token.uid.userData.provider
        }

      return session;
    },
  },
  strategy: "jwt",
  secret: process.env.NEXT_AUTH_SECRET,
  database: process.env.DB_URL  
}

export default NextAuth(authOptions)

字符串

相关问题