Save user to database
This commit is contained in:
+25
-6
@@ -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;
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user