diff --git a/utils/authOptions.js b/utils/authOptions.js index 2e59c1b..aa96976 100644 --- a/utils/authOptions.js +++ b/utils/authOptions.js @@ -1,3 +1,6 @@ +import connectDB from '@/config/database'; +import User from '@/models/User'; + import GoogleProvider from 'next-auth/providers/google'; export const authOptions = { @@ -15,18 +18,34 @@ export const authOptions = { }), ], callbacks: { - // Invoked on successful sign in + // Invoked on successful signin async signIn({ profile }) { // 1. Connect to database - // 2. Check if user exists in database - // 3. If not, create user in database - // 4. return true to allow sign in + await connectDB(); + // 2. Check if user exists + const userExists = await User.findOne({ email: profile.email }); + // 3. If not, then add user to database + if (!userExists) { + // Truncate user name if too long + const username = profile.name.slice(0, 20); + + await User.create({ + email: profile.email, + username, + image: profile.picture, + }); + } + // 4. Return true to allow sign in + return true; }, - // Session callback function that modifies the session object + // Modifies the session object async session({ session }) { // 1. Get user from database - // 2. Assign user id from database to session + const user = await User.findOne({ email: session.user.email }); + // 2. Assign the user id to the session + session.user.id = user._id.toString(); // 3. return session + return session; }, }, };