如何在 NEXT-AUTH 中添加附加数据以登录 Promise 返回?

A.A*_*kov 5 next.js next-auth

这就是我们在网站上授权用户的方式

signIn('credentials', {
 phoneNumber: verifiedPhone,
 code: otp.data,
 type: 'phone',
 redirect: false,
}).then((res) => {
 console.log(res) // default response {error,status,ok,url}

 // How can i add additional data to this response, in my case user session

 // if (!res.user.name) openModal('add_name')
 // else toast.success('You are all set!')
});
Run Code Online (Sandbox Code Playgroud)

默认情况下,signIn 将返回一个 Promise,解析为:

{
 error: string | undefined
 status: number
 ok: boolean
 url: string | null
}
Run Code Online (Sandbox Code Playgroud)

我们想将自定义数据添加到此承诺回报中。

实际上我们想要做的是让用户登录,如果用户是新用户,他/她应该没有用户名,因此会打开一个模式,输入他/她的用户名,然后我们更新下一个身份验证会话。

[...nextauth].js

...
async authorize(credentials, req) {
   // check the code here
   const res = await requests.auth.signInEnterOtp(
    credentials.phoneNumber,
    credentials.code,
    credentials.type
   );

   if (!res.ok) return null
   return {
    user: {
     access_token: res.data?.access_token,
     token_type: res.data?.token_type,
     expires_at: res.data?.expires_at,
     user_info: {
      id: res.data?.user.id,
      name: res.data?.user.name,
      phone: res.data?.user.phone,
      user_type: res.data?.user.user_type,
     },
   },
 };
},
...
Run Code Online (Sandbox Code Playgroud)

A.A*_*kov 7

我最终是这样想的:

...
.then(async (res) => {
 const session = await getSession()
 ...
})
...
Run Code Online (Sandbox Code Playgroud)

但是我还有另一个问题,它是用新用户名更新会话(


编辑

我找到了一种在登录后更改会话的方法

[...nextauth].js

...
async authorize(credentials, req){
 ...
 if(credentials.type === 'update_name'){
  const session = await getSession({ req })
  return session.user.name = credentails.name
 } 
 ...
}
Run Code Online (Sandbox Code Playgroud)

在客户端:

signIn('credentials', {
 name: newName,
 type: 'update_name',
 redirect: false
)
Run Code Online (Sandbox Code Playgroud)