Next Auth: Redirect page before success login

Viewed 500

I want make a custom login use next Auth.

What I want is, after check my email and password true, I want redirect to google auth page and after google auth true I want set the token to session and redirect to home. Is it possible to make it like that?

//This is the flow

Login -> google Auth -> Home

This is login page

//Front End 

const handler = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setLoading(true);
    const res = await signIn("credentials", {
      redirect: false,
      data: emailRef.current?.value,
      password: passwordRef.current?.value,
    });
    if (res?.error) {
      toast.error(res?.error);
      setLoading(false);
    } else {
      Router.replace("/");
      Router.events.on("routeChangeComplete", success);
    }
  };

This is the API Page

//API

export default NextAuth({
  session: {
    jwt: true,
  },

  providers: [
    Providers.Credentials({
      async authorize(credentials: credentialsData, req: NextApiRequest) {
        let client;
        try {
          client = await ConnectDatabase();
        } catch (error) {
          throw new Error("Failed connet to database.");
        }

        const checkEmail = await client
          .db()
          .collection("users")
          .findOne({ email: credentials.data });
        const checkPhone = await client
          .db()
          .collection("users")
          .findOne({ phone: credentials.data });

        let validData = {
          password: "",
          email: "",
        };

        if (!checkEmail && !checkPhone) {
          client.close();
          throw new Error("Email atau No HP tidak terdaftar.");
        } else if (checkEmail) {
          validData = checkEmail;
        } else if (checkPhone) {
          validData = checkPhone;
        }

        const checkPassword = await VertifyPassword(
          credentials.password,
          validData.password
        );
        if (!checkPassword) {
          client.close();
          throw new Error("Password Salah.");
        }
        client.close();

        return validData;
      },
    }),
  ],
  callbacks: {
    async session(session) {
      const data = await getSelectedUser(session.user!.email!);
      session.user = data.userData;
      return Promise.resolve(session);
    },
  },
});

In above Example I don't use google auth, so after login success it immediately redirects to home

0 Answers
Related