Save user to database

This commit is contained in:
Brad Traversy
2024-07-10 10:37:27 -04:00
parent 81d75e7bb9
commit f20f0430f4
+24 -5
View File
@@ -1,3 +1,6 @@
import connectDB from '@/config/database';
import User from '@/models/User';
import GoogleProvider from 'next-auth/providers/google';
export const authOptions = {
@@ -18,15 +21,31 @@ export const authOptions = {
// 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;
},
},
};