【发布时间】: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