【问题标题】:Next Auth: Extending User schema to include new fieldsNext Auth:扩展用户架构以包含新字段
【发布时间】:2022-12-25 00:00:31
【问题描述】:

我有一个带有 Next Auth v4 的打字稿应用程序,它使用 GithubProvider + MongoDBAdapter(这样我就可以访问数据库文档用户、配置文件和帐户)。

问题是我需要向用户架构添加一个新字段,例如 role 字段。

我在网上找到的大多数结果都指出,在 v4 中,您需要向您的提供商配置一个函数 profile

所以我做到了!这是我的 [...nextauth].ts

import NextAuth from 'next-auth'
import GithubProvider from 'next-auth/providers/github'
import { MongoDBAdapter } from '@next-auth/mongodb-adapter'
import connectDB from 'lib/mongooseConnect'
import mongoose from 'mongoose'

connectDB()

export const authOptions = {
   // Configure one or more authentication providers
   providers: [
      GithubProvider({
         clientId: process.env.GITHUB_ID,
         clientSecret: process.env.GITHUB_SECRET,
         //@ts-ignore
         profile(profile) {
            return {
               id: profile.id,
               name: profile.name,
               email: profile.email,
               image: profile.avatar_url,
               role: 'USER',
            }
         },
      }),
      // ...add more providers here
   ],
   adapter: MongoDBAdapter(
      new Promise((resolve) => resolve(mongoose.connection.getClient()))
   ),
}

export default NextAuth(authOptions)

这允许我在用户文档中填充默认字段...但是当我尝试通过 session.user.role 访问它时,我得到一个 TS 错误作为未定义的结果。

例如,这段代码不起作用:

import React from 'react'
import { useSession } from 'next-auth/react'
import { useRouter } from 'next/router'

import useProfileByOwner from 'hooks/api/useProfileByOwner'
import { IProfile } from 'models/Profile'

const UserContext = React.createContext<Value>({
   profile: undefined,
   isSelected: undefined,
})

export const UserProvider = ({ children }) => {
   const { data: session } = useSession()
   const { data: ownProfile } = useProfileByOwner(session?.user?.email)
   const router = useRouter()

   //@ts-ignore
   const isSelected =
      router.query.slugOrId === ownProfile?.slug ||
      router.query.slugOrId === ownProfile?._id ||
      //@ts-ignore
      session?.user?.role === 'ADMIN'

   return (
      <UserContext.Provider value={{ profile: ownProfile, isSelected }}>
         {children}
      </UserContext.Provider>
   )
}

type Value = {
   profile: IProfile
   isSelected: boolean
}

export default UserContext

【问题讨论】:

    标签: javascript reactjs typescript next.js next-auth


    【解决方案1】:

    如果您正在搜索在集合中添加用户角色字段,您可能会这样做...... 使用用户角色更新用户架构 然后在 [...nextauth] 中添加自定义回调 callbacks: { async session({ session, token, user }) { session.user.role = user.role; // Add role value to user object so it is passed along with session return session; } }, 然后你可以在你的页面中调用会话..... if (session &amp;&amp; session.user.role === "admin") { return (........................

    问候

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-15
      • 2015-12-27
      • 2011-09-27
      • 1970-01-01
      • 2022-11-12
      • 1970-01-01
      • 2023-03-05
      • 2023-03-07
      相关资源
      最近更新 更多