使用 Google Provider 进行 NextAuth 需要打开一个弹出窗口

问题描述 投票:0回答:1

这是我的 app/api/auth/[...nextauth]/route.js,我希望当用户登录时它不会重定向到新页面,而不是打开一个带有相同 Google 窗口的小弹出窗口,这样用户就留在网站上。

import NextAuth from 'next-auth'
import GoogleProvider from 'next-auth/providers/google'
import sendEmailToUser from '@/utils/email'

export const authOptions = {
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    }),
  ],
  callbacks: {
    async signIn({ user, account, profile, email, credentials }) {
      if (user && user.email) {
        try {
          await sendEmailToUser(user.email);
          return true; 
        } catch (error) {
          console.error('Error saving user:
          return false; 
        }
      }
      return true;
    },
  },
}

export const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };

{redirect:false} 不起作用。我不需要新页面,我只需要在弹出窗口中显示相同的 Google 登录页面。有哪些方法可以做到?

next.js google-oauth next-auth
1个回答
0
投票

这个问题可以分为两部分:

  1. 打开新窗口
  2. 在新窗口登录

对于第一部分,您可以使用与此类似的函数:

function popupCenter(url, title) {
  const dualScreenLeft = window.screenLeft ?? window.screenX;
  const dualScreenTop = window.screenTop ?? window.screenY;

  const width =
    window.innerWidth ?? document.documentElement.clientWidth ?? screen.width;

  const height =
    window.innerHeight ??
    document.documentElement.clientHeight ??
    screen.height;

  const systemZoom = width / window.screen.availWidth;

  const left = (width - 500) / 2 / systemZoom + dualScreenLeft;
  const top = (height - 550) / 2 / systemZoom + dualScreenTop;

  const newWindow = window.open(
    url,
    title,
    `width=${500 / systemZoom},height=${550 / systemZoom
    },top=${top},left=${left}`
  );

  newWindow?.focus();
};

这只是在用户屏幕中央打开一个新窗口,然后将焦点设置到它。现在,是时候构建打开的窗口了。

// /app/google-login/page.js

'use client'

export default function SignInPopUpPage() {
    const { data: session, status } = useSession()

    useEffect(() => {
        if (!(status === "loading") && !session) {
            signIn("google");
        }
        if (session) {
            window.close();
        }
    }, [session, status]);

    return (
        <div
            style={{
                width: "100vw",
                height: "100vh",
                position: "absolute",
                left: 0,
                top: 0,
                background: "white",
            }}
        />
    );
};

最后,让您的登录按钮调用函数

popupCenter
,并使用
SignInPopUpPage
路由作为 URL。

© www.soinside.com 2019 - 2024. All rights reserved.