reactjs 无法为用户会话Next-Auth创建自定义角色

j0pj023g  于 2023-03-29  发布在  React
关注(0)|答案(1)|浏览(97)

我正在使用NextJsnext-auth,并试图创建一个自定义角色和ID,这样我就可以像往常一样将其与用户凭据沿着保存在会话中。它工作正常,但只有当用户使用凭据提供程序注册时。
我的问题是,当与Google提供商和其他第三方提供商签署时,如何将用户凭据沿着自定义角色一起保存到会话中?
我的代码

import NextAuth from 'next-auth/next'
import GoogleProvider from 'next-auth/providers/google'
import CredentialsProvider from 'next-auth/providers/credentials'

import db from '@/database/connect'
import Users from '@/database/modals/users'

import { compare } from 'bcryptjs'

import profilePictures from '../../../data/profilePictures.json'

const authOptions = {
    providers: [
        GoogleProvider({
            clientId: process.env.GOOGLE_ID,
            clientSecret: process.env.GOOGLE_SECRET,
        }),
        CredentialsProvider({
            name: 'Credentials',
            async authorize(credentials, req){
                await db.connect()

                // Check if user exist
                const results = await Users.findOne({email: credentials.email})
                if(!results){
                    throw new Error('No User Found With That Email!')
                }
                // Compare password
                const checkPassword = await compare(credentials.password, results.password)
                if(!checkPassword || results.email !== credentials.email){
                    throw new Error("Email Or Password Doesn't Match")
                }
                
                await db.disconnect()
                return results
            }
        })
    ],
    session: {
        strategy: 'jwt'
    },
    callbacks: {
        // Google signin function for saving the user info into the DB
        async signIn({ user }){
            // Check if user exist
            await db.connect()
            const results = await Users.findOne({email: user?.email})
            await db.disconnect()
            
            // Create the User and Post Into DB
            if(!results){
                try{
                    const userSchema = {
                        name: user?.name || '',
                        email: user?.email || '',
                        password: 'Signed using google',
                        picture: profilePictures[Math.floor(Math.random()*profilePictures.length)].path || '/images/TpAnime.jpg',
                        bookMark: {
                            animeList: [],
                            watchList: []
                        },
                        banned: false,
                        admin: false,
                    }
                    await db.connect()
                    Users.create(userSchema)
                }catch(err){
                    throw new Error("Something Went Wrong!, Try Signing With Another Account.")
                }
                return user
            }
            
        },
        
        // Checking and adding the some props from DB into the jwt token
        async jwt({token, user}){
            if(user?._id) token._id = user._id
            if(typeof user?.admin == "boolean") token.admin = user.admin
            if(typeof user?.banned == "boolean") token.banned = user.banned
            return token
        },
        // And then here I'm sending it to the session from the jwt
        async session({session, token}){
            if(token?._id) session.user._id = token._id
            if(typeof token?.admin == "boolean") session.user.admin = token.admin
            if(typeof token?.banned == "boolean") session.user.banned = token.banned
            return session
        } 
    },
    secret: process.env.NEXT_PUBLIC_JWT_SECRET,
}
export default NextAuth(authOptions)
afdcj2ne

afdcj2ne1#

在用户数据库模式中,您应该有一个角色属性。通常默认值为“user”。例如,对于mongoose

role: {
    type: String,
    default: "user",
  },

现在,在credentialsProviderauthorize函数中,当您获取user时,user将已经具有role属性,因此在jwt回调中

jwt: async ({ token, user }) => {
   user && (token.user = user);
   return Promise.resolve(token);
},

当您写入令牌时,它将已经具有user.role属性

相关问题