由于[.nextauth.ts]被触发重新编译,NextJS和NextAuth会话用户对象丢失 [英] NextJS and NextAuth session user object getting lost due to [...nextauth.ts] getting triggered to be recompiled

查看:37
本文介绍了由于[.nextauth.ts]被触发重新编译,NextJS和NextAuth会话用户对象丢失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习NextJS和NextAuth,并且已经使用我自己的登录页面实现了一个凭据登录,它在Session对象包含我的用户模型的位置工作(目前包含包括密码在内的所有内容,但显然它不会一直这样)。

我可以刷新页面并维护会话,但是,如果我离开一两分钟,然后刷新会话中的User对象,即使我的会话应该要到下个月才会过期,它也会成为默认设置。

下面是我的[.nextauth.tsx]文件

import NextAuth, {NextAuthOptions} from 'next-auth'
import Providers from 'next-auth/providers'
import { PrismaClient } from '@prisma/client'
import {session} from "next-auth/client";

let userAccount = null;

const prisma = new PrismaClient();

const providers : NextAuthOptions = {
    site: process.env.NEXTAUTH_URL,
    cookie: {
        secure: process.env.NODE_ENV && process.env.NODE_ENV === 'production',
    },
    redirect: false,
    providers: [
        Providers.Credentials({
            id: 'credentials',
            name: "Login",
            async authorize(credentials : any) {
                const user = await prisma.users.findFirst({
                    where: {
                        email: credentials.email,
                        password: credentials.password
                    }
                });

                if (user !== null)
                {
                    userAccount = user;
                    return user;
                }
                else {
                    return null;
                }
            }
        })
    ],
    callbacks: {
        async signIn(user, account, profile) {
            console.log("Sign in call back");
            console.log("User Is");
            console.log(user);
            if (typeof user.userId !== typeof undefined)
            {
                if (user.isActive === '1')
                {
                    console.log("User credentials accepted")
                    return user;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                console.log("User id was not found so rejecting signin")
                return false;
            }
        },
        async session(session, token) {
            //session.accessToken = token.accessToken;
            if (userAccount !== null)
            {
                session.user = userAccount;
            }
            console.log("session callback returning");
            console.log(session);
            return session;
        },
        /*async jwt(token, user, account, profile, isNewUser) {
            console.log("JWT User");
            console.log(user);
            if (user) {
                token.accessToken = user.token;
            }
            return token;
        }*/
    }
}

const lookupUserInDb = async (email, password) => {
    const prisma = new PrismaClient()
    console.log("Email: " + email + " Password: " + password)
    const user = await prisma.users.findFirst({
        where: {
            email: email,
            password: password
        }
    });
    console.log("Got user");
    console.log(user);
    return user;
}

export default (req, res) => NextAuth(req, res, providers).

我从自定义表单触发登录,如下所示

signIn("credentials", {
            email, password, callbackUrl: `${window.location.origin}/admin/dashboard`, redirect: false }
        ).then(function(result){
            if (result.error !== null)
            {
                if (result.status === 401)
                {
                    setLoginError("Your username/password combination was incorrect. Please try again");
                }
                else
                {
                    setLoginError(result.error);
                }
            }
            else
            {
                router.push(result.url);
            }
            console.log("Sign in response");
            console.log(result);
        });

登录从Next-auth/Client导入

my_app.js如下:

export default function Blog({Component, pageProps}) {
    return (
        <Provider session={pageProps.session}>
            <Component className='w-full h-full' {...pageProps} />
        </Provider>
    )

}

然后它在登录后重定向到的页面具有以下内容:(不确定这实际上除了获取活动会话以便我可以从前端引用它之外是否还有其他作用)

const [session, loading] = useSession()

我登录时,[.nextauth.tsx]中的session回调返回以下内容:

session callback returning
{
  user: {
    userId: 1,
    registeredAt: 2021-04-21T20:25:32.478Z,
    firstName: 'Some',
    lastName: 'User',
    email: 'someone@example',
    password: 'password',
    isActive: '1'
  },
  expires: '2021-05-23T17:49:22.575Z'
}

然后,出于某种原因,从PhpStorm内部运行npm run dev的终端随后输出

event - build page: /api/auth/[...nextauth]
wait  - compiling...
event - compiled successfully

但我没有更改任何内容,即使我更改了应用程序,也不应该触发会话被删除,但在此之后,会话回调将直接返回以下内容:

session callback returning
{
  user: { name: null, email: 'someone@example.com', image: null },
  expires: '2021-05-23T17:49:24.840Z'
}

所以我有点困惑,似乎我的代码正在工作,但也许PhpStorm触发了重新编译,然后会话被清除,但正如我上面所说的,一定要进行更改,重新编译的版本不应该触发修改会话。

**更新**

我已经做了一个测试,其中我构建了一个版本,开始时是一个生产版本,我可以根据需要刷新页面,会话也会得到维护,所以我已经证明了我的代码工作得很好。因此,它看起来与PhpStorm确定某些内容已更改并在没有任何更改的情况下执行重新编译有关。

推荐答案

我终于找到解决方案了。

我在提供程序选项中添加了以下内容:

session: {
        jwt: true,
        maxAge: 30 * 24 * 60 * 60

    }

我更改的会话回调如下:

async session(session, token) {
    //session.accessToken = token.accessToken;
    console.log("Session token");
    console.log(token);
    if (userAccount !== null)
    {
        session.user = userAccount;
    }
    else if (typeof token !== typeof undefined)
    {
        session.token = token;
    }
    console.log("session callback returning");
    console.log(session);
    return session;
}

JWT回调如下:

async jwt(token, user, account, profile, isNewUser) {
    console.log("JWT Token User");
    console.log(token.user);
    if (typeof user !== typeof undefined)
    {
         token.user = user;
    }
    return token;
}

基本上我误解了我需要使用JWT回调,在第一次调用此回调时,将使用从登录回调设置的用户模型,以便我可以将其添加到令牌中,然后在会话回调中将其添加到会话中。

由于对JWT的后续请求中的问题,未设置User参数,因此我将令牌User对象设置为未定义,这就是我的会话被清空的原因。

我不明白为什么我在将其作为生产版本运行时似乎没有获得该行为。

这篇关于由于[.nextauth.ts]被触发重新编译,NextJS和NextAuth会话用户对象丢失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆