project_next_14_ai_prompt_sharing icon indicating copy to clipboard operation
project_next_14_ai_prompt_sharing copied to clipboard

Can't Log-in with other accounts

Open CarrioliDante opened this issue 1 year ago • 1 comments

I'm having an issue; it doesn't allow me to log in with different users, and it doesn't save them in the database with callbacks. When I use callbacks, it allows me to log in with different accounts but doesn't let me save new prompts.

CarrioliDante avatar Dec 04 '23 05:12 CarrioliDante

  1. copy the code below and past in your [...nextauth] router.js

import NextAuth from 'next-auth'; import GoogleProvider from 'next-auth/providers/google';

import User from '@models/user'; import { connectToDB } from '@utils/database';

const handler = NextAuth({ providers: [ GoogleProvider({ clientId: process.env.GOOGLE_ID, clientSecret: process.env.GOOGLE_CLIENT_SECRET, }) ], callback: { async session({ session }) {

  const sessionUser = await User.findOne({ email: session.user.email });
  session.user.id = sessionUser._id.toString();

  return session
},
async signIn({ user, account, profile, email, credentials }) {
  try {
    await connectToDB();
    const userExists = await User.findOne({ email: profile?.email });
    // if not, create a new document and save user in MongoDB
    if (userExists === null) {
      await User.create({
        email: profile?.email,
        username: profile?.name.replace(/\s+/g, '').toLowerCase(),
        image: user.image
      })
    }

    return true
  } catch (error) {
    console.log(error);
    return false
  }
  
} 

} })

export { handler as GET, handler as POST }

  1. in your next.config.js copy the code and paste below // next.config.js const nextConfig = { images: { domains: ['lh3.googleusercontent.com'], }, };

module.exports = nextConfig;

aabu960 avatar Dec 17 '23 21:12 aabu960